Search completed in 1.34 seconds.
4895 results for "document":
Your results are loading. Please wait...
Document.createDocumentFragment() - Web APIs
The usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its children. Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). ...
... which DOM nodes can be added to build an offscreen DOM tree. Syntax var fragment = document.createDocumentFragment(); Value A newly created, empty, DocumentFragment object, which is ready to have nodes inserted into it. Usage notes DocumentFragments are DOM Node objects which are never part of the main DOM tree. The usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its children. Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Historically, using document fragments could result in better performance. You can ...
... then append the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its children. Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Historically, using document fragments could result in better performance. ...
...And 6 more matches
DocumentTimeline.DocumentTimeline() - Web APIs
Currently the only supported option is the originTime member which specifies the zero time for the documentTimeline as a real number of milliseconds relative to the navigationStart moment of the active document for the current browsing context. Examples We could share a single documentTimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. ...
...) constructor of the Web Animations API creates a new instance of the DocumentTimeline object associated with the active document of the current browsing context. Syntax var sharedTimeline = new DocumentTimeline(options); Parameters options An object specifying options for the new timeline. Currently the only supported option is the originTime member which specifies the zero time for the documentTimeline as a real number of milliseconds relative to the navigationStart moment of the active document for the current browsing context. Examples We could share a single documentTimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. This bit of code would start all the cats animating 500 milliseconds into their animations: v...
...s a real number of milliseconds relative to the navigationStart moment of the active document for the current browsing context. Examples We could share a single documentTimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. ...
...ng context. Examples We could share a single documentTimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. This bit of code would start all the cats animating 500 milliseconds into their animations: var cats = document.querySelectorAll('.sharedTimelineCat'); cats = Array.prototype.slice.call(cats); var sharedTimeline = new DocumentTimeline({ originTime: 500 }); cats.forEach(function(cat) { var catKeyframes = new KeyframeEffect(cat, keyframes, timing); var catAnimation = new Animation(catKeyframes, sharedTimeline); catAnimation.play(); }); Specifications Specification Status Comment Web AnimationsThe definition of 'DocumentTimeline()' in that specification. Working Draft Editor's draft...
Document.documentElement - Web APIs
Document.documentElement returns the Element that is the root element of the document (for example, the <html> element for HTML documents). Syntax const element = document.documentElement Example const rootElement = document.documentElement; const firstTier = rootElement.childNodes; // firstTier is a NodeList of the direct children of the root element // such as <head> and <body> for (const child of firstTier) { // do something with each direct child of the root element } Notes For any non-empty HTML document, documentElement will always be an <html> element. For any non-empty XML document, documentElement will always be whatever element is the root element of the document. ...
... Living Standard ...
... child of firstTier) { // do something with each direct child of the root element } Notes For any non-empty HTML document, documentElement will always be an <html> element. For any non-empty XML document, documentElement will always be whatever element is the root element of the document. Specifications Specification Status Comment DOMThe definition of 'Document.documentElement' in that specification. Living Standard ...
Document.documentURIObject - Web APIs
This only works for privileged (UniversalXPConnect) scripts, including extension code. For web content this property doesn't have any special meaning and can be used just like any other custom property. Privileged code must be careful not to try getting or setting this property on a non-wrapped content object (e.g., on a wrappedJSObject of an XPCNativeWrapper). See bug 324464's comments for details. ...
...vileged (UniversalXPConnect) scripts, including extension code. For web content this property doesn't have any special meaning and can be used just like any other custom property. Privileged code must be careful not to try getting or setting this property on a non-wrapped content object (e.g., on a wrappedJSObject of an XPCNativeWrapper). See bug 324464's comments for details. Syntax var uri = document.documentURIObject; Example // Check that the URI scheme of the current tab in Firefox is 'http', // assuming this code runs in context of browser.xul let uriObj = content.document.documentURIObject; let uriPort = uriObj.port; if (uriObj.schemeIs('http')) { ... } Specifications Not part of any specification. ...
Document.documentURI - Web APIs
The documentURI read-only property of the Document interface returns the document location as a string. Syntax const uri = document.documentURI Example JavaScript document.getElementById("url").textContent = document.documentURI; HTML <p id="urlText"> URL:<br/> <span id="url">URL goes here</span> </p> Result Specifications Specification Status Comment DOMThe definition of 'documentURI' in that specification. Living Standard ...
Document.mozSyntheticDocument - Web APIs
The Document.mozSyntheticDocument property indicates whether or not the document is a synthetic one; that is, a document representing a standalone image, video, audio, or the like. Syntax var isSynthetic = document.mozSyntheticDocument; On return, isSynthetic is true if the document is a synthetic one; otherwise it's false. Example This can be useful if you have a contextual menu item you only want to display for synthetic documents (or, conversely, for documents that aren't synthetic). var isSynthetic = document.mozSyntheticDocument; if (isSynthetic) { /* insert your menu item here */ } Specifications Not part of any specification. ...
Document - Web APIs
Web › API › Document
The DOM tree includes elements such as <body> and <table>, among many others. It provides functionality globally to the document, like how to obtain the page's URL and create new elements in the document. ...
... The Document interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree. The DOM tree includes elements such as <body> and <table>, among many others. It provides functionality globally to the document, like how to obtain the page's URL and create new elements in the document. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px"...
...eight="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="188.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Node</text></a><polyline points="226,25 236,20 236,30 226,25" stroke="#D4DDE4" fill="none"/><line x1="236" y1="25" x2="266" y2="25" stroke="#D4DDE4"/><a xlink:href="/docs/Web/API/Document" target="_top"><rect x="266" y="1" width="80" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="306" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Document</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} The Document interface describes the co...
...And 57 more matches
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
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, the browser modifies its widget to allow editing. 12 contextmenu Deprecated, Global attribut...
... The hidden global attribute is a Boolean attribute indicating that the element is not yet, or is no longer, relevant. For example, it can be used to hide elements of the page that can't be used until the login process has been completed. 18 id Global attributes, HTML, Reference, Web, id The id global attribute defines an identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS). 19 inputmode Attribute, Editing, Forms, Global attributes, HTML, Input, Reference, Text, Web, contenteditable, global, inputmode, text input The inputmode global attribute is an enumerated attribute that hints at the type of data that might be entered by the u...
...ribute: readonly Attribute, Attributes, Constraint validation, Forms, required The Boolean readonly attribute, when present, makes the element not mutable, meaning the user can not edit the control. 47 HTML attribute: rel Attribute, Attributes, Constraint validation, Link, form, rel The rel attribute defines the relationship between a linked resource and the current document. Valid on <link>, <a>, <area>, and <form>, the supported values depend on the element on which the attribute is found. 48 HTML attribute: required Attribute, Attributes, Constraint validation, Forms, required The Boolean required attribute 49 HTML attribute: size Attribute, HTML, Input, Reference, Select The size attribute defines the width of the <input>...
...And 32 more matches
Manipulating documents - Learn web development
Previous Overview: Client-side web APIs Next When writing web pages and apps, one of the most common things you'll want to do is manipulate the document structure in some way. This is usually 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. ...
...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 think that such limitations are a bad thing, but browsers are locked down for good reasons, mostly centering around security. Imagine if a web site could get access...
...r 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 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 t...
...And 20 more matches
Document.cookie - Web APIs
Web › API › Document › cookie
It serves as a getter and setter for the actual values of the cookies. Syntax Read all cookies accessible from this location allCookies = document.cookie; In the code above allCookies is a string containing a semicolon-separated list of all cookies (i.e. key=value pairs). Note that each key and value may be surrounded by whitespace (space and tab characters): in fact, RFC 6265 mandates a single space after each semicolon, but some user agents may not abide by this. Write a new cookie document.cookie = newCookie; In the code above, newCookie is a string of form key=value. Note that you can only set/update a single cookie at a time using this method. ...
...a string of form key=value. Note that you can only set/update a single cookie at a time using this method. Consider also that: Any of the following cookie attribute values can optionally follow the key-value pair, specifying the cookie to set/update, and preceded by a semi-colon separator: ;path=path (e.g., '/', '/mydir') If not specified, defaults to the current path of the current document location. Note: Prior to Gecko 6.0, paths with quotes were treated as if the quotes were part of the string, instead of as if they were delimiters surrounding the actual path string. This has been fixed. ;domain=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 specificatio...
...s the path attribute the "directory" of the request URI is used. It also signals that the domain attribute must not be present, which prevents the cookie from being sent to other domains. For Chrome the path attribute must always be the origin. The dash is considered part of the prefix. These flags are only settable with the secure attribute. ...
...And 17 more matches
Document Object Model - Archive of obsolete content
When an XUL file is loaded, the tags are parsed and converted into a hierarchical document structure of nodes, one for each tag and block of text. The DOM structure may be examined and modified using 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. ...
... In Mozilla, the DOM may be accessed and manipulated using JavaScript. ...
... 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. ...
...And 14 more matches
SVG documentation index - SVG: Scalable Vector Graphics
Web › SVG › Index
tibility tables on SVG elements and attributes: 4 Content type NeedsTechnicalReview, SVG, Types, data types SVG makes use of a number of data types. This article lists these types along with their syntax and descriptions of what they're used for. 5 Linking Guide, SVG The target attribute on the SVG <a> element doesn't work in Mozilla Firefox 1.5. When SVG documents are embedded within a parent HTML document using the tag: 6 Namespaces crash course SVG, XML As an XML dialect, SVG is namespaced. It is important to understand the concept of namespaces and how they are used if you plan to author SVG content. Versions of SVG viewers prior to the release of Firefox 1.5 unfortunately paid scant attention to namespaces, but they are essential ...
...hrough the <image> element should use. 48 color-rendering SVG, SVG Attribute The color-rendering attribute provides a hint to the SVG user agent about how to optimize its color interpolation and compositing operations. 49 contentScriptType Deprecated, SVG, SVG Attribute The contentScriptType attribute specifies the default scripting language for the given document fragment on the <svg> element. 50 contentStyleType Deprecated, SVG, SVG Attribute The contentStyleType attribute specifies the style sheet language for the given document fragment on the <svg> element. 51 cursor SVG, SVG Attribute The cursor attribute specifies the mouse cursor displayed when the mouse pointer is over an element. 52 cx SVG,...
...r the animation that can constrain the active duration. 69 exponent NeedsCompatTable, SVG, SVG Attribute The exponent attribute defines the exponent of the gamma function. 70 externalResourcesRequired Deprecated, NeedsExample, SVG, SVG Attribute The externalResourcesRequired attribute specifies whether referenced resources that are not part of the current document are required for proper rendering of the given container or graphics element. 71 fill SVG, SVG Attribute The fill attribute has two different meanings. For shapes and text it's a presentation attribute that defines the color (or any SVG paint servers like gradients or patterns) used to paint the element; for animation it defines the final state of the animation. 72 ...
...And 14 more matches
Accessibility documentation index - Accessibility
Found 105 pages: # Page Tags and summary 1 Accessibility Accessibility, Landing Accessibility (often abbreviated to 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. ...
...tness, using tools such as MSAA Inspect. This must be done in order to determine where to file a bug (browser or AT). 5 ARIA annotations ARIA, Accessibility, WAI-ARIA, annotations, comments, details, suggestions WAI-ARIA version 1.3 sees the addition of a set of new features, collectively known as ARIA annotations, which allow the creation of accessible annotations inside web documents. Typical use cases include edit suggestions (i.e. an addition and/or deletion in an editable document), and comments (e.g. an editorial comment 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 ac...
...ser, userAgent The alertdialog role is used to notify the user of urgent information that demands the user's immediate attention. As the name implies, alertdialog is a type of dialog. This means that most of the instructions provided in the 'using the dialog role' technique are applicable to the alertdialog role as well: 17 Using the aria-activedescendant attribute Attribute, Document Object Model, NeedsContent, Property, Widget, aria-activedescendant This article describes the aria-activedescendant property. 18 Using the aria-describedby attribute ARIA, Accessibility, Attribute The aria-describedby attribute is used to indicate the IDs of the elements that describe the object. It is used to establish a relationship between widgets or groups and text...
...And 12 more matches
Commenting IDL for better documentation
That is why Mozilla has a couple of writers on-staff as well as a horde of happy volunteers. ...
...mentation from source code. The documentation team has tools that convert comments from the Doxygen format into the standard reference article format we use here on MDN, with certain limitations. This article will help you understand how you can format your comments to help ensure that the conversion process can be automated as much as possible in order to ensure that your interface gets properly documented. Happily, following these recommendations will also help ensure your comments are extremely human-readable, too. Don't worry! You don't need to write perfect documentation. That is why Mozilla has a couple of writers on-staff as well as a horde of happy volunteers. We will take your comments and notes and turn them into beautiful, easy to search and read documentation. But by following the guid...
... human-readable, too. Don't worry! ...
...And 11 more matches
DocumentFragment - Web APIs
The key difference is due to the fact that the document fragment isn't part of the active document tree structure. Changes made to the fragment don't affect the document (even on reflow) or incur any performance impact when changes are made. ...
... The DocumentFragment interface represents a minimal document object that has no parent. It is used as a lightweight version of Document that stores a segment of a document structure comprised of nodes just like a standard document. The key difference is due to the fact that the document fragment isn't part of the active document tree structure. Changes made to the fragment don't affect the document (even on reflow) or incur any performance impact when changes are made. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API...
...eight="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="188.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Node</text></a><polyline points="226,25 236,20 236,30 226,25" stroke="#D4DDE4" fill="none"/><line x1="236" y1="25" x2="266" y2="25" stroke="#D4DDE4"/><a xlink:href="/docs/Web/API/DocumentFragment" target="_top"><rect x="266" y="1" width="160" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="346" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">DocumentFragment</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Constructor Documen...
...And 11 more matches
DOMImplementation.createHTMLDocument() - Web APIs
The DOMImplementation.createHTMLDocument() 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. ...
...reates 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. ...
...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. ...
...And 10 more matches
Document.evaluate() - Web APIs
Web › API › Document › evaluate
Returns an XPathResult based on an XPath expression and other given parameters. Syntax var xpathResult = document.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result ); xpathExpression is a string representing the XPath to be evaluated. contextNode specifies the context node for the query (see the XPath specification). It's common to pass document as the context node. namespaceResolver is a function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. It will be used to resolve prefixes within the XPath itself, so that they can be matched with the document. null is common for HTML documents or when no namespace prefixes are used. resultType is an integer that corresponds to the...
...n no namespace prefixes are used. resultType is an integer that corresponds to the type of result XPathResult to return. Use named constant properties, such as XPathResult.ANY_TYPE, of the XPathResult constructor, which correspond to integers from 0 to 9. result is an existing XPathResult to use for the results. ...
...esultType is an integer that corresponds to the type of result XPathResult to return. Use named constant properties, such as XPathResult.ANY_TYPE, of the XPathResult constructor, which correspond to integers from 0 to 9. result is an existing XPathResult to use for the results. ...
...And 10 more matches
Archived Mozilla and build documentation - Archive of obsolete content
These articles are archived, obsolete documents about Mozilla, Gecko, and the process of building Mozilla projects. ActiveX Control for Hosting Netscape Plug-ins in IE Microsoft has removed support for Netscape plug-ins from IE 5.5 SP 2 and beyond. If you are a plug-in author, you may find this project saves you a lot of work! ant script to assemble an extension This ant script helps to package an extension Archived SpiderMonkey docs This section contains old SpiderMonkey documentation. Autodial for Windows NT This document is intended to explain how the autodial helper feature implemented for bug 93002 works and why it works that way. Automated testing tips and tricks Automa...
...Generators can also be independently downloaded and installed by users if they include a list of pages to which they apply. Creating a Mozilla Extension A Mozilla extension is an installable enhancement to the Mozilla browser that provides additional functionality (for example Linky, which adds an item to the context menu for opening multiple links in a document or selection). This tutorial walks you through the process of building a Mozilla extension that adds an icon to Mozilla's status bar showing the current status of the Mozilla source code (i.e. whether or not the latest version of the code is compiling successfully and passing tests). The extension will access Tinderbox, mozilla.org's webtool for tracking source code status, to g...
... 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 migrated. Extension Frequently Asked Questions This is quick set of answers to the most common issues with extension development. They are currently written with mostly Firefox in mind, but most if not all should easily translate to SeaMonkey, Thunderbird or any of the other applications. For Thunderbird, y...
...And 9 more matches
Document.getElementsByClassName() - Web APIs
When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class name(s). Syntax var elements = document.getElementsByClassName(names); // or: var elements = rootElement.getElementsByClassName(names); elements is a live HTMLCollection of found elements. ...
...ement with the given class name(s). Syntax var elements = document.getElementsByClassName(names); // or: var elements = rootElement.getElementsByClassName(names); elements is a live HTMLCollection of found elements. names is a string representing the class name(s) to match; multiple class names are separated by whitespace getElementsByClassName can be called on any element, not only on the document. The element on which it is called will be used as the root of the search. ...
...tsByClassName(names); elements is a live HTMLCollection of found elements. names is a string representing the class name(s) to match; multiple class names are separated by whitespace getElementsByClassName can be called on any element, not only on the document. The element on which it is called will be used as the root of the search. ...
...And 9 more matches
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
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. ...
...ment loading process. We start with the request to load a particular link in a particular window, and proceed up to the point at which the data stream is dispatched to the proper handler. The final goal 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). ...
...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 keeps track of currently pending loads and registered content listeners. ...
...And 8 more matches
nsIDOMNSHTMLDocument
dom/interfaces/html/nsIDOMNSHTMLDocument.idlScriptable This interface defines methods and properties supported by Gecko on the document object that are not part of DOM Level 2. ...
...rts Last changed in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) Method overview void captureEvents(in long eventFlags); void clear(); boolean execCommand(in DOMString commandID, in boolean doShowUI, in DOMString value); boolean execCommandShowHelp(in DOMString commandID); Obsolete since Gecko 14.0 DOMString getSelection(); nsIDOMDocument open(in ACString aContentType, in boolean aReplace); boolean queryCommandEnabled(in DOMString commandID); boolean queryCommandIndeterm(in DOMString commandID); boolean queryCommandState(in DOMString commandID); boolean queryCommandSupported(in DOMString commandID); DOMString queryCommandText(in DOMString commandID); Obsolete since Gecko 14.0 D...
...ts(in long eventFlags); void routeEvent(in nsIDOMEvent evt); void write(); Obsolete since Gecko 2.0 void writeln(); Obsolete since Gecko 2.0 Attributes Attribute Type Description alinkColor DOMString Same as body.aLink bgColor DOMString Same as body.bgColor compatMode DOMString Returns "BackCompat" if the document is in Quirks mode or "CSS1Compat" if the document is in Full Standards or Almost Standards mode. Read only. designMode DOMString Set to "on" or "off" to enable or disable editing for the entire document at once. Roughly equivalent to body.contentEditable domain DOMString Initially the host name of the document's URL, but may be changed to the parent (but not top-leve...
...And 8 more matches
Document.createElement() - Web APIs
In Firefox, Opera, and Chrome, createElement(null) works like createElement("null"). ...
...In Firefox, Opera, and Chrome, createElement(null) works like createElement("null"). ...
...In Firefox, Opera, and Chrome, createElement(null) works like createElement("null"). ...
...And 7 more matches
Document.getElementById() - Web APIs
Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly. If you need to get access to an element which doesn't have an ID, you can use querySelector() to find the element using any selector. Syntax var element = document.getElementById(id); Parameters id The ID of the element to locate. The ID is case-sensitive string which is unique within the document; only one element may have any given ID. Return value An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document. ...
...() to find the element using any selector. Syntax var element = document.getElementById(id); Parameters id The ID of the element to locate. The ID is case-sensitive string which is unique within the document; only one element may have any given ID. Return value An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document. ...
...ement object matching the specified ID, or null if no matching element was found in the document. Example HTML <html> <head> <title>getElementById example</title> </head> <body> <p id="para">Some text here</p> <button onclick="changeColor('blue');">blue</button> <button onclick="changeColor('red');">red</button> </body> </html> JavaScript function changeColor(newColor) { var elem = document.getElementById('para'); elem.style.color = newColor; } Result Usage notes The capitalization of "Id" in the name of this method must be correct for the code to function; getElementByID() is not valid and will not work, however natural it may seem. Unlike some other element-lookup methods such as Document.querySelector() and Document.querySelectorAll(), getElementById() is only available a...
...And 7 more matches
Document.readyState - Web APIs
When the value of this property changes, a readystatechange event fires on the document object. Syntax var string = document.readyState; Values The readyState of a document can be one of following: loading The document is still loading. interactive The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading. complete The document and all sub-resources have finished loading. The state indicates that the load event is about to fire. Examples Different states of readiness switch (document.readyState) { case "loading": // The document is still loading. ...
... be one of following: loading The document is still loading. interactive The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading. complete The document and all sub-resources have finished loading. The state indicates that the load event is about to fire. Examples Different states of readiness switch (document.readyState) { case "loading": // The document is still loading. break; case "interactive": // The document has finished loading. We can now access the DOM elements. // But sub-resources such as images, stylesheets and frames are still loading. ...
...g. The state indicates that the load event is about to fire. Examples Different states of readiness switch (document.readyState) { case "loading": // The document is still loading. break; case "interactive": // The document has finished loading. We can now access the DOM elements. // But sub-resources such as images, stylesheets and frames are still loading. var span = document.createElement("span"); span.textContent = "A <span> element."; document.body.appendChild(span); break; case "complete": // The page is fully loaded. ...
...And 7 more matches
ARIA: document role - Accessibility
Generally used in complex composite widgets or applications, the document role can inform assistive technologies to switch context to a reading mode: The document role tells assistive technologies with reading or browse modes to use the document mode to read the content contained within this element. <div role="dialog"> ... <div id="InfoText" role="document" tabindex="0"> <p>Some informational text goes here.</p> </div> ... <button>Close</button> </div> This example shows a dialog widget with some controls and a section with some informational text that the assistive technology user can read when tabbing to it. Description By default, web pages are treated as documents; assistive technologies (AT) enter browse or read mode when entering a new web page. This mode can be altered through...
...s example shows a dialog widget with some controls and a section with some informational text that the assistive technology user can read when tabbing to it. Description By default, web pages are treated as documents; assistive technologies (AT) enter browse or read mode when entering a new web page. This mode can be altered through various roles, including the widget and application roles. The document role brings the AT back into browse or read mode. Generally placed within an application role or other interactive widget role, the document role is used to indicate a section of a complex composit widget that an assistive technology user should read using its browse or virtual reading mode, if available. Because ATs with reading mode default to that mode for all elements except for those with...
...e or read mode. Generally placed within an application role or other interactive widget role, the document role is used to indicate a section of a complex composit widget that an assistive technology user should read using its browse or virtual reading mode, if available. Because ATs with reading mode default to that mode for all elements except for those with a widget or application role set, document role is only useful for focusable elements within a widget or application that should be read as static rich text. Adding role="document" and tabindex="0" to the element containing the text within a widget enables the screen reader user to press the Tab key to place focus on the document element and read the text with the screen reader's reading cursor. Assistive technologies should switch conte...
...And 7 more matches
nsIDocumentLoader
uriloader/base/nsIDocumentLoader.idlScriptable This interface responsible for tracking groups of loads that belong together (images, external scripts, and so on.) and subdocuments (iframe, frame, and so on.). It is also responsible for sending nsIWebProgressListener notifications. Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Implemented by: @mozilla.org/docloaderservice;1. ...
...sible for tracking groups of loads that belong together (images, external scripts, and so on.) and subdocuments (iframe, frame, and so on.). It is also responsible for sending nsIWebProgressListener notifications. Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Implemented by: @mozilla.org/docloaderservice;1. ...
...o on.). It is also responsible for sending nsIWebProgressListener notifications. Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Implemented by: @mozilla.org/docloaderservice;1. ...
...And 6 more matches
Document.createTreeWalker() - Web APIs
Syntax document.createTreeWalker(root, whatToShow[, filter[, entityReferenceExpansion]]); Parameters root A root Node of this TreeWalker traversal. Typically this will be an element owned by the document. whatToShow Optional A unsigned long representing a bitmask created by combining the constant properties of NodeFilter. It is a convenient way of filtering for certain types of node. It defaults to 0xFFFFFFFF representing the SHOW_ALL constant. Constant Numerical value Description NodeFilter.SHOW_ALL -1 (that is the max value of unsigned long) Shows all nodes. NodeFilter.SHOW_ATTRIBUTE 2 Shows attribute Attr nodes. ...
...gned long) Shows all nodes. NodeFilter.SHOW_ATTRIBUTE 2 Shows attribute Attr nodes. This is meaningful only when creating a TreeWalker with an Attr node as its root; in this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree. NodeFilter.SHOW_CDATA_SECTION 8 Shows CDATASection nodes. NodeFilter.SHOW_COMMENT 128 Shows Comment nodes. NodeFilter.SHOW_DOCUMENT 256 Shows Document nodes. NodeFilter.SHOW_DOCUMENT_FRAGMENT 1024 Shows DocumentFragment nodes. NodeFilter.SHOW_DOCUMENT_TYPE 512 Shows DocumentType nodes. ...
...CUMENT_TYPE 512 Shows DocumentType nodes. NodeFilter.SHOW_ELEMENT 1 Shows Element nodes. NodeFilter.SHOW_ENTITY 32 Shows Entity nodes. This is meaningful only when creating a TreeWalker with an Entity node as its root; in this case, it means that the Entity node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree. NodeFilter.SHOW_ENTITY_REFERENCE 16 Shows EntityReference nodes. NodeFilter.SHOW_NOTATION 2048 Shows Notation nodes. This is meaningful only when creating a TreeWalker with a Notation node as its root; in this case, it means that the Notation node will appear in the first position of the t...
...And 6 more matches
Document.getElementsByTagName() - Web APIs
The complete document is searched, including the root node. The returned HTMLCollection is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName() again. Syntax var elements = document.getElementsByTagName(name); elements is a live HTMLCollection (but see the note below) of found elements in the order they appear in the tree. name is a string representing the name of the elements. The special string "*" represents all elements. The latest W3C specification says elements is an HTMLCollection; however, this method returns a NodeList in WebKit browsers. ...
...lements is an HTMLCollection; however, this method returns a NodeList in WebKit browsers. See bug 14869 for details. Example In the following example, getElementsByTagName() starts from a particular parent element and searches top-down recursively through the DOM from that parent element, building a collection of all descendant elements which match the tag name parameter. This demonstrates both document.getElementsByTagName() and the functionally identical Element.getElementsByTagName(), which starts the search at a specific element within the DOM tree. Clicking the buttons uses getElementsByTagName() to count the descendant paragraph elements of a particular parent (either the document itself or one of two nested <div> elements). <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"...
... specific element within the DOM tree. Clicking the buttons uses getElementsByTagName() to count the descendant paragraph elements of a particular parent (either the document itself or one of two nested <div> elements). ...
...And 6 more matches
Document.getElementsByTagNameNS() - Web APIs
namespace is the namespace URI of elements to look for (see element.namespaceURI). name is either the local name of elements to look for or the special value *, which matches all elements (see element.localName). Note: While the W3C specification says elements is a NodeList, this method returns a HTMLCollection both in Gecko and Internet Explorer. ...
...the note in Browser compatibility section in Element.getElementsByTagNameNS for details. Example In the following example getElementsByTagNameNS starts from a particular parent element, and searches topdown recursively through the DOM from that parent element, looking for child elements matching the tag name parameter. ...
...hich getElementsByTagName is invoked is not the document node, in fact the element.getElementsByTagNameNS method is used. To use the following example, just copy/paste it into a new file saved with the .xhtml extension. ...
...And 6 more matches
Document.height - Web APIs
Web › API › Document › height
Note: Starting in Gecko 6.0, document.height is no longer supported. Instead, use document.body.clientHeight. See element.clientHeight. Returns the height of the document object. In most cases, this is equal to the <body> element of the current document. ...
... Note: Starting in Gecko 6.0, document.height is no longer supported. Instead, use document.body.clientHeight. See element.clientHeight. Returns the height of the document object. In most cases, this is equal to the <body> element of the current document. ...
... Note: Starting in Gecko 6.0, document.height is no longer supported. Instead, use document.body.clientHeight. See element.clientHeight. Returns the height of the document object. In most cases, this is equal to the <body> element of the current document. ...
...And 6 more matches
Document.querySelectorAll() - Web APIs
Note: This method is implemented based on the ParentNode mixin's querySelectorAll() method. Syntax elementList = parentNode.querySelectorAll(selectors); Parameters selectors A DOMString containing one or more selectors to match 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. ...
...t 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-element, the returned list is always empty. Exceptions SyntaxError The syntax of the specified selectors string is not valid. Examples Obtaining a list of matches To obtain a NodeList of all of the <p> elements in the document: var matches = document.querySelectorAll("p"); This example returns a list of all <div> elements within the document with a class of either note or alert: var matches = document.querySelectorAll("div.note, div.alert"); Here, we get a list of <p> elements whose immediate parent element is a <div> with the class highlighted and which are located inside a container whose ID is test. var contai...
... matches = document.querySelectorAll("p"); This example returns a list of all <div> elements within the document with a class of either note or alert: var matches = document.querySelectorAll("div.note, div.alert"); Here, we get a list of <p> elements whose immediate parent element is a <div> with the class highlighted and which are located inside a container whose ID is test. ...
...And 6 more matches
@document - CSS: Cascading Style Sheets
Web › CSS › @document
The @document CSS at-rule restricts the style rules contained within it based on the URL of the document. It is designed primarily for user-defined style sheets, though it can be used on author-defined style sheets, too. @document url("https://www.example.com/") { h1 { color: green; } } Syntax An @document rule can specify one or more matching functions. If any of the functions apply to a given URL, the rule will take effect on that URL. The functions available are: url(), which matches an exact URL. url-prefix(), which matches if the document URL starts with the value provided. domain(), which matches if the document URL is on the domain provided (or a subdomain of it). media-document(), with the parameter of video, image, plugin or all. regexp(), which matches if th...
...to a given URL, the rule will take effect on that URL. The functions available are: url(), which matches an exact URL. url-prefix(), which matches if the document URL starts with the value provided. domain(), which matches if the document URL is on the domain provided (or a subdomain of it). media-document(), with the parameter of video, image, plugin or all. regexp(), which matches if the document URL is matched by the regular expression provided. The expression must match the entire URL. The values provided to the url(), url-prefix(), domain(), and media-document() functions can be optionally enclosed by single or double quotes. The values provided to the regexp() function must be enclosed in quotes. Escaped values provided to the regexp() function must additionally be escaped from the...
... quotes. The values provided to the regexp() function must be enclosed in quotes. Escaped values provided to the regexp() function must additionally be escaped from the CSS. For example, a . (period) matches any character in regular expressions. To match a literal period, you would first need to escape it using regular expression rules (to \.), then escape that string using CSS rules (to \\.). @document is currently only supported in Firefox; if you wanted to replicate using such functionality in your own non-Firefox browser, you could try using this polyfill by @An-Error94, which uses a combination of a user script, data-* attributes, and attribute selectors. Note: There is a -moz-prefixed version of this property -- @-moz-document. This has been limited to use only in user and UA sheets in F...
...And 6 more matches
<body>: The Document Body element - HTML: Hypertext Markup Language
Web › HTML › Element › body
The HTML <body> Element represents the content of an HTML document. There can be only one <body> element in a document. Content categories Sectioning root. Permitted content Flow content. Tag omission The start tag may be omitted if the first thing inside it is not a space character, comment, <script> element or <style> element. The end tag may be omitted if the <body> element has contents or has a start tag, and is not immediately followed by a comment. Permitted parents It must be the second element of an <html> element. Implicit ARIA role document Permitted ARIA roles No role permitted DOM interface HTMLBodyElement The <body> element exposes the HTMLBodyElement interface. You can access the <bod...
... Attributes This element includes the global attributes. alink Color of text for hyperlinks when selected. ...
... Attributes This element includes the global attributes. alink Color of text for hyperlinks when selected. This method is non-conforming, use CSS color property in conjunction with the :active pseudo-class instead. background URI of a image to use as a background. This method is non-conforming, use CSS background property on the element instead. bgcolor Background color for the document. This method is non-conforming, use CSS background-color property on the element instead. bottommargin The margin of the bottom of the body. This method is non-conforming, use CSS margin-bottom property on the element instead. leftmargin The margin of the left of the body. This method is non-conforming, use CSS margin-left property on the element instead. link Color of text for unvisi...
...And 6 more matches
nsIAccessibleDocument
accessible/public/nsIAccessibleDocument.idlScriptable An interface for in-process accessibility clients that wish to retrieve information about a document. When accessibility is turned on in Gecko, there is an nsIAccessibleDocument for each document whether it is XUL, HTML or whatever. Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) You can QueryInterface to nsIAccessibleDocument from the nsIAccessible or nsIAccessNode for the root node of a document. ...
...ssibility is turned on in Gecko, there is an nsIAccessibleDocument for each document whether it is XUL, HTML or whatever. Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) You can QueryInterface to nsIAccessibleDocument from the nsIAccessible or nsIAccessNode for the root node of a document. ...
...sIAccessibleDocument for each document whether it is XUL, HTML or whatever. Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) You can QueryInterface to nsIAccessibleDocument from the nsIAccessible or nsIAccessNode for the root node of a document. ...
...And 5 more matches
Document: DOMContentLoaded event - Web APIs
Bubbles Yes Cancelable Yes (although specified as a simple event that isn't cancelable) Interface Event Event handler property None A different event, load, should be used only to detect a fully-loaded page. It is a common mistake to use load where DOMContentLoaded would be more appropriate. Synchronous JavaScript pauses parsing of the DOM. If you want the DOM to get parsed as fast as possible after the user has requested the page, you can make your JavaScript asynchronous and optimize loading of stylesheets. ...
...oad where DOMContentLoaded would be more appropriate. Synchronous JavaScript pauses parsing of the DOM. If you want the DOM to get parsed as fast as possible after the user has requested the page, you can make your JavaScript asynchronous and optimize loading of stylesheets. If loaded as usual, stylesheets slow down DOM parsing as they're loaded in parallel, "stealing" traffic from the main HTML document. ...
...e more appropriate. Synchronous JavaScript pauses parsing of the DOM. If you want the DOM to get parsed as fast as possible after the user has requested the page, you can make your JavaScript asynchronous and optimize loading of stylesheets. If loaded as usual, stylesheets slow down DOM parsing as they're loaded in parallel, "stealing" traffic from the main HTML document. ...
...And 5 more matches
Document.anchors - Web APIs
Web › API › Document › anchors
Syntax nodeList = document.anchors; Value An HTMLCollection. ...
... The anchors read-only property of the Document interface returns a list of all of the anchors in the document. Syntax nodeList = document.anchors; Value An HTMLCollection. ...
... The anchors read-only property of the Document interface returns a list of all of the anchors in the document. Syntax nodeList = document.anchors; Value An HTMLCollection. ...
...And 5 more matches
Document.createNodeIterator() - Web APIs
whatToShow Optional Is an optional unsigned long representing a bitmask created by combining the constant properties of NodeFilter. It is a convenient way of filtering for certain types of node. It defaults to 0xFFFFFFFF representing the SHOW_ALL constant. Constant Numerical value Description NodeFilter.SHOW_ALL -1 (that is the max value of unsigned long) Shows all nodes. NodeFilter.SHOW_ATTRIBUTE 2 Shows attribute Attr nodes. ...
... Shows all nodes. NodeFilter.SHOW_ATTRIBUTE 2 Shows attribute Attr nodes. This is meaningful only when creating a TreeWalker with an Attr node as its root. In this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree. NodeFilter.SHOW_CDATA_SECTION 8 Shows CDATASection nodes. NodeFilter.SHOW_COMMENT 128 Shows Comment nodes. NodeFilter.SHOW_DOCUMENT 256 Shows Document nodes. NodeFilter.SHOW_DOCUMENT_FRAGMENT 1024 Shows DocumentFragment nodes. NodeFilter.SHOW_DOCUMENT_TYPE 512 Shows DocumentType nodes.
...CUMENT_TYPE 512 Shows DocumentType nodes. NodeFilter.SHOW_ELEMENT 1 Shows Element nodes. NodeFilter.SHOW_ENTITY 32 Shows Entity nodes. This is meaningful only when creating a TreeWalker with an Entity node as its root; in this case, it means that the Entity node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree. NodeFilter.SHOW_ENTITY_REFERENCE 16 Shows EntityReference nodes. NodeFilter.SHOW_NOTATION 2048 Shows Notation nodes. This is meaningful only when creating a TreeWalker with a Notation node as its root; in this case, it means that the Notation node will appear in the first position of the t...
...And 5 more matches
Document.forms - Web APIs
Web › API › Document › forms
Note: Similarly, you can access a list of a form's component user input elements using the HTMLFormElement.elements property. Syntax collection = document.forms; Value An HTMLCollection object listing all of the document's forms. Each item in the collection is a HTMLFormElement representing a single <form> element. If the document has no forms, the returned collection is empty, with a length of zero. ...
...llection listing all the <form> elements contained in the document. Note: Similarly, you can access a list of a form's component user input elements using the HTMLFormElement.elements property. Syntax collection = document.forms; Value An HTMLCollection object listing all of the document's forms. Each item in the collection is a HTMLFormElement representing a single <form> element. If the document has no forms, the returned collection is empty, with a length of zero. ...
...FormElement.elements property. Syntax collection = document.forms; Value An HTMLCollection object listing all of the document's forms. Each item in the collection is a HTMLFormElement representing a single <form> element. If the document has no forms, the returned collection is empty, with a length of zero. ...
...And 5 more matches
Document.hasFocus() - Web APIs
Web › API › Document › hasFocus
This method can be used to determine whether the active element in a document has focus. When viewing a document, an element with focus is always the active element in the document, but an active element does not necessarily have focus. For example, an active element within a popup window that is not the foreground doesn't have focus. Syntax var focused = document.hasFocus(); Return value false if the active element 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. ...
...When viewing a document, an element with focus is always the active element in the document, but an active element does not necessarily have focus. For example, an active element within a popup window that is not the foreground doesn't have focus. Syntax var focused = document.hasFocus(); Return value false if the active element 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. ...
...lement 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. ...
...And 5 more matches
Document.open() - Web APIs
Web › API › Document › open
Examples The following simple code opens the document and replaces its content 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. ...
...od opens a document for writing. This does come with some side effects. For example: All event listeners currently registered on the document, nodes inside the document, or the document's window are removed. All existing nodes are removed from the document. Syntax document.open(); Parameters None. Return value A Document object instance. Examples The following simple code opens the document and replaces its content 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...
...ument.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 whose URI it uses, instead of fetching the principal off the stack. As a result, you can no...
...And 5 more matches
Document.write() - Web APIs
Web › API › Document › write
Note: Because document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document. Syntax document.write(markup); Parameters markup A string containing the text to be written to the document. ...
... The Document.write() method writes a string of text to a document stream opened by document.open(). Note: Because document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document. Syntax document.write(markup); Parameters markup A string containing the text to be written to the document. ...
... Because document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document. Syntax document.write(markup); Parameters markup A string containing the text to be written to the document. Example <html> <head> <title>Write example</title> <script> function newContent() { document.open(); document.write("<h1>Out with the old, in with the new!</h1>"); document.close(); } </script> </head> <body onload="newContent();"> <p>Some original document content.</p> </body> </html> Notes The text you write is parsed into the document's structure model. In the example above, the h1 element becomes a node in the document. ...
...And 5 more matches
DocumentType - Web APIs
The DocumentType interface represents a Node containing a doctype. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">EventTarget</text></a><polyline points="111,25 121,20 121,30 111,25" stroke="#D4DDE4" fill="none"/><line x1="121" y1="25" x2="15...
...eight="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="188.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Node</text></a><polyline points="226,25 236,20 236,30 226,25" stroke="#D4DDE4" fill="none"/><line x1="236" y1="25" x2="266" y2="25" stroke="#D4DDE4"/><a xlink:href="/docs/Web/API/DocumentType" target="_top"><rect x="266" y="1" width="120" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="326" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">DocumentType</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits propertie...
...="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="326" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">DocumentType</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits properties from its parent, Node, and implements the ChildNode interface. DocumentType.entities Read only A NamedNodeMap of entities declared in the DTD. Every node in this map implements the Entity interface. ...
...And 5 more matches
Document Object Model (DOM) - Web APIs
Usually, that means JavaScript, although modeling HTML, SVG, or XML documents as objects are not part of the core JavaScript language, as such. 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. Nodes can also have event handlers attached to them. Once an event is triggered, the event handlers get executed. To learn more about what the DOM is and how it represents documents, see our article Introduction to the DOM. ...
... 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. Nodes can also have event handlers attached to them. Once an event is triggered, the event handlers get executed. To learn more about what the DOM is and how it represents documents, see our article Introduction to the DOM. DOM interfaces Attr CDATASection CharacterData ChildNode Comment CustomEvent Document DocumentFragment DocumentType DOMError DOMException DOMImplementation DOMString DOMTimeStamp DOMStringList DOMTokenList Element Event EventTarget HTMLCollection MutationObserver MutationRecord NamedNodeMap Node NodeFilter NodeIterator ...
...icle Introduction to the DOM. DOM interfaces Attr CDATASection CharacterData ChildNode Comment CustomEvent Document DocumentFragment DocumentType DOMError DOMException DOMImplementation DOMString DOMTimeStamp DOMStringList DOMTokenList Element Event EventTarget HTMLCollection MutationObserver MutationRecord NamedNodeMap Node NodeFilter NodeIterator NodeList NonDocumentTypeChildNode ParentNode ProcessingInstruction Selection Range Text TextDecoder TextEncoder TimeRanges TreeWalker URL Window Worker XMLDocument Obsolete DOM interfaces The Document Object Model has been highly simplified. To achieve this, the following interfaces present in the different DOM level 3 or earlier specifications have been removed. It is uncertain whether some ...
...And 5 more matches
Properly Using CSS and JavaScript in XHTML Documents - Archive of obsolete content
n 9, Microsoft(R) Internet Explorer only supports XHTML if it is served with MIME media type text/html rather than the recommended application/xhtml+xml. When an XHTML page is served with MIME type text/html it is treated by all browsers as if it were nothing more than HTML. However when an XHTML page is served with MIME type text/xml or application/xhtml+xml, then it should be treated as an XML document which must conform to the strict rules for authoring and displaying XML. Proper XHTML is an application of XML and as such requires that authors follow strict rules when authoring XHTML. In particular: Raw < and & characters are not allowed except inside of CDATA Sections (<![CDATA[ ... ]]>). Comments (<!---- ... ---->) must not contain double dashes (----). Content contained within Comment...
...rmant 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. Netscape 7.0x/Mozilla 1.0.x Do not apply CSS but does execute the JavaScript. Internet Explorer 5.5+ Can not display the document. (See Talk:Properly_Using_CSS_and_JavaScript_in_XHTML_Documents of this ascertation. - XmlGuru) Inline style and script Containing Double Dashes Another problem with using comments to surround JavaScript in XHTML is related to the problems which can occur if comments contain double dashes (----). <script type="text/javascript"> <!-- var i; var sum = 0; for (i = 10; i > 0; --i) { ...
...era 7 and Internet Explorer 5.5+ which all apply the CSS rules as expected. Example 2 - XHTML 1.0 Strict as text/xml This example illustrates the behavior of XHTML served as text/xml when CSS rules are contained inline and surrounded by comments. This example is supported by Netscape 7.x, Mozilla, and Opera 7 but not Internet Explorer 5.5+ (See Talk:Properly_Using_CSS_and_JavaScript_in_XHTML_Documents of this ascertation. - XmlGuru). Note that Netscape 7.x, Mozilla and Opera all agree that CSS rules contained inline inside of comments are to be ignored. Example 3 - XHTML 1.0 Strict as application/xhtml+xml This example illustrates the behavior of XHTML served as application/xhtml+xml when CSS rules are contained inline and surrounded by comments. This example is supported by Netscape 7.x...
...And 4 more matches
Document.createTouchList() - Web APIs
In following code snippet, some Touch objects are created for the target element and those touch points are then used to create some TouchList objects. ...
... In following code snippet, some Touch objects are created for the target element and those touch points are then used to create some TouchList objects. ...
... In following code snippet, some Touch objects are created for the target element and those touch points are then used to create some TouchList objects. ...
...And 4 more matches
Document.lastModified - Web APIs
Syntax var string = document.lastModified; Examples Simple usage This example alerts the value of lastModified. alert(document.lastModified); // returns: Tuesday, December 16, 2017 11:09:42 Transforming lastModified into a Date object This example transforms lastModified into a Date object. let oLastModif = new Date(document.lastModified); Transforming lastModified into milliseconds This example transforms lastModified into the number of milliseconds since January 1, 1970, 00:00:00, local time. ...
...ied); // returns: Tuesday, December 16, 2017 11:09:42 Transforming lastModified into a Date object This example transforms lastModified into a Date object. let oLastModif = new Date(document.lastModified); Transforming lastModified 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. ...
...forms 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. ...
...And 4 more matches
Document.querySelector() - Web APIs
If no matches are found, null is returned. Note: The matching is done using depth-first pre-order traversal of the document's nodes starting with the first element in the document's markup and iterating through sequential nodes by order of the number of child nodes. Syntax element = document.querySelector(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. ...
...e 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. ...
... 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 ("\"). ...
...And 4 more matches
Document.width - Web APIs
Web › API › Document › width
Note: Starting in Gecko 6.0, document.width is no longer supported. Instead, use document.body.clientWidth. See element.clientWidth. Returns the width of the <body> element of the current document in pixels. Not supported by Internet Explorer. ...
... Note: Starting in Gecko 6.0, document.width is no longer supported. Instead, use document.body.clientWidth. See element.clientWidth. Returns the width of the <body> element of the current document in pixels. Not supported by Internet Explorer. ...
... Note: Starting in Gecko 6.0, document.width is no longer supported. Instead, use document.body.clientWidth. See element.clientWidth. Returns the width of the <body> element of the current document in pixels. Not supported by Internet Explorer. ...
...And 4 more matches
DOMImplementation.createDocument() - Web APIs
The DOMImplementation.createDocument() method creates and returns an XMLDocument. Syntax var doc = document.implementation.createDocument(namespaceURI, qualifiedNameStr, documentType); Parameters namespaceURI Is a DOMString containing the namespace URI of the document to be created, or null if the document doesn't belong to one. qualifiedNameStr Is a DOMString containing the qualified name, that is an optional prefix and colon plus the local root element name, of the document to be created. documentType Optional Is the DocumentType of the document to be created. It defaults to null. ...
...aining the namespace URI of the document to be created, or null if the document doesn't belong to one. qualifiedNameStr Is a DOMString containing the qualified name, that is an optional prefix and colon plus the local root element name, of the document to be created. documentType Optional Is the DocumentType of the document to be created. It defaults to null. ...
...e document to be created, or null if the document doesn't belong to one. qualifiedNameStr Is a DOMString containing the qualified name, that is an optional prefix and colon plus the local root element name, of the document to be created. documentType Optional Is the DocumentType of the document to be created. It defaults to null. ...
...And 3 more matches
Document.adoptNode() - Web APIs
Document.adoptNode() transfers a node from another document into the method's document. The adopted node and its subtree is removed from its original document (if any), and its ownerDocument is changed to the current document. The node can then be inserted into the current document. Syntax const importedNode = document.adoptNode(externalNode); Parameters externalNode The node from another document to be adopted. Return value The copied importedNode in the scope of the importing document. After calling this method, importedNode and externalNode are the same object. ...
...cument. Syntax const importedNode = document.adoptNode(externalNode); Parameters externalNode The node from another document to be adopted. Return value The copied importedNode in the scope of the importing document. After calling this method, importedNode and externalNode are the same object. ...
...ument.adoptNode(externalNode); Parameters externalNode The node from another document to be adopted. Return value The copied importedNode in the scope of the importing document. After calling this method, importedNode and externalNode are the same object. ...
...And 3 more matches
Document.domain - Web APIs
Web › API › Document › domain
If this property is successfully set, the port part of the origin is also set to null. Syntax const domainString = document.domain document.domain = domainString Value The domain portion of the current document's origin. ...
... The domain property of the Document interface gets/sets the domain portion of the origin of the current document, as used by the same origin policy. If this property is successfully set, the port part of the origin is also set to null. Syntax const domainString = document.domain document.domain = domainString Value The domain portion of the current document's origin. ...
... the current document, as used by the same origin policy. If this property is successfully set, the port part of the origin is also set to null. Syntax const domainString = document.domain document.domain = domainString Value The domain portion of the current document's origin. ...
...And 3 more matches
Document.importNode() - Web APIs
deep Optional A Boolean which controls whether to include the entire DOM subtree of the externalNode in the import. ...
... The Document object's importNode() method creates a copy of a Node or DocumentFragment from another document, to be inserted into the current document later. The imported node is not yet included in the document tree. To include it, you need to call an insertion method such as appendChild() or insertBefore() with a node that is currently in the document tree. Unlike document.adoptNode(), the original node is not removed from its original document. The imported node is a clone of the original. Syntax const importedNode = document.importNode(externalNode [, deep]); Parameters externalNode The external Node or DocumentFragment to import into the current document. deep Optional A Boolean which controls whether to include the entire DOM subtree of the externalNode in the import. If dee...
...eep argument for backward and forward compatibility. With Gecko 28.0 (Firefox 28 / Thunderbird 28 / SeaMonkey 2.25 / Firefox OS 1.3), the console warns developers not to omit the argument. Starting with Gecko 29.0 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26)), a shallow clone is defaulted instead of a deep clone. Return value The copied importedNode in the scope of the importing document. ...
...And 3 more matches
Document.origin - Web APIs
Web › API › Document › origin
In most cases, this property is equivalent to document.defaultView.location.origin. ...
... Use self.origin instead. The Document.origin read-only property returns the document's origin. In most cases, this property is equivalent to document.defaultView.location.origin. ...
... Use self.origin instead. The Document.origin read-only property returns the document's origin. In most cases, this property is equivalent to document.defaultView.location.origin. ...
...And 3 more matches
DocumentFragment.querySelector() - Web APIs
The DocumentFragment.querySelector() method returns the first element, or null if no matches are found, within the DocumentFragment (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors. If the selector matches an ID and this ID is erroneously used several times in the document, it returns the first matching element. If the selectors specified in parameter are invalid a DOMException with a SYNTAX_ERR value is raised. Syntax element = documentfragment.querySelector(selectors); Parameters selectors Is a DOMString containing one or more CSS selectors separated by commas. ...
...mes in the document, it returns the first matching element. If the selectors specified in parameter are invalid a DOMException with a SYNTAX_ERR value is raised. Syntax element = documentfragment.querySelector(selectors); Parameters selectors Is a DOMString containing one or more CSS selectors separated by commas. Examples Basic example In this basic example, the first element in the DocumentFragment with the class "myclass" is returned: var el = documentfragment.querySelector(".myclass"); CSS syntax and the method's argument The string argument pass to querySelector must follow the CSS syntax. To match ID or selectors that do not follow the CSS syntax (by using semicolon or space inappropriately for example), it's mandatory to escape the wrong character with a double back slash: ...
...mentfragment.querySelector(".myclass"); CSS syntax and the method's argument The string argument pass to querySelector must follow the CSS syntax. ...
...And 3 more matches
DocumentOrShadowRoot.nodesFromPoint() - Web APIs
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. ...
... The nodesFromPoint() property of the DocumentOrShadowRoot interface returns an array of all nodes at the specified coordinates (relative to the 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. ...
...od 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. ...
...And 3 more matches
NonDocumentTypeChildNode.previousElementSibling - Web APIs
The NonDocumentTypeChildNode.previousElementSibling read-only property returns the Element immediately prior to the specified one in its parent's children list, or null if the specified element is the first one in the list. Syntax prevNode = elementNodeReference.previousElementSibling; Example <div id="div-01">Here is div-01</div> <div id="div-02">Here is div-02</div> <li>This is a list item</li> <li>This is another list item</li> <div id="div-03">Here is div-03</div> <script> let el = document.getElementById('div-03').previousElementSibling; document.write('<p>Siblings of div-03</p><ol>'); while (el) { document.write('<li>' + el.nodeName + '</li>'); el = el.previousElementSibling; } document.write('</ol>'); </script> This example outputs the following into the page when...
...his example outputs the following into the page when it loads: Siblings of div-03 1. LI 2. LI 3. DIV 4. ...
...le outputs the following into the page when it loads: Siblings of div-03 1. LI 2. LI 3. DIV 4. ...
...And 3 more matches
Archived open Web documentation - Archive of obsolete content
Talk:background-size Should not the "Browser compatibility" table also list Google Chrome and Konqueror? Chome is not mentioned at all, but is becoming increasingly popular. Konqueror is listed below the table, which seems inconsistent. Znerd 04 August 2009 Browser Detection and Cross Browser Support Improper browser detection can lead to web maintenance nightmares. Rethinking the basics of when and how to detect user agents is crucial to creating maintainable, cross browser web content. ...
...upport 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 syntax of E4X (ECMAScript for XML). With E4X, programmer...
...at 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 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 Iter...
...And 2 more matches
Document and website structure - Learn web development
"the main content column"). This article looks into how to plan a basic website structure, and write the HTML to represent this structure. Prerequisites: Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals. How hyperlinks work, as covered in Creating hyperlinks. ...
...o represent this structure. Prerequisites: Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals. How hyperlinks work, as covered in Creating hyperlinks. Objective: Learn how to structure your document using semantic tags, and how to work out the structure of a simple website. Basic sections of a document Webpages can and will look pretty different from one another, but they all tend to share similar standard components, unless the page is displaying a fullscreen video or game, is part of some kind of art project, or is just badly structured: header: Usually a big strip across the top with a big heading, logo, and perhaps a tagline. This usually stays the same from one webpage to another. na...
...ere is our main footer that is used across all the pages of our website --> <footer> <p>(C)Copyright 2050 by nobody. All rights reversed.</p> </footer> </body> </html> Take some time to look over the code and understand it -- the comments inside the code should also help you to understand it. We aren't asking you to do much else in this article, because the key to understanding document layout is writing a sound HTML structure, and then laying it out with CSS. We'll wait for this until you start to study CSS layout as part of the CSS topic. HTML layout elements in more detail It's good to understand the overall meaning of all the HTML sectioning elements in detail -- this is something you'll work on gradually as you start to get more experience with web development. You can fi...
...And 2 more matches
Mozilla Style System Documentation
Style context management A style context (class nsStyleContext, currently also interface nsIStyleContext although the interface should go away when all of the style systems can be moved back into the layout DLL) represents the style data for a CSS formatting object. In the layout system, these formatting objects are described as frames (interface nsIFrame), although a pair of frames represents table formatting objects. The CSS specification describes formatting objects that correspond to elements in the content model and formatting objects that correspond to pseudo-elements. ...
...mputed if it hasn't been computed already and then fill in the struct pointer. The struct is owned by the style system (either on the style context or on the rule node). These functions should only fill in a null pointer on allocation failure. Style contexts and the rule tree When the style system creates a style context, it walks through the style sheets (interface nsIStyleSheet) attached to a document in the order defined by the CSS cascade and finds the style rules (interface nsIStyleRule) thatmatch the content node or content node + pseudo-element pair. (The "non-element" style contexts are defined never to match any rules.) These interfaces nsIStyleSheet and nsIStyleRule correspond to the CSS concepts of style sheets and style rules, except they are more general, and are used by other code ...
...d finds the style rules (interface nsIStyleRule) thatmatch the content node or content node + pseudo-element pair. (The "non-element" style contexts are defined never to match any rules.) These interfaces nsIStyleSheet and nsIStyleRule correspond to the CSS concepts of style sheets and style rules, except they are more general, and are used by other code that needs to add style information to the document. For the CSS stylesheets, this process corresponds to CSS selector matching. The output of CSS selector matching as defined by the CSS specification is an ordered list of rules, where the order determines which declarations override other declarations. (In CSS,declarations are the property-value pairs within style rules. In Mozilla, nsCSSDeclaration objects correspond to CSS declaration-blocks.) ...
...And 2 more matches
DOMImplementation.createDocumentType() - Web APIs
The DOMImplementation.createDocumentType() method returns a DocumentType object which can either be used with DOMImplementation.createDocument upon document creation or can be put into the document via methods like Node.insertBefore() or Node.replaceChild(). Syntax var doctype = document.implementation.createDocumentType(qualifiedNameStr, publicId, systemId); Parameters qualifiedNameStr Is a DOMString containing the qualified name, like svg:svg. publicId Is a DOMString containing the PUBLIC identifier. systemId Is a DOMString containing the SYSTEM identifiers. ...
...thods like Node.insertBefore() or Node.replaceChild(). Syntax var doctype = document.implementation.createDocumentType(qualifiedNameStr, publicId, systemId); Parameters qualifiedNameStr Is a DOMString containing the qualified name, like svg:svg. publicId Is a DOMString containing the PUBLIC identifier. systemId Is a DOMString containing the SYSTEM identifiers. ...
... or Node.replaceChild(). Syntax var doctype = document.implementation.createDocumentType(qualifiedNameStr, publicId, systemId); Parameters qualifiedNameStr Is a DOMString containing the qualified name, like svg:svg. publicId Is a DOMString containing the PUBLIC identifier. systemId Is a DOMString containing the SYSTEM identifiers. Example var dt = document.implementation.createDocumentType('svg:svg', '-//W3C//DTD SVG 1.1//EN', 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'); var d = document.implementation.createDocument('http://www.w3.org/2000/svg', 'svg:svg', dt); alert(d.doctype.publicId); // -//W3C//DTD SVG 1.1//EN Specifications Specification Status Comment DOMThe definition of 'DOMImplementation.createDocumentType' in that specification. ...
...And 2 more matches
Document.alinkColor - Web APIs
Gecko supports both alinkColor/:active and :focus. ...
... Gecko supports both alinkColor/:active and :focus. ...
... Gecko supports both alinkColor/:active and :focus. ...
...And 2 more matches
Document.caretRangeFromPoint() - Web APIs
Syntax var range = document.caretRangeFromPoint(float x, float y); Parameters x A horizontal position within the current viewport. y A vertical position within the current viewport. Returns One of the following: A Range. Null, if x or y are negative, outside viewport, or there is no text entry node. Example Basic demo: When clicking in a paragraph insert a line break at the caret position: HTML <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. ...
... <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. ...
...pscing 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. ...
...And 2 more matches
Document.characterSet - Web APIs
(A character encoding is a set of characters and how to interpret bytes into those characters.) A "character set" and a "character encoding" are related, but different. Despite the name of this property, it returns the encoding. Users can override the developer-specified encoding inside the Content-Type header or inline like <meta charset="utf-8">, such as with Firefox's View -> Text Encoding menu. This override is provided to fix incorrect developer-specified encodings that result in garbled text. The properties document.charset and document.inputEncoding are legacy aliases for document.characterSet. Do not use them any more. ...
...aracter encoding" are related, but different. Despite the name of this property, it returns the encoding. Users can override the developer-specified encoding inside the Content-Type header or inline like <meta charset="utf-8">, such as with Firefox's View -> Text Encoding menu. This override is provided to fix incorrect developer-specified encodings that result in garbled text. ...
... related, but different. Despite the name of this property, it returns the encoding. Users can override the developer-specified encoding inside the Content-Type header or inline like <meta charset="utf-8">, such as with Firefox's View -> Text Encoding menu. This override is provided to fix incorrect developer-specified encodings that result in garbled text. ...
...And 2 more matches
Document.createElementNS() - Web APIs
The namespaceURI property of the created element is initialized with the value of namespaceURI. See Valid Namespace URIs. qualifiedName A string that specifies the type of element to be created. ...
...nt. Important Namespace URIs HTML http://www.w3.org/1999/xhtml SVG http://www.w3.org/2000/svg MathML http://www.w3.org/1998/Math/MathML XUL http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul XBL http://www.mozilla.org/xbl Example This creates a new <div> element in the XHTML namespace and appends it to the vbox element. ...
.../svg MathML http://www.w3.org/1998/Math/MathML XUL http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul XBL http://www.mozilla.org/xbl Example This creates a new <div> element in the XHTML namespace and appends it to the vbox element. ...
...And 2 more matches
Document.execCommand() - Web APIs
Note: Only returns true if part of a user interaction. Don't try using the return value to verify browser support before calling a command. ...
... Note: Only returns true if part of a user interaction. Don't try using the return value to verify browser support before calling a command. ...
... Note: Only returns true if part of a user interaction. ...
...And 2 more matches
Document.requestStorageAccess() - Web APIs
Conditions for granting storage access Storage access is granted based on a series of checks described here: If the document already has been granted access, resolve. If the document has a null origin, reject. If the document's frame is the main frame, resolve. If the sub frame's origin is equal to the main frame's, resolve. If the sub frame is not sandboxed, skip to step 7. If the sub frame doesn't have the token allow-storage-access-by-user-activation, reject. If the sub frame's parent frame is not the top frame, reject. ...
...-user-activation, reject. If the sub frame's parent frame is not the top frame, reject. If the browser is not processing a user gesture, reject. Check any additional rules that the browser has. Examples: allow lists, block lists, on-device classification, user settings, anti-clickjacking heuristics, or prompting the user for explicit permission. Reject if some rule is not fulfilled. Grant the document access to cookies and other site storage and store that fact for the purposes of future calls to Document.hasStorageAccess() and requestStorageAccess(). Assuming all of the requirements above are satisfied, Firefox will automatically grant storage access to the requesting origin on up to a threshold number of first-party origins in the current session for the duration of user's session, up to a...
...ng origin has storage access to is decremented by one. Note: If the requesting origin is not classified as a tracking origin, the access request is automatically given an ephemeral storage access grant, which will go away when the page is reloaded. The user is never shown a prompt in this case, and calling requestStorageAccess() won't have any side effects besides changing the value returned by Document.hasStorageAccess(). Debugging The storage access grant threshold may make it more difficult to test your website under the condition where Firefox prompts the user for access. To make testing easier, we have added two preferences in about:config that control prompting upon requestStorageAccess() calls: dom.storage_access.auto_grants can be set to false to disable the automatic granting of e...
...And 2 more matches
DocumentOrShadowRoot.activeElement - Web APIs
Often activeElement will return a HTMLInputElement or HTMLTextAreaElement object if it has the text selection at the time. If so, you can get more detail by using the object's selectionStart and selectionEnd properties. Other times the focused element might be a <select> element (menu) or an <input> element, of type "button", "checkbox", or "radio". Typically a user can press the tab key to move the focus around the page among focusable elements, and use the space bar to activate one (that is, to press a button or toggle a radio button). ...
... is, to press a button or toggle a radio button). Which elements are focusable varies depending on the platform and the browser's current configuration. For example, on macOS systems, elements that aren't text input elements are not typically focusable by default. Note: Focus (which element is receiving user input events) is not the same thing as selection (the currently highlighted part of the document). You can get the current selection using window.getSelection(). Syntax element = DocumentOrShadowRoot.activeElement Value The Element which currently has focus, <body> or null if there is no focused element. Example HTML <p>Select some text from one of the text areas below:</p> <form> <textarea name="ta-example-one" id="ta-example-one" rows="7" cols="40">This is Text Area One. Lorem i...
...e="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. ...
...And 2 more matches
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
Syntax var caretPosition = document.caretPositionFromPoint(float x, float y); Parameters x The horizontal coordinate of a point. y The vertical coordinate of a point. Returns A CaretPosition object. Example This example inserts 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. ...
...m 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. ...
...litr, 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. ...
...And 2 more matches
DocumentOrShadowRoot.elementsFromPoint() - Web APIs
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. ...
...). 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. ...
... 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. ...
...And 2 more matches
DocumentOrShadowRoot - Web APIs
The DocumentOrShadowRoot mixin of the Shadow DOM API provides APIs that are shared between documents and shadow roots. The following features are included in both Document and ShadowRoot. Properties DocumentOrShadowRoot.activeElementRead only Returns the Element within the shadow tree that has focus. DocumentOrShadowRoot.fullscreenElementRead only Returns the Element that's currently in full screen mode for this document. DocumentOrShadowRoot.pointerLockElement Read only Returns the element set as the target for mouse events while the pointer is locked. It returns null if lock is pending, the pointer is unlocked, or if the target is in another document. ...
...the shadow tree that has focus. DocumentOrShadowRoot.fullscreenElementRead only Returns the Element that's currently in full screen mode for this document. DocumentOrShadowRoot.pointerLockElement Read only Returns the element set as the target for mouse events while the pointer is locked. It returns null if lock is pending, the pointer is unlocked, or if the target is in another document. DocumentOrShadowRoot.styleSheetsRead only Returns a StyleSheetList of CSSStyleSheet objects for stylesheets explicitly linked into, or embedded in a document. Methods DocumentOrShadowRoot.caretPositionFromPoint() Returns a CaretPosition object containing the DOM node containing the caret, and caret's character offset within that node. ...
...s unlocked, or if the target is in another document. DocumentOrShadowRoot.styleSheetsRead only Returns a StyleSheetList of CSSStyleSheet objects for stylesheets explicitly linked into, or embedded in a document. Methods DocumentOrShadowRoot.caretPositionFromPoint() Returns a CaretPosition object containing the DOM node containing the caret, and caret's character offset within that node. DocumentOrShadowRoot.elementFromPoint() Returns the topmost element at the specified coordinates. DocumentOrShadowRoot.elementsFromPoint() Returns an array of all elements at the specified coordinates. ...
...And 2 more matches
HTMLDocument - Web APIs
The HTMLDocument interface, which may be accessed through the Window.HTMLDocument property, extends the Window.HTMLDocument property to include methods and properties that are specific to HTML documents. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="mi...
...eight="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="188.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Node</text></a><polyline points="226,25 236,20 236,30 226,25" stroke="#D4DDE4" fill="none"/><line x1="236" y1="25" x2="266" y2="25" stroke="#D4DDE4"/><a xlink:href="/docs/Web/API/Document" target="_top"><rect x="266" y="1" width="80" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="306" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Document</text></a><polyline points="346,25 356,20 356,30 346,25" stroke="#D4DDE4" fill="none"/><line x1="356" y1="25" x2="386" y2="2...
..."50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="306" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Document</text></a><polyline points="346,25 356,20 356,30 346,25" stroke="#D4DDE4" fill="none"/><line x1="356" y1="25" x2="386" y2="25" stroke="#D4DDE4"/><a xlink:href="/docs/Web/API/HTMLDocument" target="_top"><rect x="386" y="1" width="120" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="446" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLDocument</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} For the purposes of web developmen...
...And 2 more matches
Node.compareDocumentPosition() - Web APIs
Return value An integer value whose bits represent the otherNode's relationship to the calling node. ...
... The Node.compareDocumentPosition() method reports the position of the given node relative to another node in any document -- not just the given node's document. The return value is a bitmask of the following values: Name Value DOCUMENT_POSITION_DISCONNECTED 1 DOCUMENT_POSITION_PRECEDING 2 DOCUMENT_POSITION_FOLLOWING 4 DOCUMENT_POSITION_CONTAINS 8 DOCUMENT_POSITION_CONTAINED_BY 16 DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC 32 Syntax compareMask = node.compareDocumentPosition(otherNode) Parameters otherNode The other Node with which to compare the first node's document position. Return value An integer value whose bits represent the otherNode's relationship to the calling node. More than one b...
...TION_SPECIFIC 32 Syntax compareMask = node.compareDocumentPosition(otherNode) Parameters otherNode The other Node with which to compare the first node's document position. Return value An integer value whose bits represent the otherNode's relationship to the calling node. More than one bit is set if multiple scenarios apply. For example, if otherNode is located earlier in the document and contains the node on which compareDocumentPosition() was called, then both the DOCUMENT_POSITION_CONTAINS and DOCUMENT_POSITION_PRECEDING bits would be set, producing a value of 10 (0x0A). ...
...And 2 more matches
SVGDocument - Web APIs
SVG document interface When an "svg" element is embedded inline as a component of a document from another namespace, such as when an "svg" element is embedded inline within an XHTML document, then an SVGDocument object will not exist; instead, the root object in the document object hierarchy will be a Document object of a different type, such as an HTMLDocument object. Interface overview Also implement None Methods None Properties DOMString domain DOMString referrer SVGSVGElement rootElement DOMString title DOMString URL Nor...
... ...
... referrer DOMString Returns the URI of the page that linked to this page. ...
...And 2 more matches
XMLDocument - Web APIs
The XMLDocument interface represents an XML document. It inherits from the generic Document and does not add any specific methods or properties to it: nevertheless, several algorithms behave differently with the two types of documents. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor...
...eight="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="188.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Node</text></a><polyline points="226,25 236,20 236,30 226,25" stroke="#D4DDE4" fill="none"/><line x1="236" y1="25" x2="266" y2="25" stroke="#D4DDE4"/><a xlink:href="/docs/Web/API/Document" target="_top"><rect x="266" y="1" width="80" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="306" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Document</text></a><polyline points="346,25 356,20 356,30 346,25" stroke="#D4DDE4" fill="none"/><line x1="356" y1="25" x2="386" y2="2...
...="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="306" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Document</text></a><polyline points="346,25 356,20 356,30 346,25" stroke="#D4DDE4" fill="none"/><line x1="356" y1="25" x2="386" y2="25" stroke="#D4DDE4"/><a xlink:href="/docs/Web/API/XMLDocument" target="_top"><rect x="386" y="1" width="110" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="441" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">XMLDocument</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Property Also inherits properties ...
...And 2 more matches
document - XPath
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The document finds a node-set in an external document, or multiple external documents, and returns the resulting node-set. Syntax document(URI [,node-set] ) Arguments URI An absolute or relative URI of the document to be retrieved. The URI may also include a fragment identifier. node-set (optional) An expression pointing to a node-set in the external document that should be returned. Returns A node-set. Notes If the URI contains a fragment identifier and that fragment can be identified in the external document, that fragment will be treated as the root in the node-set argument's expression. If the node-set argument is omitted, the entire fragment will be returned. If the U...
... that fragment can be identified in the external document, that fragment will be treated as the root in the node-set argument's expression. If the node-set argument is omitted, the entire fragment will be returned. If the URI argument is a node-set, and the second argument is present, each node in the node-set will be evaluated as a separate URI, and the returned node-set will be as if the document function has been called multiple times (each time with the same second argument just as given in the function call) and the resulting node-sets had been concatenated into a single node-set. Other specific conditions exist with specified behaviors. See the XSLT 1.0 documentation for details. ...
... This function is an XSLT-specific addition to XPath. It is not a part of the core XPath function library. ...
...And 2 more matches
Mozilla Documentation Roadmap - Archive of obsolete content
There's a great deal of free online documentation available on XUL and extension development, but finding it and turning it into useful information can be a daunting task. Knowing where to look is critical and non trivial. This tutorial was aimed at compiling all the right resources for extension development and putting them in the right context, but there's much more to learn, and knowing how to find it is part of what we felt was necessary to teach. Let's look into the resources that have helped us the most. ...
...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 existed at XULPlanet and was later taken down. XULPlanet allowed you to navigate between interfaces and their related components, which makes locating components very easy. Hopefully this will be corrected in the future. In the meantime, you can still navigate XULPla...
...t it isn't nearly as useful as the documentation that existed at XULPlanet and was later taken down. XULPlanet allowed you to navigate between interfaces and their related components, which makes locating components very easy. Hopefully this will be corrected in the future. In the meantime, you can still navigate XULPlanet using the Wayback Machine. MDC should be your first stop when looking for documentation. If you find it lacking or missing some piece of information, please consider adding it once you've found it. Everyone looking for it later will thank you for it. The AMO Developer Hub The AMO Developer Hub is a great guide for add-on developers. It includes links to tutorials and documentation, development tools, and most notably, the Mozilla Add-ons Forum. This is a great place to ask qu...
...ther extensions. There are thousands of extensions out there, and you may strike luck and find one that does exactly what you need. Be sure to look at the license the extension's code is released with before thinking about copying large sections of it. Also, remember to give credit when it's due. Mozilla's Bugzilla repository. Pretty much every code change done in Firefox and Mozilla projects is documented in this huge tracking database. But this also means that finding exactly what you need can be time-consuming, and often fruitless. The advanced search is very useful in filtering results, but it is our experience that it's often better to be too general than too specific. Better to scan a list of hundreds of bugs than getting no results at all, right? Anywhere else. Use your favorite search en...
Documentation for BiDi Mozilla - Archive of obsolete content
IBMBIDI), written by Simon Montagu and posted to the mozilla-layout mailing list. While it was published in 2001 and might not be totally accurate, it does help understanding the internals of the BiDi code. Overview of BiDi processing Bidi text is reordered according to the Unicode Bidi Algorithm (UBA). The implementation is based on IBM's International Components for Unicode (ICU), which was chosen after comparing and testing the available open-source implementations. ...
...lgorithm (UBA). The implementation is based on IBM's International Components for Unicode (ICU), which was chosen after comparing and testing the available open-source implementations. As far as we could discover, ICU is the only one which is 100% compatible with UBA, including support for explicit directional controls (LRO, RLO, etc, and their HTML equivalents). Bidi processing for a given HTML document will only take place if one of the following is true: The page includes a Hebrew or Arabic character or a Hindi digit. This is determined in nsTextFragment::SetTo The page includes a element with the attribute dir=rtl, either explicitly (nsGenericHTMLElement::MapCommonAttributesInto), or as a consequence of a style rule (MapDeclarationTextInto in nsCSSStyleRule.cpp) All these cases use nsDocume...
...e includes a Hebrew or Arabic character or a Hindi digit. This is determined in nsTextFragment::SetTo The page includes a element with the attribute dir=rtl, either explicitly (nsGenericHTMLElement::MapCommonAttributesInto), or as a consequence of a style rule (MapDeclarationTextInto in nsCSSStyleRule.cpp) All these cases use nsDocument::EnableBidi to set the flag mBidiEnabled. In a Bidi-enabled document, the following things happen: During a reflow, nsBidiPresUtils::Resolve is called. This method uses the UBA to determine the directional properties of the text and reorder frames if necessary. If necessary, text frames are split so that every frame has the same directionality. FrameManager::SetFrameProperty is used to set the following flags and pointers (for terminology see the specification o...
... "Logical" mode, the text copied into the clipboard is converted (if needed) so that a Logical application will display it (from a Bidi point of view) as it is displayed by Mozilla. Text pasted from the clipboard is treated exactly as if it came from a Logical source. Form controls: based on Bidi Options in Preferences, the text mode of form controls may be "Logical", "Visual" or "Like Containing Document". We have also tested behaviour of all controls with dir=rtl and added support where necessary. Some support added for alignment in tables and lists, and fixes for problems with different combinations of dir and align. Improvements to lists with Hebrew and Arabic list-style-type Summary of New Classes Class Name XPCOM interface (if applicable) Implementation Comments nsIBidi intl\unicharut...
Tamarin build documentation - Archive of obsolete content
Supported platforms Tamarin currently supports the following operating systems and/or architectures. Windows 32 and 64 bit Mac OSX 10.4, 10.5 on PPC Mac OSX 10.5, 10.6 on Intel Linux 32 and 64 bit Solaris 10 on SPARC Android 2.2 on ARM Windows Mobile 6.5 MIPS (Linux) SH4 (Linux) Getting the Tamarin source The Tamarin source resides in Mercurial at Tamarin Central. ...
...rts the following operating systems and/or architectures. Windows 32 and 64 bit Mac OSX 10.4, 10.5 on PPC Mac OSX 10.5, 10.6 on Intel Linux 32 and 64 bit Solaris 10 on SPARC Android 2.2 on ARM Windows Mobile 6.5 MIPS (Linux) SH4 (Linux) Getting the Tamarin source The Tamarin source resides in Mercurial at Tamarin Central. Active development source resides at Tamarin Redux. In this document replace instances of tamarin-central with tamarin-redux to operate in the redux repository. Use the following command to create a copy of the Tamarin repository: $ hg clone http://hg.mozilla.org/tamarin-central tamarin-central Tips for working with Mercurial can be found here. Building Tamarin Building Tamarin will create all the libraries for the AVMPlus and garbage collector (MMgc), and c...
...r build --enable-debug - Debug build For verbose build of Tamarin, you can pass CPPFLAGS to make. $ make CPPFLAGS=-DAVMPLUS_VERBOSE Additional instructions for non-android cross-platform Tamarin-redux build on OSX 10.6 (Snow Leopard) (To build Tamarin-central on Mac please see previous cross-platform instructions here: https://developer.mozilla.org/index.php?title=En/Tamarin/Tamarin_Build_Documentation&revision=21 The bug when building on Snow Leopard (Bug 537817) has been fixed in the Tamarin-redux repo. The work for that fix also included some changes to the configure.py default behavior to decouple the --target switch from sdk choice: There is a new switch, --mac-sdk, that selects the 10.4u, 10.5 or 10.6 sdk. Its options are '104u', '105' or '106' (Note: no '.') If you don't pass ...
...s that they would like to have tested in the automated build/test process prior to actually pushing the changes. The Sandbox is setup so that it is able to build and test branches that are based on either tamarin-central or tamarin-tracing. Any comments, questions or problems can be directed to ActionScript QE How to Setup a user repository with the source and patches that will be compiled. Documentation on how to setup a user repository http://developer.mozilla.org/En/Publishing_Mercurial_Clones. Push any changes that you want to test into this repository. Request a build via the form at http://tamarin-builds.mozilla.org/build_trigger/requestbuild.cfm User Email: Your email address. An email with the build status will be sent to this address when a builder completes whether it is pas...
markupDocumentViewer - Archive of obsolete content
...
... ...
... ...
... ...
Document.body - Web APIs
Web › API › Document › body
Syntax const objRef = document.body document.body = objRef Example // Given this HTML: <body id="oldBodyElement"></body> alert(document.body.id); // "oldBodyElement" const aNewBodyElement = document.createElement("body"); aNewBodyElement.id = "newBodyElement"; document.body = aNewBodyElement; alert(document.body.id); // "newBodyElement" Notes document.body is the element that contains the content for the document. In documents with <body> contents, returns the <body> element, and in frameset documents, this returns the outermost <frameset> element. ...
... Specification Specification Status Comment HTML Living StandardThe definition of 'Document.body' in that specification. ...
... Specification Specification Status Comment HTML Living StandardThe definition of 'Document.body' in that specification. Living Standard HTML 5.1The definition of 'Document.body' in that specification. ...
... documents with <body> contents, returns the <body> element, and in frameset documents, this returns the outermost <frameset> element. Though the body property is settable, setting a new body on a document will effectively remove all the current children of the existing <body> element. Specification Specification Status Comment HTML Living StandardThe definition of 'Document.body' in that specification. Living Standard HTML 5.1The definition of 'Document.body' in that specification. Recommendation HTML5The definition of 'Document.body' in that specification. Recommendation ...
Document.createTextNode() - Web APIs
Creates a new Text node. This method can be used to escape HTML characters. Syntax var text = document.createTextNode(data); text is a Text node. data is a string containing the data to be put in the text node. ...
... Creates a new Text node. This method can be used to escape HTML characters. Syntax var text = document.createTextNode(data); text is a Text node. data is a string containing the data to be put in the text node. ...
...ates a new Text node. This method can be used to escape HTML characters. Syntax var text = document.createTextNode(data); text is a Text node. data is a string containing the data to be put in the text node. ...
... Living Standard ...
Document.doctype - Web APIs
Web › API › Document › doctype
Syntax doctype = document.doctype; doctype is a read-only property. Example var doctypeObj = document.doctype; console.log( "doctypeObj.name: " + doctypeObj.name + "\n" + "doctypeObj.internalSubset: " + doctypeObj.internalSubset + "\n" + "doctypeObj.publicId: " + doctypeObj.publicId + "\n" + "doctypeObj.systemId: " + doctypeObj.systemId ); Notes The property returns null if there is no DTD associated with the current document. DOM level 2 doesn't support editing the document type declaration. ...
... Specifications Specification Status Comment DOMThe definition of 'Document: doctype' in that specification. ...
... Specifications Specification Status Comment DOMThe definition of 'Document: doctype' in that specification. Living Standard ...
... Living Standard ...
Document: drag event - Web APIs
iv is draggable </div> </div> <div class="dropzone"></div> <div class="dropzone"></div> <div class="dropzone"></div> CSS #draggable { width: 200px; height: 20px; text-align: center; background: white; } .dropzone { width: 200px; height: 20px; background: blueviolet; margin-bottom: 10px; padding: 10px; } JavaScript var dragged; /* events fired on the draggable target */ document.addEventListener("drag", function(event) { }, false); document.addEventListener("dragstart", function(event) { // store a ref. on the dragged elem dragged = event.target; // make it half transparent event.target.style.opacity = .5; }, false); document.addEventListener("dragend", function(event) { // reset the transparency event.target.style.opacity = ""; }, false); /* events fired...
..., function(event) { }, false); document.addEventListener("dragstart", function(event) { // store a ref. ...
... dragged = event.target; // make it half transparent event.target.style.opacity = .5; }, false); document.addEventListener("dragend", function(event) { // reset the transparency event.target.style.opacity = ""; }, false); /* events fired on the drop targets */ document.addEventListener("dragover", function(event) { // prevent default to allow drop event.preventDefault(); }, false); document.addEventListener("dragenter", function(event) { // highlight potential drop target when the draggable element enters it if (event.target.className == "dropzone") { event.target.style.background = "purple"; } }, false); document.addEventListener("dragleave", function(event) { // reset background of potential drop target when the draggable element leaves it if (event.target.classNam...
...op target when the draggable element enters it if (event.target.className == "dropzone") { event.target.style.background = "purple"; } }, false); document.addEventListener("dragleave", function(event) { // reset background of potential drop target when the draggable element leaves it if (event.target.className == "dropzone") { event.target.style.background = ""; } }, false); document.addEventListener("drop", function(event) { // prevent default action (open as link for some elements) event.preventDefault(); // move dragged elem to the selected drop target if (event.target.className == "dropzone") { event.target.style.background = ""; dragged.parentNode.removeChild( dragged ); event.target.appendChild( dragged ); } }, false); Specifications S...
Document.enableStyleSheetsForSet() - Web APIs
All style sheets with a title that match this name will be enabled, while all others that have a title will be disabled. Specify an empty string for the name parameter to disable all alternate and preferred style sheets (but not the persistent style sheets; that is, those with no title attribute). ...
...e sheets (but not the persistent style sheets; that is, those with no title attribute). Notes Title matches are case-sensitive. ...
...nt style sheets; that is, those with no title attribute). Notes Title matches are case-sensitive. ...
...e attribute). Notes Title matches are case-sensitive. ...
Document.exitFullscreen() - Web APIs
This usually reverses the effects of a previous call to Element.requestFullscreen(). Syntax exitPromise = document.exitFullscreen(); Parameters None. Return value A Promise which is resolved once the user agent has finished exiting full-screen mode. If an error occurs while attempting to exit full-screen mode, the catch() handler for the promise is called. Example This example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it. ...
...ally reverses the effects of a previous call to Element.requestFullscreen(). Syntax exitPromise = document.exitFullscreen(); Parameters None. Return value A Promise which is resolved once the user agent has finished exiting full-screen mode. If an error occurs while attempting to exit full-screen mode, the catch() handler for the promise is called. Example This example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it. ...
...exitFullscreen(); Parameters None. Return value A Promise which is resolved once the user agent has finished exiting full-screen mode. If an error occurs while attempting to exit full-screen mode, the catch() handler for the promise is called. Example This example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it. document.onclick = function (event) { if (document.fullscreenElement) { document.exitFullscreen() .then(() => console.log("Document Exited form Full screen mode")) .catch((err) => console.error(err)) } else { document.documentElement.requestFullscreen(); } } Note: For a more complete example, see the Example in Element.requestFullscreen(). Specifications Specificati...
...document.exitFullscreen() .then(() => console.log("Document Exited form Full screen mode")) .catch((err) => console.error(err)) } else { document.documentElement.requestFullscreen(); } } Note: For a more complete example, see the Example in Element.requestFullscreen(). Specifications Specification Status Comment Fullscreen APIThe definition of 'Document.exitFullscreen()' in that specification. Living Standard Initial definition ...
Document.fullscreen - Web APIs
Syntax var isFullScreen = document.fullscreen; Value A Boolean value which is true if the document is currently displaying an element in full-screen mode; otherwise, the value is false. ...
...he obsolete Document interface's fullscreen read-only property reports whether or not the document is currently displaying content in full-screen mode. Although this property is read-only, it will not throw if it is modified (even in strict mode); the setter is a no-operation and it will be ignored. Note: Since this property is deprecated, you can determine if full-screen mode is active on the document by checking to see if Document.fullscreenElement is not null. Syntax var isFullScreen = document.fullscreen; Value A Boolean value which is true if the document is currently displaying an element in full-screen mode; otherwise, the value is false. Example This simple function reports whether or not full-screen mode is currently active, using the obsolete fullscreen property. function isD...
...creenElement is not null. Syntax var isFullScreen = document.fullscreen; Value A Boolean value which is true if the document is currently displaying an element in full-screen mode; otherwise, the value is false. Example This simple function reports whether or not full-screen mode is currently active, using the obsolete fullscreen property. function isDocumentInFullScreenMode() { return document.fullscreen; } This next example, on the other hand, uses the current fullscreenElement property to determine the same thing: function isDocumentInFullScreenMode() { return document.fullscreenElement !== null; } If fullscreenElement isn't null, this returns true, indicating that full-screen mode is in effect. Specifications Specification Status Comment Fullscree...
...xt example, on the other hand, uses the current fullscreenElement property to determine the same thing: function isDocumentInFullScreenMode() { return document.fullscreenElement !== null; } If fullscreenElement isn't null, this returns true, indicating that full-screen mode is in effect. Specifications Specification Status Comment Fullscreen APIThe definition of 'Document.fullscreen' in that specification. Living Standard Initial definition (as an obsolete property). ...
Document.getBoxObjectFor() - Web APIs
Returns a boxObject (x, y, width, height) for a specified element. Note: This method is obsolete. You should use the element.getBoundingClientRect() method instead. Syntax boxObject = document.getBoxObjectFor(element); boxObject is an nsIBoxObject. element is a DOMElement. ...
... Returns a boxObject (x, y, width, height) for a specified element. Note: This method is obsolete. You should use the element.getBoundingClientRect() method instead. Syntax boxObject = document.getBoxObjectFor(element); boxObject is an nsIBoxObject. element is a DOMElement. ...
... Returns a boxObject (x, y, width, height) for a specified element. Note: This method is obsolete. You should use the element.getBoundingClientRect() method instead. Syntax boxObject = document.getBoxObjectFor(element); boxObject is an nsIBoxObject. element is a DOMElement. ...
...etBoundingClientRect() method instead. Syntax boxObject = document.getBoxObjectFor(element); boxObject is an nsIBoxObject. element is a DOMElement. Example var myDiv = document.getElementById("myDiv"), boxObj = document.getBoxObjectFor (myDiv); alert ( "x:" + boxObj.x + ", y:" + boxObj.y + ", Width:" + boxObj.width + ", Height:" + boxObj.height ); Notes Specified in nsIXULDocument.idl ...
Document: gotpointercapture event - Web APIs
res a pointer using setPointerCapture(). Bubbles No Cancelable No Interface PointerEvent Event handler property ongotpointercapture Examples This example gets a <p> element and listens for the gotpointercapture event. It then calls setPointerCapture() on the element on a pointerdown event, which will trigger gotpointercapture. ...
...Capture(). Bubbles No Cancelable No Interface PointerEvent Event handler property ongotpointercapture Examples This example gets a <p> element and listens for the gotpointercapture event. It then calls setPointerCapture() on the element on a pointerdown event, which will trigger gotpointercapture. ...
...he element on a pointerdown event, which will trigger gotpointercapture. ...
...ent, which will trigger gotpointercapture. ...
Document.location - Web APIs
Web › API › Document › location
This means that you can work with document.location as if it were a string in most cases: document.location = 'http://www.example.com' is a synonym of document.location.href = 'http://www.example.com'. To retrieve just the URL as a string, the read-only document.URL property can also be used. If the current document is not in a browsing context, the returned value is null. ...
... The Document.location read-only property returns a Location object, which contains information about the URL of the document and provides methods for changing that URL and loading another URL. Though Document.location is a read-only Location object, you can also assign a DOMString to it. This means that you can work with document.location as if it were a string in most cases: document.location = 'http://www.example.com' is a synonym of document.location.href = 'http://www.example.com'. To retrieve just the URL as a string, the read-only document.URL property can also be used. If the current document is not in a browsing context, the returned value is null. ...
...his means that you can work with document.location as if it were a string in most cases: document.location = 'http://www.example.com' is a synonym of document.location.href = 'http://www.example.com'. To retrieve just the URL as a string, the read-only document.URL property can also be used. If the current document is not in a browsing context, the returned value is null. Syntax locationObj = document.location document.location = 'http://www.mozilla.org' // Equivalent to document.location.href = 'http://www.mozilla.org' Examples console.log(document.location); // Prints a Location object to the console Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.location' in that specification. Living Standard No change fro...
... Recommendation Initial definition. ...
Document: lostpointercapture event - Web APIs
ed pointer is released. Bubbles No Cancelable No Interface PointerEvent Event handler property onlostpointercapture Examples This example listens for the lostpointercapture event, and captures the pointer for an element on pointerdown. When the user subsequently releases the pointer, the lostpointercapture event will be fired. ...
... Bubbles No Cancelable No Interface PointerEvent Event handler property onlostpointercapture Examples This example listens for the lostpointercapture event, and captures the pointer for an element on pointerdown. When the user subsequently releases the pointer, the lostpointercapture event will be fired. ...
... releases the pointer, the lostpointercapture event will be fired. ...
...tpointercapture event will be fired. ...
Document.onfullscreenchange - Web APIs
If it's null, the event indicates a transition out of full-screen mode. Otherwise, the specified element is about to take over the screen. ...
... The Document interface's onfullscreenchange property is an event handler for the fullscreenchange event that is fired immediately before a document transitions into or out of full-screen mode. Syntax targetDocument.onfullscreenchange = fullscreenChangeHandler; Value An event handler which is invoked whenever the document receives a fullscreenchange event, indicating that the document is transitioning into or out of full-screen mode. Usage notes The fullscreenchange event does not directly specify whether the transition is into or out of full-screen mode, so your event handler should look at the value of Document.fullscreenElement. ...
...transitioning into or out of full-screen mode. Usage notes The fullscreenchange event does not directly specify whether the transition is into or out of full-screen mode, so your event handler should look at the value of Document.fullscreenElement. If it's null, the event indicates a transition out of full-screen mode. Otherwise, the specified element is about to take over the screen. ...
...es not directly specify whether the transition is into or out of full-screen mode, so your event handler should look at the value of Document.fullscreenElement. If it's null, the event indicates a transition out of full-screen mode. Otherwise, the specified element is about to take over the screen. Example document.onfullscreenchange = function ( event ) { console.log("FULL SCREEN CHANGE") }; document.documentElement.onclick = function () { // requestFullscreen() must be in an event handler or it will fail document.documentElement.requestFullscreen(); } Specifications Specification Status Comment Fullscreen APIThe definition of 'onfullscreenchange' in that specification. Living Standard Initial definition. ...
Document.styleSheetSets - Web APIs
The styleSheetSets read-only property returns a live list of all of the currently-available style sheet sets. Syntax var sets = document.styleSheetSets; On return, sets is a list of style sheet sets that are available. ...
... The styleSheetSets read-only property returns a live list of all of the currently-available style sheet sets. Syntax var sets = document.styleSheetSets; On return, sets is a list of style sheet sets that are available. ...
...s a live list of all of the currently-available style sheet sets. Syntax var sets = document.styleSheetSets; On return, sets is a list of style sheet sets that are available. ...
...etSets; On return, sets is a list of style sheet sets that are available. Example Given an <ul> (list) element with the ID "sheetList", you can populate it with the names of all the available style sheet sets with code like this: let list = document.getElementById('sheetList'); let sheets = document.styleSheetSets; list.innerHTML = ''; for (let i = 0; i < sheets.length; i++) { let item = document.createElement('li'); item.innerHTML = sheets[i]; list.appendChild(item); } Notes The list of available style sheet sets is constructed by enumerating all the style sheets available for the document, in the order in which they're listed in the document.styleSheets attribute, adding the title of each style sheet that has a title to the list. Duplicates are dropped from the list (using a case...
Document.visibilityState - Web APIs
It is useful to know if the document is in the background or an invisible tab, or only loaded for pre-rendering. Possible values are: 'visible' The page content may be at least partially visible. In practice this means that the page is the foreground tab of a non-minimized window. 'hidden' The page content is not visible to the user. In practice this means that the document is either a background tab or part of a minimized window, or the OS screen lock is active. 'prerender' The page content is being prerendered and is not visible to the user (considered hidden for purposes of document.hidden). ...
...ible. In practice this means that the page is the foreground tab of a non-minimized window. 'hidden' The page content is not visible to the user. In practice this means that the document is either a background tab or part of a minimized window, or the OS screen lock is active. 'prerender' The page content is being prerendered and is not visible to the user (considered hidden for purposes of document.hidden). The document may start in this state, but will never transition to it from another value. Note: This was removed from the standard. Check compatibility table for details. ...
...tive. 'prerender' The page content is being prerendered and is not visible to the user (considered hidden for purposes of document.hidden). The document may start in this state, but will never transition to it from another value. Note: This was removed from the standard. Check compatibility table for details. When the value of this property changes, the visibilitychange event is sent to the Document. Typical use of this can be to prevent the download of some assets when the document is solely prerendered, or stop some activities when the document is in the background or minimized. Syntax var string = document.visibilityState Examples document.addEventListener("visibilitychange", function() { console.log( document.visibilityState ); // Modify behavior... }); Specifications ...
... prerendered, or stop some activities when the document is in the background or minimized. Syntax var string = document.visibilityState Examples document.addEventListener("visibilitychange", function() { console.log( document.visibilityState ); // Modify behavior... }); Specifications Specification Status Comment Page Visibility (Second Edition)The definition of 'Document.visibilityState' in that specification. Recommendation Initial definition. ...
Document.xmlVersion - Web APIs
could be removed at any time. Try to avoid using it. Returns the version number as specified in the XML declaration (e.g., <?xml version="1.0"?>) or "1.0" if the declaration is absent. This attribute was never really useful, since it always returned 1.0, and has been removed in DOM Level 4. As such, Firefox 10 no longer implements it. ...
...was never really useful, since it always returned 1.0, and has been removed in DOM Level 4. As such, Firefox 10 no longer implements it. Its primary use in the past was to detect whether or not the document was being rendered as XML rather than HTML. ...
...urned 1.0, and has been removed in DOM Level 4. As such, Firefox 10 no longer implements it. Its primary use in the past was to detect whether or not the document was being rendered as XML rather than HTML. ...
..., Firefox 10 no longer implements it. ...
DocumentOrShadowRoot.elementFromPoint() - Web APIs
If the element at the specified point belongs to another document (for example, the document of an <iframe>), that document's parent element is returned (the <iframe> itself). If the element at the given point is anonymous or XBL generated content, such as a textbox's scroll bars, then the first non-anonymous ancestor element (for example, the textbox) is returned. Elements with pointer-events set to none will be ignored, and the element below it will be returned. ...
...ame>), that document's parent element is returned (the <iframe> itself). If the element at the given point is anonymous or XBL generated content, such as a textbox's scroll bars, then the first non-anonymous ancestor element (for example, the textbox) is returned. Elements with pointer-events set to none will be ignored, and the element below it will be returned. If the method is run on another document (like an <iframe>'s subdocument), the coordinates are relative to the document where the method is being called. If the specified point is outside the visible bounds of the document or either coordinate is negative, the result is null. If you need to find the specific position inside the element, use Document.caretPositionFromPoint(). ...
... 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. ...
...t 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> <button onclick="changeColor('red');">Red</button> Th...
DocumentOrShadowRoot.fullscreenElement - Web APIs
Although this property is read-only, it will not throw if it is modified (even in strict mode); the setter is a no-operation and it will be ignored. Syntax var element = document.fullscreenElement; Return value The Element object that's currently in full-screen mode; if full-screen mode isn't currently in use by the document>, the returned value is null. ...
... The DocumentOrShadowRoot.fullscreenElement read-only property returns the Element that is currently being presented in full-screen mode in this document, or null if full-screen mode is not currently in use. Although this property is read-only, it will not throw if it is modified (even in strict mode); the setter is a no-operation and it will be ignored. Syntax var element = document.fullscreenElement; Return value The Element object that's currently in full-screen mode; if full-screen mode isn't currently in use by the document>, the returned value is null. ...
...de); the setter is a no-operation and it will be ignored. Syntax var element = document.fullscreenElement; Return value The Element object that's currently in full-screen mode; if full-screen mode isn't currently in use by the document>, the returned value is null. Example This example presents a function, isVideoInFullscreen(), which looks at the value returned by fullscreenElement; if the document is in full-screen mode (fullscreenElement isn't null) and the full-screen element's nodeName is VIDEO, indicating a <video> element, the function returns true, indicating that the video is in full-screen mode. ...
...e is null. Example This example presents a function, isVideoInFullscreen(), which looks at the value returned by fullscreenElement; if the document is in full-screen mode (fullscreenElement isn't null) and the full-screen element's nodeName is VIDEO, indicating a <video> element, the function returns true, indicating that the video is in full-screen mode. function isVideoInFullscreen() { if (document.fullscreenElement && document.fullscreenElement.nodeName == 'VIDEO') { return true; } return false; } Specifications Specification Status Comment Fullscreen APIThe definition of 'Document.fullscreenElement' in that specification. Living Standard Initial definition ...
DocumentTimeline - Web APIs
Properties This interface inherits its property from its parent, AnimationTimeline. AnimationTimeline.currentTime Returns the time value in milliseconds for this timeline or null if it is inactive. Examples We could share a single documentTimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. ...
...ment.timeline). Constructor DocumentTimeline() Creates a new DocumentTimeline object associated with the active document of the current browsing context. Properties This interface inherits its property from its parent, AnimationTimeline. AnimationTimeline.currentTime Returns the time value in milliseconds for this timeline or null if it is inactive. Examples We could share a single documentTimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. ...
...meline. AnimationTimeline.currentTime Returns the time value in milliseconds for this timeline or null if it is inactive. Examples We could share a single documentTimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. ...
...onds for this timeline or null if it is inactive. Examples We could share a single documentTimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. This bit of code would start all the cats animating 500 milliseconds into their animations: const cats = document.querySelectorAll('.sharedTimelineCat'); const sharedTimeline = new DocumentTimeline({ originTime: 500 }); for (const cat of cats) { const catKeyframes = new KeyframeEffect(cat, keyframes, timing); const catAnimation = new Animation(catKeyframes, sharedTimeline); catAnimation.play(); } Specifications Specification Status Comment Web AnimationsThe definition of 'DocumentTimeline' in that specification. Working Draft Editor's draft. ...
XMLDocument.async - Web APIs
Web › API › XMLDocument › async
document.async can be set to indicate whether a XMLDocument.load() call should be an asynchronous or synchronous request. true is the default value, indicating that documents should be loaded asynchronously. ...
... document.async can be set to indicate whether a XMLDocument.load() call should be an asynchronous or synchronous request. true is the default value, indicating that documents should be loaded asynchronously. ...
...cate whether a XMLDocument.load() call should be an asynchronous or synchronous request. true is the default value, indicating that documents should be loaded asynchronously. ...
...d() call should be an asynchronous or synchronous request. ...
<head>: The Document Metadata (Header) element - HTML: Hypertext Markup Language
Web › HTML › Element › head
Otherwise, one or more elements of metadata content where exactly one is a <title> element. ...
... Otherwise, one or more elements of metadata content where exactly one is a <title> element. ...
... Otherwise, one or more elements of metadata content where exactly one is a <title> element. ...
...ed parents An <html> element, as its first child. Implicit ARIA role No corresponding role Permitted ARIA roles No role permitted DOM interface HTMLHeadElement Attributes This element includes the global attributes. profile The URIs of one or more metadata profiles, separated by white space. Example <!doctype html> <html> <head> <title>Document title</title> </head> </html> Notes HTML5-compliant browsers automatically create a <head> element if its tags are omitted in the markup. This auto-creation is not guaranteed in ancient browsers. Specifications Specification Status Comment HTML Living StandardThe definition of '<head>' in that specification. Living Standard No change from latest shapshot ...
<meta>: The Document-level Metadata element - HTML: Hypertext Markup Language
Web › HTML › Element › meta
is not an encoding declaration, it can also be inside a <noscript> element, itself inside a <head> element. Implicit ARIA role No corresponding role Permitted ARIA roles No role permitted DOM interface HTMLMetaElement The type of metadata provided by the meta element can be one of the following: If the name attribute is set, the meta element provides document-level metadata, applying to the whole page. If the http-equiv attribute is set, the meta element is a pragma directive, providing information equivalent to what can be given by a similarly-named HTTP header. If the charset attribute is set, the meta element is a charset declaration, giving the character encoding in which the document is encoded. If the itemprop attribute is set, the meta eleme...
... encoded. If the itemprop attribute is set, the meta element provides user-defined metadata. Attributes This element includes the global attributes. Note: the attribute name has a specific meaning for the <meta> element, and the itemprop attribute must not be set on the same <meta> element that has any existing name, http-equiv or charset attributes. charset This attribute declares the document's character encoding. If the attribute is present, its value must be an ASCII case-insensitive match for the string "utf-8". content This attribute contains the value for the http-equiv or name attribute, depending on which is used. http-equiv Defines a pragma directive. The attribute is named http-equiv(alent) because all the allowed values are names of particular HTTP headers: conten...
... names of particular HTTP headers: content-security-policy Allows page authors to define a content policy for the current page. Content policies mostly specify allowed server origins and script endpoints which help guard against cross-site scripting attacks. content-type If specified, the content attribute must have the value "text/html; charset=utf-8". Note: Can only be used in documents served with a text/html MIME type -- not in documents served with an XML MIME type. default-style Sets the name of the default CSS style sheet set. x-ua-compatible If specified, the content attribute must have the value "IE=edge". User agents are required to ignore this pragma. refresh This instruction specifies: The number of seconds until the page should be rel...
... See standard metadata names for details about the set of standard metadata names defined in the HTML specification. Examples <meta charset="utf-8"> <!-- Redirect page after 3 seconds --> <meta http-equiv="refresh" content="3;url=https://www.mozilla.org"> S...
getBrowserForDocument - Archive of obsolete content
...
... ...
... ...
contentDocument - Archive of obsolete content
...
... ...
... ...
Document directive - MDN Web Docs Glossary: Definitions of Web-related terms
Document directives don't fall back to the default-src directive. See Document directives for a complete list. ...
... ...
... ...
mozbrowserdocumentfirstpaint
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 mozbrowserdocumentfirstpaint event is fired when a new paint occurs on any document in the browser <iframe>. General info Specification Non standard Interface CustomEvent Bubbles Yes Cancelable Yes Target <iframe> Default Action None Properties Property Type Description target Read only EventTarget The event target (the topmost target in the DOM tree). type Read only DOMString The type of event. bubbles Read only Boolean...
... Property Type Description target Read only EventTarget The event target (the topmost target in the DOM tree). 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. ...
...entTarget The event target (the topmost target in the DOM tree). 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. ...
nsIMarkupDocumentViewer
Inherits from: nsISupports Last changed in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) Method overview void scrollToNode(in nsIDOMNode node); void sizeToContent(); Attributes Attribute Type Description allowPlugins boolean If true, plugins are allowed within the doc shell. default = true. ...
...ent(); Attributes Attribute Type Description allowPlugins boolean If true, plugins are allowed within the doc shell. default = true. Obsolete since Gecko 1.8 authorStyleDisabled boolean Disable entire author style level (including HTML presentation hints) bidiCharacterSet octet Whether to force the user's character set 1 - use the document character set 2 - use the character set chosen by the user. Obsolete since Gecko 6.0 bidiControlsTextMode octet The order of bidirectional text in form controls. 1 - logical 2 - visual 3 - like the containing document. Obsolete since Gecko 2.0 bidiNumeral octet The type of numerals to display. 1 - depending on context, default is Arabic numerals 2 - depending on cont...
... forceCharacterSet ACString fullZoom float The amount by which to scale all lengths. Default is 1.0. hintCharacterSet ACString hintCharacterSetSource PRInt32 minFontSize long The minimum font size to allow. Note: This attribute was added late in the Gecko 2.0 development cycle and was implemented by the nsIMarkupDocumentViewer_MOZILLA_2_0_BRANCH interface; it was merged into this interface in Gecko 7.0. prevDocCharacterSet ACString textZoom float The amount by which to scale all text. Default is 1.0. Methods scrollToNode() Scroll the make the specified node visible. void scrollToNode( in nsIDOMNode node ); Parameters node The nsIDOMNode of the node to make vis...
Document() - Web APIs
Web › API › Document › Document
Living Standard Initial definition. ...
... Living Standard Initial definition. ...
... Living Standard Initial definition. ...
Document.createAttribute() - Web APIs
The object created a node implementing the Attr interface. The DOM does not enforce what sort of attributes can be added to a particular element in this manner. The string given in parameter is converted to lowercase. Syntax attribute = document.createAttribute(name) Parameters name is a string containing the name of the attribute. Return value A Attr node. Exceptions INVALID_CHARACTER_ERR if the parameter contains invalid characters for XML attribute. ...
... attributes can be added to a particular element in this manner. The string given in parameter is converted to lowercase. Syntax attribute = document.createAttribute(name) Parameters name is a string containing the name of the attribute. Return value A Attr node. Exceptions INVALID_CHARACTER_ERR if the parameter contains invalid characters for XML attribute. Example var node = document.getElementById("div1"); var a = document.createAttribute("my_attrib"); a.value = "newVal"; node.setAttributeNode(a); console.log(node.getAttribute("my_attrib")); // "newVal" Specifications Specification Status Comment DOMThe definition of 'Document.createAttribute()' in that specification. Living Standard Precised behavior with uppercase characters Docume...
...b"); a.value = "newVal"; node.setAttributeNode(a); console.log(node.getAttribute("my_attrib")); // "newVal" Specifications Specification Status Comment DOMThe definition of 'Document.createAttribute()' in that specification. Living Standard Precised behavior with uppercase characters Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Document.createAttribute()' in that specification. Obsolete No change. Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Document.createAttribute()' in that specification. Obsolete No change. Document Object Model (DOM) Level 1 SpecificationThe definition of 'Document.createAttribute()' in that specification. Obsolete Initial definition. ...
Document.createProcessingInstruction() - Web APIs
target is a string containing the first part of the processing instruction (i.e., <?target ... ?>) data is a string containing any information the processing instruction should carry, after the target. The data is up to you, but it can't contain ?>, since that closes the processing instruction. ...
..."mycss.css" type="text/css"?><foo/> Specifications Specification Status Comment DOMThe definition of 'createProcessingInstruction()' in that specification. Living Standard No change DOM4The definition of 'createProcessingInstruction()' in that specification. Obsolete Added more explicit definition of how the data parameter is validated. ...
...lidated. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'createProcessingInstruction()' in that specification. Obsolete Added note that the namespace of the target name is not checked whether it is well-formed, defined what is considered an illegal character for the target name and specified the returned ProcessingInstruction object more precisely. Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'createProcessingInstruction()' in that specification. Obsolete No change Document Object Model (DOM) Level 1 SpecificationThe definition of 'createProcessingInstruction()' in that specification. Obsolete Initial definition ...
Document.createTouch() - Web APIs
view The window in which the touch occurred. target The EventTarget for the touch. identifier The value for Touch.identifier. pageX The value for Touch.pageX. pageY The value for Touch.pageY. screenX The value for Touch.screenX. screenY The value for Touch.screenY. ...
...ecated and not used. clientX The value for Touch.clientX. clientY The value for Touch.clientY. radiusX The value for Touch.radiusX. radiusY The value for Touch.radiusY. rotationAngle The value for Touch.rotationAngle. force The value for Touch.force. Return value touch A Touch object configured as described by the input parameters. ...
...he value for Touch.radiusY. rotationAngle The value for Touch.rotationAngle. force The value for Touch.force. Return value touch A Touch object configured as described by the input parameters. Example This example illustrates using the Document.createTouch() method to create Touch objects. In following code snippet, two Touch objects are created for the target element. var target = document.getElementById("target"); var touch1 = Document.createTouch(window, target, 1, 15, 20, 35, 40); var touch2 = Document.createTouch(window, target, 2, 25, 30, 45, 50); Specifications Specification Status Comment Touch EventsThe definition of 'Document.createTouch()' in that specification. Recommendation Initial definition. ...
Document.currentScript - Web APIs
(For modules use import.meta instead.) It's important to note that this will not reference the <script> element if the code in the script is being called as a callback or event handler; it will only reference the element while it's initially being processed. ...
...perty returns the <script> element whose script is currently being processed and isn't a JavaScript module. (For modules use import.meta instead.) It's important to note that this will not reference the <script> element if the code in the script is being called as a callback or event handler; it will only reference the element while it's initially being processed. ...
...dules use import.meta instead.) It's important to note that this will not reference the <script> element if the code in the script is being called as a callback or event handler; it will only reference the element while it's initially being processed. Syntax var curScriptElement = document.currentScript; Example This example checks to see if the script is being executed asynchronously: if (document.currentScript.async) { console.log("Executing asynchronously"); } else { console.log("Executing synchronously"); } View Live Examples Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.currentScript' in that specification. Living Standard Initial definition ...
Document.getAnimations() - Web APIs
Examples The following code snippet will slow down all animations on a page by halving their Animation.playbackRate. ...
... The getAnimations() method of the Document interface returns an array of all Animation objects currently in effect whose target elements are descendants of the document. This array includes CSS Animations, CSS Transitions, and Web Animations. Syntax var allAnimations = Document.getAnimations(); Parameters None. Return value An Array of Animation objects, each representing one animation currently associated with elements which are descendants of the Document on which it's called. Examples The following code snippet will slow down all animations on a page by halving their Animation.playbackRate. ...
...ransitions, and Web Animations. Syntax var allAnimations = Document.getAnimations(); Parameters None. Return value An Array of Animation objects, each representing one animation currently associated with elements which are descendants of the Document on which it's called. Examples The following code snippet will slow down all animations on a page by halving their Animation.playbackRate. document.getAnimations().forEach( function (animation) { animation.playbackRate *= .5; } ); Specifications Specification Status Comment Web AnimationsThe definition of 'document.getAnimations()' in that specification. Working Draft ...
Document.getElementsByName() - Web APIs
Syntax var elements = document.getElementsByName(name); elements is a live NodeList Collection, meaning it automatically updates as new elements with the same name are added to/removed from the document. name is the value of the name attribute of the element(s). ...
... The getElementsByName() method of the Document object returns a NodeList Collection of elements with a given name in the document. Syntax var elements = document.getElementsByName(name); elements is a live NodeList Collection, meaning it automatically updates as new elements with the same name are added to/removed from the document. name is the value of the name attribute of the element(s). Example <!DOCTYPE html> <html lang="en"> <title>Example: using document.getElementsByName</title> <input type="hidden" name="up"> <input type="hidden" name="down"> <script> var up_names = document.getElementsByName("up"); console.log(up_names[0].tagName); // displays "INPUT" </script> </html> Notes The name attribute can only be applied in (X)HTML documents. The returned NodeList Collection...
...eful not to use the same string as both a name and an id. The getElementsByName method works differently in IE. There, getElementsByName() does not return all elements which may not have a name attribute (such as <span>). Both IE and Edge return an HTMLCollection, not a NodeList Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.getElementsByName()' in that specification. Living Standard Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'Document.getElementsByName()' in that specification. Obsolete Initial definition ...
Document: keypress event - Web APIs
ncelable Yes Default Action Varies: keypress event; launch text composition system; blur and focus events; DOMActivate event; other event Examples addEventListener keypress example This example logs the KeyboardEvent.code value whenever you press a key. ...
...Action Varies: keypress event; launch text composition system; blur and focus events; DOMActivate event; other event Examples addEventListener keypress example This example logs the KeyboardEvent.code value whenever you press a key. ...
...les addEventListener keypress example This example logs the KeyboardEvent.code value whenever you press a key. ...
Document: keyup event - Web APIs
en processed by an IME): eventTarget.addEventListener("keyup", event => { if (event.isComposing || event.keyCode === 229) { return; } // do something }); Examples This example logs the KeyboardEvent.code value whenever you release a key. ...
...rget.addEventListener("keyup", event => { if (event.isComposing || event.keyCode === 229) { return; } // do something }); Examples This example logs the KeyboardEvent.code value whenever you release a key. addEventListener keyup example <p>Focus the IFrame first (e.g. ...
...g }); Examples This example logs the KeyboardEvent.code value whenever you release a key. addEventListener keyup example <p>Focus the IFrame first (e.g. ...
Document.lastStyleSheetSet - Web APIs
This property's value changes whenever the document.selectedStyleSheetSet property is changed. Syntax var lastStyleSheetSet = document.lastStyleSheetSet On return, lastStyleSheetSet indicates the style sheet set that was most recently set. If the current style sheet set has not been changed by setting document.selectedStyleSheetSet, the returned value is null. Note: This value doesn't change when document.enableStyleSheetsForSet() is called. ...
...property's value changes whenever the document.selectedStyleSheetSet property is changed. Syntax var lastStyleSheetSet = document.lastStyleSheetSet On return, lastStyleSheetSet indicates the style sheet set that was most recently set. If the current style sheet set has not been changed by setting document.selectedStyleSheetSet, the returned value is null. Note: This value doesn't change when document.enableStyleSheetsForSet() is called. ...
...ty is changed. Syntax var lastStyleSheetSet = document.lastStyleSheetSet On return, lastStyleSheetSet indicates the style sheet set that was most recently set. If the current style sheet set has not been changed by setting document.selectedStyleSheetSet, the returned value is null. Note: This value doesn't change when document.enableStyleSheetsForSet() is called. ...
Document.mozSetImageElement() - Web APIs
Syntax document.mozSetImageElement(imageElementId, imageElement); Parameters imageElementId is a string indicating the name of an element that has been specified as a background image using the -moz-element CSS function. imageElement is the new element to use as the background corresponding to that image element string. Specify null to remove the background element. Example This example changes the background of a <div> block each time the block is clicked by the user. View this example live. ...
...licked by the user. View this example live. <style type="text/css"> #mybox { background-image: -moz-element(#canvasbg); text-align: center; width: 400px; height: 400px; cursor: pointer; } </style> The CSS defined by the <style> block above is used by our <div> to use an element with the id "canvasbg" as its background. var c = 0x00; function clicked() { var canvas = document.createElement("canvas"); canvas.setAttribute("width", 100); canvas.setAttribute("height", 100); var ctx = canvas.getContext('2d'); ctx.fillStyle = "#" + c.toString(16) + "0000"; ctx.fillRect(25, 25, 75, 75); c += 0x11; if (c > 0xff) { c = 0x00; } document.mozSetImageElement("canvasbg", canvas); } The code here is called each time the user clicks the <div> element. It cr...
...ser clicks the <div> element. It creates a new <canvas> with the width and height set to 100 pixels, then draws into it a 50 by 50 pixel square. Each time the function is called, the square is a different color (its red component is increased each time), so each time the user clicks the element, the background is filled with a brighter and brighter pattern of red tiles. Once the canvas is drawn, document.mozSetImageElement() is called to set the background for any CSS using the ID "canvasbg" as its background element ID to be our new canvas. Specifications Not part of any specification. ...
Document: pointerlockerror event - Web APIs
The pointerlockerror event is fired when locking the pointer failed (for technical reasons or because the permission was denied). ...
... The pointerlockerror event is fired when locking the pointer failed (for technical reasons or because the permission was denied). ...
...rmission was denied). ...
Document.preferredStyleSheetSet - Web APIs
The preferredStyleSheetSet property returns the preferred style sheet set as set by the page author. Syntax preferredStyleSheetSet = document.preferredStyleSheetSet On return, preferredStyleSheetSet indicates the author's preferred style sheet set. This is determined from the order of style sheet declarations and the Default-Style HTTP header. If there isn't a preferred style sheet set defined by the author, the empty string ("") is returned. ...
...eet set as set by the page author. Syntax preferredStyleSheetSet = document.preferredStyleSheetSet On return, preferredStyleSheetSet indicates the author's preferred style sheet set. This is determined from the order of style sheet declarations and the Default-Style HTTP header. If there isn't a preferred style sheet set defined by the author, the empty string ("") is returned. ...
...tyleSheetSet On return, preferredStyleSheetSet indicates the author's preferred style sheet set. ...
Document.queryCommandEnabled() - Web APIs
Syntax isEnabled = document.queryCommandEnabled(command); Parameters command The command for which to determine support. Return value Returns a Boolean which is true if the command is enabled and false if the command isn't. Notes For 'cut' and 'copy' commands the method only returns true when called from a user-initiated thread. The 'paste' command return false not only if the feature is unavailable, but also if the script calling it has insufficient privileges to perform the action. ...
...t. Return value Returns a Boolean which is true if the command is enabled and false if the command isn't. Notes For 'cut' and 'copy' commands the method only returns true when called from a user-initiated thread. ...
...e command is enabled and false if the command isn't. Notes For 'cut' and 'copy' commands the method only returns true when called from a user-initiated thread. ...
Document: readystatechange event - Web APIs
The readystatechange event is fired when the readyState attribute of a document has changed. Bubbles No Cancelable No Interface Event Event handler property onreadystatechange Examples Live example HTML <div class="controls"> <button id="reload" type="button">Reload</button> </div> <div class="event-log"> <label>Event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea> </div> CSS body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } JS ...
...ass="event-log-contents" rows="8" cols="30"></textarea> </div> CSS body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } JS const log = document.querySelector('.event-log-contents'); const reload = document.querySelector('#reload'); reload.addEventListener('click', () => { log.textContent =''; window.setTimeout(() => { window.location.reload(true); }, 200); }); window.addEventListener('load', (event) => { log.textContent = log.textContent + 'load\n'; }); document.addEventListener('readystatechange', (event) => { log...
...oad = document.querySelector('#reload'); reload.addEventListener('click', () => { log.textContent =''; window.setTimeout(() => { window.location.reload(true); }, 200); }); window.addEventListener('load', (event) => { log.textContent = log.textContent + 'load\n'; }); document.addEventListener('readystatechange', (event) => { log.textContent = log.textContent + `readystate: ${document.readyState}\n`; }); document.addEventListener('DOMContentLoaded', (event) => { log.textContent = log.textContent + `DOMContentLoaded\n`; }); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'readystatechange' in that specification. Living Standard ...
Document.registerElement() - Web APIs
Warning: document.registerElement() is deprecated in favor of customElements.define(). The document.registerElement() method registers a new custom element in the browser and returns a constructor for the new element. Note: This is an experimental technology. The browser you use it in must support Web Components. See Enabling Web Components in Firefox. Syntax var constructor = document.registerElement(tag-name, options); Parameters tag-name The name of the custom element. The name must contain a dash (-), for example my-tag. optionsOptional An object with properties prototype to base the custom element on, and extends, an existing tag to extend. Both of these are optional. ...
...ox. Syntax var constructor = document.registerElement(tag-name, options); Parameters tag-name The name of the custom element. The name must contain a dash (-), for example my-tag. optionsOptional An object with properties prototype to base the custom element on, and extends, an existing tag to extend. Both of these are optional. Example Here is a very simple example: var Mytag = document.registerElement('my-tag'); Now the new tag is registered in the browser. The Mytag variable holds a constructor that you can use to create a my-tag element in the document as follows: document.body.appendChild(new Mytag()); This inserts an empty my-tag element that will be visible if you use the browser's developer tools. It will not be visible if you use the browser's view source capability.
...e a my-tag element in the document as follows: document.body.appendChild(new Mytag()); This inserts an empty my-tag element that will be visible if you use the browser's developer tools. It will not be visible if you use the browser's view source capability. And it won't be visible in the browser unless you add some content to the tag. ...
Document.selectedStyleSheetSet - Web APIs
The selectedStyleSheetSet property indicates the name of the style sheet set that's currently in use. Syntax currentStyleSheetSet = document.selectedStyleSheetSet; document.selectedStyleSheet = newStyleSheetSet; On return, currentStyleSheetSet indicates the name of the style sheet set currently in use. You can also set the current style sheet set using this property. Setting the value of this property is equivalent to calling document.enableStyleSheetsForSet() with the value of currentStyleSheetSet, then setting the value of lastStyleSheetSet to that value as well. ...
...operty. Setting the value of this property is equivalent to calling document.enableStyleSheetsForSet() with the value of currentStyleSheetSet, then setting the value of lastStyleSheetSet to that value as well. Note: This attribute's value is live; directly changing the disabled attribute on style sheets will affect the value of this attribute. ...
... property is equivalent to calling document.enableStyleSheetsForSet() with the value of currentStyleSheetSet, then setting the value of lastStyleSheetSet to that value as well. Note: This attribute's value is live; directly changing the disabled attribute on style sheets will affect the value of this attribute. ...
Document.timeline - Web APIs
Web › API › Document › timeline
The time values for this timeline are calculated as a fixed offset from the global clock such that the zero time corresponds to the navigationStart moment plus a signed delta known as the origin time. Prior to establishing the navigationStart moment, the document timeline is inactive. Note: A document timeline that is associated with a non-active document is also considered to be inactive. ...
...ated on page load. This timeline is unique to each document and persists for the lifetime of the document including calls to Document.open(). The time values for this timeline are calculated as a fixed offset from the global clock such that the zero time corresponds to the navigationStart moment plus a signed delta known as the origin time. Prior to establishing the navigationStart moment, the document timeline is inactive. Note: A document timeline that is associated with a non-active document is also considered to be inactive. Syntax var pageTimeline = document.timeline; var thisMoment = pageTimeline.currentTime; Value A DocumentTimeline object. ...
... navigationStart moment, the document timeline is inactive. Note: A document timeline that is associated with a non-active document is also considered to be inactive. Syntax var pageTimeline = document.timeline; var thisMoment = pageTimeline.currentTime; Value A DocumentTimeline object. Specifications Specification Status Comment Web AnimationsThe definition of 'document.timeline' in that specification. Working Draft Editor's draft. ...
Document.title - Web APIs
Web › API › Document › title
The document.title property gets or sets the current title of the document. Syntax var docTitle = document.title; docTitle is a string containing the document's title. If the title was overridden by setting document.title, it contains that value. Otherwise, it contains the title specified in the markup (see the Notes below). document.title = newTitle; newTitle is the new title of the document. The assignment affects the return value of document.title, the title displayed for the document (e.g. in the titlebar of the window or tab), and it also affects the DOM of the document (e.g. the content of the <title> element in an HTML document). ...
... newTitle is the new title of the document. The assignment affects the return value of document.title, the title displayed for the document (e.g. in the titlebar of the window or tab), and it also affects the DOM of the document (e.g. the content of the <title> element in an HTML document). Example <!DOCTYPE html> <html> <head> <title>Hello World!</title> </head> <body> <script> alert(document.title); // displays "Hello World!" document.title = "Goodbye World!"; alert(document.title); // displays "Goodbye World!" </script> </body> </html> Notes This property applies to HTML, SVG, XUL, and other documents in Gecko. For HTML documents the initial value of document.title is the text content of the <title> element. For XUL it's the value of the title attribute of the <xul:wi...
..."Goodbye World!"; alert(document.title); // displays "Goodbye World!" </script> </body> </html> Notes This property applies to HTML, SVG, XUL, and other documents in Gecko. For HTML documents the initial value of document.title is the text content of the <title> element. For XUL it's the value of the title attribute of the <xul:window> or other top-level XUL element. In XUL, accessing document.title before the document is fully loaded has undefined behavior: document.title may return an empty string and setting document.title may have no effect. Specifications Specification Status Comment HTML Living StandardThe definition of 'document.title' in that specification. Living Standard ...
Document: visibilitychange event - Web APIs
The visibilitychange event is fired at the document when the content of its tab have become visible or have been hidden. Bubbles Yes Cancelable No Interface Event Event handler property onvisibilitychange Usage notes The event doesn't include the document's updated visibility status, but you can get that information from the document's visibilityState property. Examples This example begins playing a music track when the document becomes visible, and pauses the music when the document is no longer visible. ...
... Interface Event Event handler property onvisibilitychange Usage notes The event doesn't include the document's updated visibility status, but you can get that information from the document's visibilityState property. Examples This example begins playing a music track when the document becomes visible, and pauses the music when the document is no longer visible. document.addEventListener("visibilitychange", function() { if (document.visibilityState === 'visible') { backgroundMusic.play(); } else { backgroundMusic.pause(); } }); Specifications Specification Status Comment Page Visibility (Second Edition)The definition of 'visibilitychange' in that specification. Recommendation Browser compatibility No com...
... ...
Document: wheel event - Web APIs
Working Draft ...
... Working Draft ...
... Working Draft ...
DocumentOrShadowRoot.getSelection() - Web APIs
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. ...
...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 objects You can call Window.getSelection(), which works identically to Document.getSelection(). It is worth noting that currently getSelection() doesn't work on the content of <input> elements in Firefox. HTMLInputElement.setSelectionRange()) could be used to work around this. Notice also the difference between selection and focus. Document.activeElement returns the focused element. Specifications Specification Status Comment Shadow DOMThe definit...
... Obsolete Initial definition. ...
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. Syntax var nextNode = elementNodeReference.nextElementSibling; Example <div id="div-01">Here is div-01</div> <div id="div-02">Here is div-02</div> <script type="text/javascript"> var el = document.getElementById('div-01').nextElementSibling; console.log('Siblings of div-01:'); while (el) { console.log(el.nodeName); el = el.nextElementSibling; } </script> This example outputs the following into the console when it loads: Siblings of div-01: DIV SCRIPT Polyfill for Internet Explorer 8 This property is unsupported prior to IE9, so the following snippet can ...
...el.nextElementSibling; } </script> This example outputs the following into the console when it loads: Siblings of div-01: DIV SCRIPT Polyfill for Internet Explorer 8 This property is unsupported prior to IE9, so the following snippet can be used to add support to IE8: // Source: https://github.com/Alhadis/Snippets/blob/master/js/polyfills/IE8-child-elements.js if(!("nextElementSibling" in document.documentElement)){ Object.defineProperty(Element.prototype, "nextElementSibling", { get: function(){ var e = this.nextSibling; while(e && 1 !== e.nodeType) e = e.nextSibling; return e; } }); } Polyfill for Internet Explorer 9+ and Safari // Source: https://github.com/jserz/js_piece/blob/master/DOM/NonDocumentTypeChildNo...
...{ return el; } } return null; }, set: undefined }); }); })([Element.prototype, CharacterData.prototype]); Specifications Specification Status Comment DOMThe definition of 'ChildNodenextElementSibling' in that specification. Living Standard Split the ElementTraversal interface in ChildNode, ParentNode, and NonDocumentTypeChildNode. This method is now defined on the former. The Element and CharacterData interfaces implemented the new interface. Element Traversal SpecificationThe definition of 'ElementTraversal.nextElementSibling' in that specification. Obsolete Added its initial definition to the ElementTraversal pure interface and use it on Element. Browser compatibility The compati...
NonDocumentTypeChildNode - Web APIs
The NonDocumentTypeChildNode interface contains methods that are particular to Node objects that can have a parent, but not suitable for DocumentType. NonDocumentTypeChildNode is a raw interface and no object of this type can be created; it is implemented by Element, and CharacterData objects. Properties There are no inherited properties. NonDocumentTypeChildNode.previousElementSibling Read only Returns the Element immediately prior to this node in its parent's children list, or null if there is no Element in the list prior to this node. NonDocumentTypeChildNode.nextElementSibling Read only Returns the Element immediately following this node in its parent's children list, or null if there is no Element in the list following this node. Methods There are neither inherited nor specific...
...The previousElementSibling and nextElementSibling are now defined on the latter. The CharacterData and Element implemented the new interfaces. ...
...The previousElementSibling and nextElementSibling are now defined on the latter. ...
<base>: The Document Base URL element - HTML: Hypertext Markup Language
Web › HTML › Element › base
Content categories Metadata content. Permitted content None, it is an empty element. Tag omission There must be no closing tag. Permitted parents A <head> that doesn't contain another <base> element. ...
...orresponding role Permitted ARIA roles No role permitted DOM interface HTMLBaseElement Attributes This element's attributes include the global attributes. If either of the following attributes are specified, this element must come before other elements with attribute values of URLs, such as <link>'s href attribute. href The base URL to be used throughout the document for relative URLs. Absolute and relative URLs are allowed. target A keyword or author-defined name of the default browsing context to show the results of navigation from <a>, <area>, or <form> elements without explicit target attributes. The following keywords have special meanings: _self (default): Show the result in the current browsing context. _blank: Show the result in a new, unname...
...lf. _top: Show the result in the topmost browsing context (the browsing context that is an ancestor of the current one and has no parent). If there is no parent, acts the same as _self. Usage notes Multiple <base> elements If multiple <base> elements are used, only the first href and first target are obeyed -- all others are ignored. In-page anchors Links pointing to a fragment in the document -- e.g. <a href="#some-id"> -- are resolved with the <base>, triggering an HTTP request to the base URL with the fragment attached. For example: Given <base href="https://example.com"> ...and this link: <a href="#anchor">Anker</a> ...the link points to https://example.com/#anchor. Open Graph Open Graph tags do not acknowledge <base>, and should always have full absolute URLs. For example:...
Feature-Policy: document-domain - HTTP
The HTTP Feature-Policy header document-domain directive controls whether the current document is allowed to set document.domain. When this policy is enabled, attempting to set document.domain will fail and cause a SecurityError DOMException to be be thrown. Syntax Feature-Policy: document-domain <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The default value is *. Specifications Specification Status Comment HTML Living StandardThe definition of 'document-domain' in that specification. Living Standard ...
getBrowserIndexForDocument - Archive of obsolete content
The returned index is dependent on the tabs in the tabbrowser and is invalidated when the tab ordering changes. ...
...The returned index is dependent on the tabs in the tabbrowser and is invalidated when the tab ordering changes. ...
Tamarin Tracing Build Documentation - Archive of obsolete content
Tamarin Source Versions The following instructions are for obtaining and building the Tamarin Tracing source code. ...
...e changes that they would like to have tested in the automated build/test process prior to actually pushing the changes. The Sandbox is setup so that it is able to build and test branches that are based on either tamarin-central or tamarin-tracing. Any comments, questions or problems can be directed to Brent Baker How To Setup a user repository with the source and patches that will be compiled. Documentation on how to setup a user repository http://developer.mozilla.org/En/Publishing_Mercurial_Clones. Push any changes that you want to test into this repository. Request a build via the form at http://tamarin-builds.mozilla.org/build_trigger/requestbuild.cfm User Email: Your email address. An email with the build status will be sent to this address when a builder completes whether it is passes o...
document environment - MDN Web Docs Glossary: Definitions of Web-related terms
When the JavaScript global environment is a window or an iframe, it is called a document environment. A global environment is an environment that doesn't have an outer environment. ...
... When the JavaScript global environment is a window or an iframe, it is called a document environment. A global environment is an environment that doesn't have an outer environment. ...
SpiderMonkey Build Documentation
Use these instructions to build the latest SpiderMonkey source code. Before you begin, make sure you have the right build tools for your computer: Linux, Windows, Mac, others. When building a version older than 28, you'll additionally need NSPR. And of course, you'll need to get the SpiderMonkey source code. Non-developer (optimized) build Use these steps if you want to install SpiderMonkey for production use or run performance benchmarks. ...
... You must have started your MozillaBuild shell with the proper -x64.bat script in order for the 64-bit compilers to be in your PATH. Whatever compiler and flags you pass to configure are recorded in the generated makefile, so you don't need to specify them again until you re-run configure. Building your application While "How to build your complete application" is clearly out of scope for this document, here are some tips that will help get you on your way: The SpiderMonkey developers frequently and deliberately change the JSAPI ABI. You cannot use headers built for one version/configuration of JSAPI to create object files which will be linked against another. Support for JS_THREADSAFE was recently removed, and threadsafe builds are now enabled by default. The js-config script, described b...
Document: animationiteration event - Web APIs
at the same time as the animationend event, and therefore does not occur for animations with an animation-iteration-count of one. Bubbles Yes Cancelable No Interface AnimationEvent Event handler property onanimationiteration The original target for this event is the Element that had the animation applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationiteration. Examples This code uses animationiteration to keep track of the number of iterations an animation has completed: let iterationCount = 0; document.addEventListener('animationiteration', () => { iterationCount++; console.log(`Animation iteration co...
...animationiteration. Examples This code uses animationiteration to keep track of the number of iterations an animation has completed: let iterationCount = 0; document.addEventListener('animationiteration', () => { iterationCount++; console.log(`Animation iteration count: ${iterationCount}`); }); The same, but using the onanimationiteration event handler property: let iterationCount = 0; document.onanimationiteration = () => { iterationCount++; console.log(`Animation iteration count: ${iterationCount}`); }; See a live example of this event. Specifications Specification Status Comment CSS Animations Working Draft Initial definition ...
Document.clear() - Web APIs
Web › API › Document › clear
In recent versions of Mozilla-based applications, as well as in Internet Explorer and Netscape 4, this method does nothing. ...
... The Document.clear() method clears the whole specified document in early (pre-1.0) versions of Mozilla. ...
Document.createCDATASection() - Web APIs
createCDATASection() creates a new CDATA section node, and returns it. Syntax var CDATASectionNode = document.createCDATASection(data); CDATASectionNode is a CDATA Section node. data is a string containing the data to be added to the CDATA Section. Example var docu = new DOMParser().parseFromString('<xml></xml>', 'application/xml') var cdata = docu.createCDATASection('Some <CDATA> data & then some'); docu.getElementsByTagName('xml')[0].appendChild(cdata); alert(new XMLSerializer().serializeToString(docu)); // Displays: <xml><![CDATA[Some <CDATA> data & then some]]></xml> Notes This will only work with XML, not HTML documents (as HTML documents do not support CDATA sections); attempting it on an HTML document will throw NOT_SUPPORTED_ERR. Will throw a NS_ERROR_DOM_INVALID_CHARAC...
...PORTED_ERR. Will throw a NS_ERROR_DOM_INVALID_CHARACTER_ERR exception if one tries to submit the closing CDATA sequence ("]]>") as part of the data, so unescaped user-provided data cannot be safely used without with this method getting this exception (createTextNode() can often be used in its place). Specifications Specification Status Comment DOMThe definition of 'document.createCDATASection' in that specification. Living Standard ...
Document.createEvent() - Web APIs
Many methods used with createEvent, such as initCustomEvent, are deprecated. Use event constructors instead. Creates an event of the type specified. The returned object should be first initialized and can then be passed to EventTarget.dispatchEvent. Syntax var event = document.createEvent(type); event is the created Event object. type is a string that represents the type of event to be created. Possible event types include "UIEvents", "MouseEvents", "MutationEvents", and "HTMLEvents". See Notes section for details. Example // Create the event. var event = document.createEvent('Event'); // Define that the event name is 'build'. event.initEvent('build', true, true); // Listen for the event. elem.addEventListener('build', function (e) { // e.target matches elem }, false); ...
...some non-standard event object aliases, which are listed below. Event Module Standard event object Gecko also supports Text event module TextEvent TextEvents Keyboard event module KeyboardEvent KeyEvents Basic events module Event Events Specifications Specification Status Comment DOMThe definition of 'document.createEvent' in that specification. Living Standard ...
Document.createNSResolver() - Web APIs
Creates an XPathNSResolver which resolves namespaces with respect to the definitions in scope for a specified node. Syntax nsResolver = document.createNSResolver(node); Parameters node is the node to be used as a context for namespace resolution. Return value nsResolver is an XPathNSResolver object. Notes Adapts any DOM node to resolve namespaces so that an XPath expression can be easily evaluated relative to the context of the node where it appeared within the document. This adapter works like the DOM Level 3 method lookupNamespaceURI on nodes in resolving the namespaceURI from a given prefix using the current information available in the node's hierarchy at the time lookupNamespaceURI is called. Also correctly resolves the implicit xml prefix. Note, XPath defines QNames without ...
....org/1999/xhtml and name()=p[@id='_myid'] (this approach works well for dynamic XPath expressions where the namespaces might not be known) or use prefixed name tests, and create a namespace resolver mapping the prefix to the namespace. Read more on how to create a user defined namespace resolver if you wish to take the latter approach. createNSResolver was introduced in DOM Level 3. See also document.evaluate Introduction to using XPath in JavaScript Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'document.createNSResolver' in that specification. Recommendation ...
Document.createRange() - Web APIs
Syntax range = document.createRange(); range is the created Range object. Example let range = document.createRange(); range.setStart(startNode, startOffset); range.setEnd(endNode, endOffset); Notes Once a Range is created, you need to set its boundary points before you can make use of most of its methods. Specifications Specification Status Comment DOMThe definition of 'document.createRange' in that specification. ...
...e = document.createRange(); range is the created Range object. Example let range = document.createRange(); range.setStart(startNode, startOffset); range.setEnd(endNode, endOffset); Notes Once a Range is created, you need to set its boundary points before you can make use of most of its methods. Specifications Specification Status Comment DOMThe definition of 'document.createRange' in that specification. Living Standard ...
Document.defaultView - Web APIs
Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.defaultView' in that specification. Living Standard No change HTML5The definition of 'Document.defaultView' in that specification. ...
... In browsers, document.defaultView returns the window object associated with a document, or null if none is available. Syntax var win = document.defaultView; This property is read-only. Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.defaultView' in that specification. Living Standard No change HTML5The definition of 'Document.defaultView' in that specification. Recommendation Initial definition ...
Document.designMode - Web APIs
document.designMode controls whether the entire document is editable. Valid values are "on" and "off". According to the specification, this property is meant to default to "off". Firefox follows this standard. The earlier versions of Chrome and IE default to "inherit". Starting in Chrome 43, the default is "off" and "inherit" is no longer supported. In IE6-10, the value is capitalized. Syntax var mode = document.designMode; document.designMode = value; Value A string indicating whether designMode is (or should be) set to on or off. Valid values are on and off. ...
...standard. The earlier versions of Chrome and IE default to "inherit". Starting in Chrome 43, the default is "off" and "inherit" is no longer supported. In IE6-10, the value is capitalized. Syntax var mode = document.designMode; document.designMode = value; Value A string indicating whether designMode is (or should be) set to on or off. Valid values are on and off. Example Make an <iframe>'s document editable: iframeNode.contentDocument.designMode = "on"; Specifications Specification Status Comment HTML Living StandardThe definition of 'designMode' in that specification. Living Standard Initial definition. ...
Document.featurePolicy - Web APIs
Syntax var policy = iframeElement.featurePolicy Value A FeaturePolicy object that can be used to inspect the Feature Policy settings applied to the document. ...
... The featurePolicy read-only property of the Document interface returns the FeaturePolicy interface which provides a simple API for inspecting the feature policies applied to a specific document. Syntax var policy = iframeElement.featurePolicy Value A FeaturePolicy object that can be used to inspect the Feature Policy settings applied to the document. Specification Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Document.fullscreenEnabled - Web APIs
Full-screen mode is available only for a page that has no windowed plug-ins in any of its documents, and if all <iframe> elements which contain the document have their allowfullscreen attribute set. Although this property is read-only, it will not throw if it is modified (even in strict mode); the setter is a no-operation and it will be ignored. Syntax var isFullscreenAvailable = document.fullscreenEnabled; Value A Boolean value which is true if the document and the elements within can be placed into full-screen mode by calling Element.requestFullscreen(). If full-screen mode isn't available, this value is false. ...
...ocument and the elements within can be placed into full-screen mode by calling Element.requestFullscreen(). If full-screen mode isn't available, this value is false. Example In this example, before attempting to request full-screen mode for a <video> element, the value of fullscreenEnabled is checked, in order to avoid making the attempt when not available. function requestFullScreen() { if (document.fullscreenEnabled) { videoElement.requestFullScreen(); } else { console.log('Your browser cannot use fullscreen right now'); } } Specifications Specification Status Comment Fullscreen APIThe definition of 'Document.fullscreenEnabled' in that specification. Living Standard Initial definition ...
Document: fullscreenchange event - Web APIs
The fullscreenchange event is fired immediately after the browser switches into or out of full-screen mode. Bubbles Yes Cancelable No Interface Event Event handler property onfullscreenchange The event is sent to the Element that is transitioning into or out of full-screen mode, and this event then bubbles up to the Document. To find out whether the Element is entering or exiting full-screen mode, check the value of DocumentOrShadowRoot.fullscreenElement: if this value is null then the element is exiting full-screen mode, otherwise it is entering full-screen mode. Examples In this example, a handler for the fullscreenchange event is added to the Document. document.addEventListener('fullscreenchange', (event) => { // document.fullscreen...
...is exiting full-screen mode, otherwise it is entering full-screen mode. Examples In this example, a handler for the fullscreenchange event is added to the Document. document.addEventListener('fullscreenchange', (event) => { // document.fullscreenElement will point to the element that // is in fullscreen mode if there is one. If there isn't one, // the value of the property is null. if (document.fullscreenElement) { console.log(`Element: ${document.fullscreenElement.id} entered full-screen mode.`); } else { console.log('Leaving full-screen mode.'); } }); See Element: fullscreenchange event for another example. Specifications Specification Status Fullscreen API Living Standard ...
Document.hasStorageAccess() - Web APIs
See Storage Access API for more information. Syntax var promise = document.hasStorageAccess(); Parameters None. Return value A Promise that resolves with a boolean value indicating whether the document has access to its first-party storage. If the promise gets resolved and a user gesture event was being processed when the function was originally called, the resolve handler will run as if a user gesture was being processed, so it will be able to call APIs that require user activation. ...
... } else { // storage access hasn't been granted already; // you may want to call requestStorageAccess(). ...
Document.head - Web APIs
Web › API › Document › head
The head read-only property of the Document interface returns the <head> element of the current document. Syntax var objRef = document.head; Value An HTMLHeadElement. Example <!doctype html> <head id="my-document-head"> <title>Example: using document.head</title> </head> <script> var theHead = document.head; console.log(theHead.id); // "my-document-head"; console.log( theHead === document.querySelector("head") ); // true </script> Notes document.head is read-only. Trying to assign a value to this property will fail silently or, in Strict Mode, throws a TypeError . Specifications Specification Status Comment HTML 5.1The definition of 'Document.head' in that specification. ...
...( theHead === document.querySelector("head") ); // true </script> Notes document.head is read-only. Trying to assign a value to this property will fail silently or, in Strict Mode, throws a TypeError . Specifications Specification Status Comment HTML 5.1The definition of 'Document.head' in that specification. Recommendation HTML5The definition of 'Document.head' in that specification. Recommendation HTML Living StandardThe definition of 'Document.head' in that specification. Living Standard Initial definition. ...
Document.images - Web APIs
Web › API › Document › images
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". ...
...nt 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 == 'banner.gif') { // found the banner } } Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.images' in that specification. Living Standard Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'Document.images'...
Document.implementation - Web APIs
Syntax DOMImpObj = document.implementation; Example var modName = "HTML"; var modVer = "2.0"; var conformTest = document.implementation.hasFeature( modName, modVer ); alert( "DOM " + modName + " " + modVer + " supported?: " + conformTest ); // alerts with: "DOM HTML 2.0 supported?: true" if DOM Level 2 HTML module is supported. A list of module names (e.g., Core, HTML, XML, etc.) is available in the DOM Level 2 Conformance Section. Notes The W3C's DOM Level 1 Recommendation only specified the hasFeature method, which is one way to determine if a DOM module is supported by a browser (see example above and What does your user agent claim to support?). ...
...HTML, XML, etc.) is available in the DOM Level 2 Conformance Section. Notes The W3C's DOM Level 1 Recommendation only specified the hasFeature method, which is one way to determine if a DOM module is supported by a browser (see example above and What does your user agent claim to support?). If available, other DOMImplementation methods provide services for controlling things outside of a single document. For example, the DOMImplementation interface includes a createDocumentType method with which DTDs can be created for one or more documents managed by the implementation. Specifications Specification Status Comment DOMThe definition of 'document.implementation' in that specification. Living Standard ...
Document.onafterscriptexecute - Web APIs
It does not fire if the element is added dynamically, such as with appendChild(). Syntax document.onafterscriptexecute = funcRef; funcRef is a function reference, called when the event is fired. The event's target attribute is set to the <script> element that just finished executing. ...
...uting its script. It does not fire if the element is added dynamically, such as with appendChild(). Syntax document.onafterscriptexecute = funcRef; funcRef is a function reference, called when the event is fired. The event's target attribute is set to the <script> element that just finished executing. ...
Document.onbeforescriptexecute - Web APIs
Fired when the code in a <script> element declared in an HTML document is about to start executing. Does not fire if the element is added dynamically, eg with appendChild(). Syntax document.onbeforescriptexecute = funcRef; funcRef is a function reference, called when the event is fired. The event's target attribute is set to the script Element that is about to be executed. ...
... about to start executing. Does not fire if the element is added dynamically, eg with appendChild(). Syntax document.onbeforescriptexecute = funcRef; funcRef is a function reference, called when the event is fired. The event's target attribute is set to the script Element that is about to be executed. ...
Document.onfullscreenerror - Web APIs
Example This example attempts to call requestFullscreen() outside of an event handler. Since requestFullscreen() can only be called in response to user action, for security reasons, this will fail, causing the fullscreenerror to be sent to the document. document.onfullscreenerror = function ( event ) { displayWarning("Unable to switch into full-screen mode."); }; //.... ...
...Element.requestFullscreen(). Syntax targetDocument.onfullscreenerror = fullscreenErrorHandler; Value An event handler for the fullscreenerror event. Example This example attempts to call requestFullscreen() outside of an event handler. Since requestFullscreen() can only be called in response to user action, for security reasons, this will fail, causing the fullscreenerror to be sent to the document. document.onfullscreenerror = function ( event ) { displayWarning("Unable to switch into full-screen mode."); }; //.... document.documentElement.requestFullscreen(); Specifications Specification Status Comment Fullscreen APIThe definition of 'onfullscreenerror' in that specification. Living Standard Initial definition. ...
Document.ononline - Web APIs
Web › API › Document › ononline
Additionally, the events bubble up from document.body, to document, ending at window. Both events are non-cancellable (you can't prevent the user from coming online, or going offline). window.navigator.onLine returns boolean true if the browser is online and false if it is definitely offline (disconnected from the network). The online and offline events are fired when the value of this 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. ...
...efinitely offline (disconnected from the network). The online and offline events are fired when the value of this 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 event...
Document: pointercancel event - Web APIs
put accidentally. This can happen if, for example, the hardware supports palm rejection to prevent a hand resting on the display while using a stylus from accidentally triggering events. The touch-action CSS property prevents the input from continuing. ...
...m accidentally triggering events. The touch-action CSS property prevents the input from continuing. After the pointercancel event is fired, the browser will also send pointerout followed by pointerleave. ...
Document: pointerdown event - Web APIs
itions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer. ...
...en, it is fired when the stylus makes physical contact with the digitizer. ...
Document: pointerenter event - Web APIs
event fires when a pointing device is moved into the hit test boundaries of an element or one of its descendants, including as a result of a pointerdown event from a device that does not support hover (see pointerdown). ...
...n event from a device that does not support hover (see pointerdown). ...
Document: pointerleave event - Web APIs
The pointerleave event is fired when a pointing device is moved out of the hit test boundaries of an element. For pen devices, this event is fired when the stylus leaves the hover range detectable by the digitizer. ...
...red when the stylus leaves the hover range detectable by the digitizer. ...
Document: pointerlockchange event - Web APIs
The pointerlockchange event is fired when the pointer is locked/unlocked. ...
...lockchange event is fired when the pointer is locked/unlocked. ...
Document: pointermove event - Web APIs
The pointermove event is fired when a pointer changes coordinates, and the pointer has not been canceled by a browser touch-action. ...
...s coordinates, and the pointer has not been canceled by a browser touch-action. ...
Document: pointerout event - Web APIs
lement; firing the pointerup event for a device that does not support hover (see pointerup); after firing the pointercancel event (see pointercancel); when a pen stylus leaves the hover range detectable by the digitizer. ...
...cancel); when a pen stylus leaves the hover range detectable by the digitizer. ...
Document: pointerover event - Web APIs
The pointerover event is fired when a pointing device is moved into an element's hit test boundaries. ...
...fired when a pointing device is moved into an element's hit test boundaries. ...
Document: pointerup event - Web APIs
The pointerup event is fired when a pointer is no longer active. ...
... The pointerup event is fired when a pointer is no longer active. ...
Document.popupNode - Web APIs
This will be the target of the mouse event that activated the popup. If the popup was opened via the keyboard, the popup node may be set to null. Typically, this property will be checked during a popupshowing event handler for a context menu to initialize the menu based on the context. ...
...pshowing event handler for a context menu to initialize the menu based on the context. This property is only set for popups attached via the popup or context attributes. For other types of popups, the value is not changed. In these other cases, for example when calling the popup's showPopup method, you may wish to set the popupNode property directly beforehand. This property applies only to XUL documents. Syntax var node = document.popupNode; Example <menupopup id="toolbarContextMenu"> ... <menuitem oncommand="mailNewsCore.deleteButton(document.popupNode)"> ... </menupopup> ...
Document.queryCommandState() - Web APIs
The queryCommandState() method will tell you if the current selection has a certain 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. Example HTML <div contenteditable="true">Select a part of this text!</div> <button onclick="makeBold();">Test the state of the 'bold' command</button> JavaScript function makeBold() { var state = document.queryCommandState("bold"); switch (state) { case true: alert("The bold formatting will be removed from the selected text."); break; case false: alert("The selected text will be displayed in bold."); break; case null: alert(...
... JavaScript function makeBold() { var state = document.queryCommandState("bold"); switch (state) { case true: alert("The bold formatting will be removed from the selected text."); break; case false: alert("The selected text will be displayed in bold."); break; case null: alert("The state of the 'bold' command is indeterminable."); break; } document.execCommand('bold'); } Result Specifications Specification Status Comment execCommand ...
Document.queryCommandSupported() - Web APIs
Syntax isSupported = document.queryCommandSupported(command); Parameters command The command for which to determine support. Return value Returns a Boolean which is true if the command is supported and false if the command isn't. ...
...eryCommandSupported(command); Parameters command The command for which to determine support. ...
Document.referrer - Web APIs
Web › API › Document › referrer
Specifications Specification Status Comment HTML Living StandardThe definition of 'document.referrer' in that specification. ...
... The Document.referrer property returns the URI of the page that linked to this page. Syntax var referrer = document.referrer; Value The value is an empty string if the user navigated to the page directly (not through a link, but, for example, by using a bookmark). Because this property returns only a string, it doesn't give you document object model (DOM) access to the referring page. Inside an <iframe>, the Document.referrer will initially be set to the same value as the href of the parent window's Window.location. Specifications Specification Status Comment HTML Living StandardThe definition of 'document.referrer' in that specification. Living Standard ...
Document: transitionrun event - Web APIs
The transitionrun event is fired when a CSS transition is first created, i.e. before any transition-delay has begun. Bubbles Yes Cancelable No Interface TransitionEvent Event handler property ontransitionrun The original target for this event is the Element that had the transition applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: transitionrun. Examples This code adds a listener to the transitionrun event: document.addEventListener('transitionrun', () => { console.log('Transition is running but hasn't necessarily started transitioning yet'); }); The same, but using the ontransitionrun property inst...
...pture or bubbling phases. For full details on this event please see the page on HTMLElement: transitionrun. Examples This code adds a listener to the transitionrun event: document.addEventListener('transitionrun', () => { console.log('Transition is running but hasn't necessarily started transitioning yet'); }); The same, but using the ontransitionrun property instead of addEventListener(): document.ontransitionrun = () => { console.log('Transition started running'); }; See a live example of this event. Specifications Specification Status Comment CSS TransitionsThe definition of 'transitionrun' in that specification. Working Draft Initial definition. ...
Document.vlinkColor - Web APIs
The recommended alternative is to get/set the color of the CSS :visited pseudo-class on HTML <a> elements (e.g., a:visited {color:red;}). ...
... The Document.vlinkColor property gets/sets the color of links that the user has visited in the document. Syntax color = document.vlinkColor document.vlinkColor = color Parameters color is a string representing the color as a word (e.g., "red") or hexadecimal value (e.g., "#ff0000"). Notes The default value for this property in Mozilla Firefox is purple (#551a8b in hexadecimal). Document.vlinkColor is deprecated in DOM Level 2 HTML. The recommended alternative is to get/set the color of the CSS :visited pseudo-class on HTML <a> elements (e.g., a:visited {color:red;}). Another alternative is document.body.vLink, although this is deprecated in HTML 4.01 in favor of the CSS alternative. ...
Document.writeln() - Web APIs
Web › API › Document › writeln
Writes a string of text followed by a newline character to a document. Syntax document.writeln(line); Parameters line is string containing a line of text. Example document.writeln("<p>enter password:</p>"); Notes document.writeln is the same as document.write but adds a newline. Note: document.writeln (like document.write) does not work in XHTML documents (you'll get a "Operation is not supported" (NS_ERROR_DOM_NOT_SUPPORTED_ERR) error on the error console). This is the case if opening a local file with a .xhtml file extension or for any document served with an application/xhtml+xml MIME type. More information is available in the W3C XHTML FAQ. ...
...get a "Operation is not supported" (NS_ERROR_DOM_NOT_SUPPORTED_ERR) error on the error console). This is the case if opening a local file with a .xhtml file extension or for any document served with an application/xhtml+xml MIME type. More information is available in the W3C XHTML FAQ. Specifications Specification Status Comment HTML Living StandardThe definition of 'document.writeln()' in that specification. Living Standard Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'document.writeln()' in that specification. Obsolete ...
DocumentFragment.querySelectorAll() - Web APIs
The DocumentFragment.querySelectorAll() method returns a NodeList of elements within the DocumentFragment (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors. If the selectors specified in parameter are invalid a DOMException with a SYNTAX_ERR value is raised. Note: The definition of this API was moved to the ParentNode interface. Syntax elementList = documentfragment.querySelectorAll(selectors); Parameters selectors Is a DOMString containing one or more CSS selectors separated by commas. ...
... specified in parameter are invalid a DOMException with a SYNTAX_ERR value is raised. Note: The definition of this API was moved to the ParentNode interface. Syntax elementList = documentfragment.querySelectorAll(selectors); Parameters selectors Is a DOMString containing one or more CSS selectors separated by commas. Examples This example returns a list of all div elements within the DocumentFragment with a class of either "note" or "alert": var matches = documentfrag.querySelectorAll("div.note, div.alert"); Specifications Specification Status Comment Selectors API Level 1The definition of 'DocumentFragment.querySelectorAll' in that specification. Obsolete Initial definition. ...
DocumentOrShadowRoot.nodeFromPoint() - Web APIs
Currently this method 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. ...
...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.pointerLockElement - Web APIs
The pointerLockElement property of the Document and ShadowRoot interfaces provides the element set as the target for mouse events while the pointer is locked. It is null if lock is pending, pointer is unlocked, or the target is in another document. Syntax var element = document.pointerLockElement; Return value An Element or null. Specifications Specification Status Comment Pointer LockThe definition of 'pointerLockElement' in that specification. ...
...ts while the pointer is locked. It is null if lock is pending, pointer is unlocked, or the target is in another document. Syntax var element = document.pointerLockElement; Return value An Element or null. Specifications Specification Status Comment Pointer LockThe definition of 'pointerLockElement' in that specification. Candidate Recommendation Extend the Document interface ...
Selection.deleteFromDocument() - Web APIs
The deleteFromDocument() method of the Selection interface deletes the selected text from the document's DOM. Syntax sel.deleteFromDocument() Parameters 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. ...
...ample 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 Current ...
<html>: The HTML Document / Root element - HTML: Hypertext Markup Language
Web › HTML › Element › html
The HTML <html> element represents the root (top-level element) of an HTML document, so it is also referred to as the root element. All other elements must be descendants of this element. Content categories None. Permitted content One <head> element, followed by one <body> element. Tag omission The start tag may be omitted if the first thing inside the <html> element is not a comment. The end tag may be omitted if the <html> element is not immediately followed by a comment. Permitted parents None. This is the root element of a document. Implicit ARIA role No corresponding role Permitted ARIA roles No role permitted DOM interface HTMLHtmlElement Attributes This element includes the global attributes. ...
...Implicit ARIA role No corresponding role Permitted ARIA roles No role permitted DOM interface HTMLHtmlElement Attributes This element includes the global attributes. manifest Specifies the URI of a resource manifest indicating resources that should be cached locally. See Using the application cache for details. version Specifies the version of the HTML Document Type Definition that governs the current document. This attribute is not needed, because it is redundant with the version information in the document type declaration. xmlns Specifies the XML Namespace of the document. Default value is "http://www.w3.org/1999/xhtml". This is required in documents parsed with XML parsers, and optional in text/html documents. Example <!DOCTYPE html> <html lang...
MathML documentation index - MathML
Web › MathML › Index
rence, Web, XML Mathematical Markup Language (MathML) is a dialect of XML for describing mathematical notation and capturing both its structure and content. 2 Authoring MathML Beginner, MathML, MathML Project This page explains how to write mathematics using the MathML language. Just like HTML, MathML is described with tags and attributes. HTML becomes verbose when your document contains advanced structures like lists or tables but fortunately there are many generators from simple notations, WYSIWYG editors and other Content Management Systems to help writing Web pages. 3 Examples Beginner, Example, Guide, MathML, NeedsBeginnerUpdate Below you'll find some examples you can look at to help you to understand how to use MathML to display increasingly co...
...L Reference This is an alphabetical list of MathML attributes. More details for each attribute are available on particular element pages. 7 Values Guide, MathML, MathML Reference Several MathML presentation elements have attributes that accept length values used for size or spacing. MathML accepts different units and constants for specifying lengths. 8 MathML documentation index Index, MathML Found 40 pages: 9 MathML element reference MathML, MathML Reference This is an alphabetical list of MathML presentation elements. 10 <maction> MathML, MathML Reference, MathML:Element, MathML:Enlivening Expressions The following example uses the "toggle" actiontype: 11 <math> MathML, MathML Reference, Math...
Safe Browsing: Design Documentation - Archive of obsolete content
This documentation now lives on the main Mozilla Wiki, see https://wiki.mozilla.org/Phishing_Protection:_Design_Documentation. ...
documentCharsetInfo - Archive of obsolete content
<< XUL Reference documentCharsetInfo Obsolete since Gecko 12.0 Type: nsIDocumentCharsetInfo This read-only property contains the nsIDocumentCharsetInfo object for the document which is used to handle which character set should be used to display the document. The properties of the nsIDocumentCharsetInfo object were merged into the docshell in Gecko 12.0 (Firefox 12.0 / Thunderbird 12.0 / SeaMonkey 2.9). ...
DOM (Document Object Model) - MDN Web Docs Glossary: Definitions of Web-related terms
The DOM is a document model loaded in the browser and representing the document as a node tree, where each node represents part of the document (e.g. an element, text string, or comment). The DOM is one of the most-used APIs on the Web because it allows code running in a browser to access and interact with every node in the document. Nodes can be created, moved and changed. Event listeners can be added to nodes and triggered on occurrence of a given event. DOM was not originally specified--it came about when browsers began implementing JavaScript. This legacy DOM is sometimes called DOM 0. Today, the WHATWG maintains the DOM Living Standard. ...
Web APIs: Mozilla-specific documents
In the pages listed here, we provide Mozilla-specific documents about standard Web APIs. This includes notes about any Firefox-only features, or about any experiments or other deviations from the specification that may exist in Mozilla code. ...
Document.URL - Web APIs
Web › API › Document › URL
The URL read-only property of the Document interface returns the document location as a string. Syntax const url = document.URL Example JavaScript document.getElementById("url").textContent = document.URL; HTML <p id="urlText"> URL:<br/> <span id="url">URL goes here</span> </p> Result Specifications Specification Status Comment DOMThe definition of 'Document.URL' in that specification. Living Standard Defines that the property is a USVString instead of a DOMString. ...
Document.all - Web APIs
Web › API › Document › all
In other words, it returns all of the document's elements, accessible by order (like an array) and by ID (like a regular object). Syntax var htmlAllCollection = document.all; Value An HTMLAllCollection which contains every element in the document. Conversion to boolean document.all is the only falsy object accessible to JavaScript, because it has the [[IsHTMLDDA]] internal slot. This was done because of compatibility with older versions of Internet Explorer. More information about this can be found in this answer from StackOverflow. Specifications Specification Status Comment HTML Living StandardThe definition of 'all' in that specification. ...
Document: animationcancel event - Web APIs
moved, or when the animating node is hidden using CSS. Therefore, either directly or because any of its containing nodes are hidden. Bubbles Yes Cancelable No Interface AnimationEvent Event handler property onanimationcancel The original target for this event is the Element that had the animation applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationcancel. Examples This code adds a listener to the animationcancel event. document.addEventListener('animationcancel', () => { console.log('Animation canceled'); }); The same, but using the onanimationcancel property instead of addEventListener(): document.on...
Document: animationend event - Web APIs
tion, such as if the element is removed from the DOM or the animation is removed from the element, the animationend event is not fired. Bubbles Yes Cancelable No Interface AnimationEvent Event handler property onanimationend The original target for this event is the Element that had the animation applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationend. Examples This example listens for the animationend event: document.addEventListener('animationend', () => { console.log('Animation ended'); }); The same, but using the onanimationend event handler property: document.onanimationend = () => { console.lo...
Document: animationstart event - Web APIs
ual to the absolute value of the delay (and, correspondingly, the animation will begin playing at that time index into the sequence). Bubbles Yes Cancelable No Interface AnimationEvent Event handler property onanimationstart The original target for this event is the Element that had the animation applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationstart. Examples This listens for the animationstart event and logs a message when it is fired: document.addEventListener('animationstart', () => { console.log('Animation started'); }); The same, but using onanimationstart: document.onanimationstart = () => ...
Document.applets - Web APIs
Web › API › Document › applets
The applets property of the Document interface returns a list of the applets within a document. Note: The <applet> element was removed in Gecko 56 and Chrome in late 2015. Since then, calling document.applets in those browsers always returns an empty HTMLCollection. Removal is being considered in WebKit and Edge. Syntax var nodeList = document.applets; Value An HTMLCollection. Example // When you know the second applet is the one you want my_java_app = document.applets[1]; Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.applets' in that specification. Living Standard Obsoleted. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'Document.applets' in that specification. Obs...
Document.bgColor - Web APIs
Web › API › Document › bgColor
The deprecated bgColor property gets or sets the background color of the current document. Syntax color = document.bgColor document.bgColor =color Parameters color is a string representing the color as a word (e.g., "red") or hexadecimal value (e.g., "#ff0000"). Example document.bgColor = "darkblue"; Notes The default value for this property in Firefox is white (#ffffff in hexadecimal). document.bgColor is deprecated in DOM Level 2 HTML. The recommended alternative is use of the CSS style background-color which can be accessed through the DOM with document.body.style.backgroundColor. Another alternative is document.body.bgColor, although this is also deprecated in HTML 4.01 in favor of the CSS alternative. ...
Document.close() - Web APIs
Web › API › Document › close
The Document.close() method finishes writing to a document, opened with Document.open(). Syntax document.close(); Example // Open a document to write to it document.open(); // Write the content of the document document.write("<p>The one and only content.</p>"); // Close the document document.close(); Specifications Specification Status Comment HTML Living StandardThe definition of 'document.close()' in that specification. Living Standard Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'document.close()' in that specification. Obsolete ...
Document.compatMode - Web APIs
Syntax const mode = document.compatMode Value An enumerated value that can be: "BackCompat" if the document is in quirks mode. "CSS1Compat" if the document is in no-quirks (also known as "standards") mode or limited-quirks (also known as "almost standards") mode. Note: All these modes are now standardized, so the older "standards" and "almost standards" names are nonsensical and no longer used in standards. Example if (document.compatMode == "BackCompat") { // in Quirks mode } Specifications Specification Status Comment DOMThe definition of 'compatMode' in that specification. ...
Document.contentType - Web APIs
The Document.contentType read-only property returns the MIME type that the document is being rendered as. This may come from HTTP headers or other sources of MIME information, and might be affected by automatic type conversions performed by either the browser or extensions. Note: This property is unaffected by <meta> elements. Syntax contentType = document.contentType; Value contentType is a read-only property. Specifications Specification Status Comment DOMThe definition of 'Document.contentType' in that specification. Living Standard Initial definition ...
Document: copy event - Web APIs
The copy event fires when the user initiates a copy action through the browser's user interface. Bubbles Yes Cancelable Yes Interface ClipboardEvent Event handler property oncopy The original target for this event is the Element that was the intended target of the copy action. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Element: copy event. Examples document.addEventListener('copy', (event) => { console.log('copy action initiated') }); Specifications Specification Status Clipboard API and events Working Draft ...
Document.createComment() - Web APIs
createComment() creates a new comment node, and returns it. Syntax CommentNode = document.createComment(data); Parameters data A string containing the data to be added to the Comment. Example var docu = new DOMParser().parseFromString('<xml></xml>', 'application/xml'); var comment = docu.createComment('This is a not-so-secret comment in your document'); docu.getElementsByTagName('xml')[0].appendChild(comment); alert(new XMLSerializer().serializeToString(docu)); // Displays: <xml><!--This is a not-so-secret comment in your document--></xml> Specifications Specification Status Comment DOMThe definition of 'document.createComment' in that specification. Living Standard ...
Document.createExpression() - Web APIs
This method compiles an XPathExpression which can then be used for (repeated) evaluations. Syntax xpathExpr = document.createExpression(xpathText, namespaceURLMapper); Parameters xpathText is a string which is the XPath expression to be compiled. namespaceURLMapper is a function which maps a namespace prefix to a namespace URL (or null if none needed). Firefox 3 note Prior to Firefox 3, you could call this method on documents other than the one you planned to run the XPath against. Under Firefox 3, you must call it on the same document. Return value XPathExpression ...
Document: cut event - Web APIs
The cut event is fired when the user has initiated a "cut" action through the browser's user interface. Bubbles Yes Cancelable Yes Interface ClipboardEvent Event handler property oncut The original target for this event is the Element that was the intended target of the cut action. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Element: cut event. Examples document.addEventListener('cut', (event) => { console.log('cut action initiated') }); Specifications Specification Status Clipboard API and events Working Draft ...
Document.dir - Web APIs
Web › API › Document › dir
The Document.dir property is a DOMString representing the directionality of the text of the document, whether left to right (default) or right to left. Possible values are 'rtl', right to left, and 'ltr', left to right. Syntax dirStr = document.dir document.dir = dirStr Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.dir' in that specification. Living Standard Initial specification ...
Document.domConfig - Web APIs
Specification http://www.w3.org/TR/DOM-Level-3-Cor...ent3-domConfig ...
Document.embeds - Web APIs
Web › API › Document › embeds
The embeds read-only property of the Document interface returns a list of the embedded <object> elements within the current document. Syntax nodeList = document.embeds Value An HTMLCollection. Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.embeds' in that specification. Living Standard ...
Document.exitPointerLock() - Web APIs
The exitPointerLock() method asynchronously releases a pointer lock previously requested through Element.requestPointerLock. To track the success or failure of the request, it is necessary to listen for the pointerlockchange and pointerlockerror events. Syntax document.exitPointerLock(); Specifications Specification Status Comment Pointer LockThe definition of 'Document' in that specification. Candidate Recommendation Extend the Document interface ...
Document.fgColor - Web APIs
Web › API › Document › fgColor
fgColor gets/sets the foreground color, or text color, of the current document. Syntax var color = document.fgColor; document.fgColor = color; Parameters color is a string representing the color as a word (e.g., "red") or hexadecimal value (e.g., "#ff0000"). Example document.fgColor = "white"; document.bgColor = "darkblue"; Notes The default value for this property in Mozilla Firefox is black (#000000 in hexadecimal). document.fgColor is deprecated in DOM Level 2 HTML. The recommended alternative is the CSS property color (e.g., document.body.style.color = "red"). Another alternative is document.body.text, although this is deprecated in HTML 4.01 in favor of the CSS alternative above. ...
Document.fonts - Web APIs
Web › API › Document › fonts
Syntax let fontFaceSet = document.fonts; Value The returned value is the FontFaceSet interface of the document. The FontFaceSet interface is useful for loading new fonts, checking the status of previously loaded fonts etc. Examples Doing operation after all fonts are loaded document.fonts.ready.then(function() { // Any operation that needs to be done only after all the fonts // have finished loading can go here. }); Specifications Specification Status Comment CSS Font Loading Module Level 3The definition of 'FontFaceSet' in that specification. ...
Document: fullscreenerror event - Web APIs
The fullscreenerror event is fired when the browser cannot switch to full-screen mode. Bubbles Yes Cancelable No Interface Event Event handler property onfullscreenerror As with the fullscreenchange event, two fullscreenerror events are fired; the first is sent to the Element which failed to change modes, and the second is sent to the Document which owns that element. For some reasons that switching into full-screen mode might fail, see the guide to the Fullscreen API. Examples const requestor = document.querySelector('div'); document.addEventListener('fullscreenerror', (event) => { console.error('an error occurred changing into fullscreen'); console.log(event); }); requestor.requestFullscreen(); Specifications Specificat...
Document.hidden - Web APIs
Web › API › Document › hidden
The Document.hidden read-only property returns a Boolean value indicating if the page is considered hidden or not. Syntax var boolean = document.hidden Examples document.addEventListener("visibilitychange", function() { console.log( document.hidden ); // Modify behavior... }); Specifications Specification Status Comment Page Visibility (Second Edition)The definition of 'Document.hidden' in that specification. Recommendation Initial definition ...
Document: keydown event - Web APIs
as been processed by an IME): eventTarget.addEventListener("keydown", event => { if (event.isComposing || event.keyCode === 229) { return; } // do something }); Examples addEventListener keydown example This example logs the KeyboardEvent.code value whenever you press down a key. <p>Focus the IFrame first (e.g. by clicking in it), then try pressing some keys.</p> <p id="log"></p> document.addEventListener('keydown', logKey); function logKey(e) { log.textContent += ` ${e.code}`; } onkeydown equivalent document.onkeydown = logKey; Specifications Specification Status UI Events Working Draft ...
Document.linkColor - Web APIs
The Document.linkColor property gets/sets the color of links within the document. This property is deprecated. As an alternative, you can set the CSS color property on either HTML anchor links (<a>) or on :link pseudo-classes. Another alternative is document.body.link, although this is deprecated in HTML 4.01. Syntax color = document.linkColor document.linkColor = color Parameters color is a string representing the color as a word (e.g., red) or hexadecimal value (e.g., #ff0000). Example document.linkColor = 'blue'; Specification HTML5 Document.linkColor is deprecated in DOM Level 2 HTML. ...
Document.links - Web APIs
Web › API › Document › links
The links read-only property of the Document interface returns a collection of all <area> elements and <a> elements in a document with a value for the href attribute. Syntax nodeList = document.links Value An HTMLCollection. Example var links = document.links; for(var i = 0; i < links.length; i++) { var linkHref = document.createTextNode(links[i].href); var lineBreak = document.createElement("br"); document.body.appendChild(linkHref); document.body.appendChild(lineBreak); } Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.links' in that specification. Living Standard Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'document.links' in that specification. Obsolete Init...
Document.onoffline - Web APIs
The Document.onoffline event handler is called when an offline is fired on the <body> element and bubbles up, when navigator.onLine property changes and becomes false. ...
Document.onvisibilitychange - Web APIs
Syntax obj.onvisibilitychange = function; function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration. Example document.onvisibilitychange = function() { console.log("Visibility of page has changed!"); }; Specifications Specification Status Comment Page Visibility (Second Edition)The definition of 'onvisibilitychange' in that specification. Recommendation Initial definition. ...
Document: paste event - Web APIs
The paste event is fired when the user has initiated a "paste" action through the browser's user interface. Bubbles Yes Cancelable Yes Interface ClipboardEvent Event handler property onpaste The original target for this event is the Element that was the intended target of the paste action. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Element: paste event. Examples document.addEventListener('paste', (event) => { console.log('paste action initiated') }); Specifications Specification Status Clipboard API and events Working Draft ...
Document.plugins - Web APIs
Web › API › Document › plugins
The plugins read-only property of the Document interface returns an HTMLCollection object containing one or more HTMLEmbedElements representing the <embed> elements in the current document. For a list of installed plugins, use NavigatorPlugins.plugins instead. Syntax embedArrayObj = document.plugins Value An HTMLCollection, or null if there are no embeds in the document. Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.plugins' in that specification. Living Standard ...
Document.releaseCapture() - Web APIs
The releaseCapture() method releases mouse capture if it's currently enabled on an element within this document. Enabling mouse capture on an element is done by calling element.setCapture(). Syntax document.releaseCapture(); Once mouse capture is released, mouse events will no longer all be directed to the element on which capture is enabled. Example See the example for element.setCapture(). Specifications Based on Internet Explorer's implementation. ...
Document.rootElement - Web APIs
Document.rootElement returns the Element that is the root element of the document if it is an <svg> element, otherwise null. It is deprecated in favor of Document.documentElement, which returns the root element for all documents. Syntax const element = document.rootElement Notes If the document is a non-empty SVG document, then the rootElement will be an SVGSVGElement, identical to the documentElement. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGDocument.rootElement' in that specification. Candidate Recommendation Deprecated Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'SVGDocument.rootElement' in that specification. Recommendation Initial definition ...
Document.scripts - Web APIs
Web › API › Document › scripts
The scripts property of the Document interface returns a list of the <script> elements in the document. The returned object is an HTMLCollection. Syntax var scriptList = document.scripts; Value An HTMLCollection. You can use this just like an array to get all the elements in the list. Example This example looks to see if the page has any <script> elements. let scripts = document.scripts; if (scripts.length) { alert('This page has scripts!'); } Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.scripts' in that specification. Living Standard ...
Document: scroll event - Web APIs
Bubbles Yes Cancelable No Interface Event Event handler property onscroll Note: In iOS UIWebViews, scroll events are not fired while scrolling is taking place; they are only fired after the scrolling has completed. See Bootstrap issue #16202. Safari and WKWebViews are not affected by this bug. Examples Scroll event throttling Since scroll events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as DOM modifications. Instead, it is recommended to throttle the event using requestAnimationFrame(), setTimeout(), or a CustomEvent, as follows. ...
Document.scrollingElement - Web APIs
In standards mode, this is the root element of the document, document.documentElement. When in quirks mode, the scrollingElement attribute returns the HTML body element if it exists and is not potentially scrollable, otherwise it returns null. Syntax var element = document.scrollingElement; Example var scrollElm = document.scrollingElement; scrollElm.scrollTop = 0; Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'scrollingElement' in that specification. ...
Document: selectionchange event - Web APIs
The selectionchange event of the Selection API is fired when the current text selection on a document is changed. Bubbles No Cancelable No Interface Event Event handler property onselectionchange Examples // addEventListener version document.addEventListener('selectionchange', () => { console.log(document.getSelection()); }); // onselectionchange version document.onselectionchange = () => { console.log(document.getSelection()); }; Specifications Specification Status Comment Selection APIThe definition of 'selectionchange' in that specification. Working Draft Initial definition. ...
Document: selectstart event - Web APIs
The selectstart event of the Selection API is fired when a user starts a new selection. If the event is canceled, the selection is not changed. Bubbles Yes Cancelable Yes Interface Event Event handler property onselectstart Examples // addEventListener version document.addEventListener('selectstart', () => { console.log('Selection started'); }); // onselectstart version document.onselectstart = () => { console.log('Selection changed.'); }; Specifications Specification Status Comment Selection APIThe definition of 'selectstart' in that specification. Working Draft Initial definition. ...
Document.tooltipNode - Web APIs
The Document.tooltipNode property returns the node which is the target of the current <xul:tooltip>. Syntax document.tooltipNode; Specification XUL-specific method. Not part of any specification. Defined in nsIDOMXULDocument.idl. ...
Document: transitioncancel event - Web APIs
is fired when a CSS transition is canceled. See GlobalEventHandlers.ontransitioncancel for more information. Bubbles Yes Cancelable No Interface TransitionEvent Event handler property GlobalEventHandlers.ontransitioncancel The original target for this event is the Element that had the transition applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: transitioncancel. Examples This code adds a listener to the transitioncancel event: document.addEventListener('transitioncancel', () => { console.log('Transition canceled'); }); The same, but using the ontransitioncancel property instead of addEventListener(): docume...
Document: transitionend event - Web APIs
erts to the default or non-transitioned state. If there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. If the transitioncancel event is fired, the transitionend event will not fire. The original target for this event is the Element that had the transition applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: transitionend. Examples This code adds a listener to the transitionend event: document.addEventListener('transitionend', () => { console.log('Transition ended'); }); The same, but using the ontransitionend property instead of addEventListener(): document.ontransition...
Document: transitionstart event - Web APIs
rt of any delay) and transitionstart fires when the actual animation has begun (i.e. at the end of any delay). Bubbles Yes Cancelable No Interface TransitionEvent Event handler property GlobalEventHandlers.ontransitionstart The original target for this event is the Element that had the transition applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: transitionstart. Examples This code adds a listener to the transitionstart event: document.addEventListener('transitionstart', () => { console.log('Started transitioning'); }); The same, but using the ontransitionstart property instead of addEventListener(): document...
Document.xmlEncoding - Web APIs
UTF-16"?> ...the result should be "UTF-16". However, Firefox 3.0 includes information on endianness (e.g., UTF-16BE for big endian encoding), and while this extra information is removed as of Firefox 3.1b3, Firefox 3.1b3 is still consulting the file's encoding, rather than the XML Declaration as the spec defines it ("An attribute specifying, as part of the XML declaration, the encoding of this document."). Specification http://www.w3.org/TR/DOM-Level-3-Cor...ment3-encoding This has been removed from DOM Core Level 4WD ...
DocumentFragment() - Web APIs
The DocumentFragment() constructor returns a new, empty DocumentFragment object . Syntax fragment = new DocumentFragment() Example let fragment = new DocumentFragment(); Specification Specification Status Comment DOMThe definition of 'DocumentFragment()' in that specification. Living Standard Initial definition. ...
DocumentOrShadowRoot.msElementsFromRect() - Web APIs
) Parameters left [in] Type: Floating-point top[in] Type: Floating-point width[in] Type: Floating-point height [in] Type: Floating-point retVal [out, reval] Type: NodeList Example To find all of the elements under a given point, use msElementsFromPoint(x, y). To find all of the elements which intersect a rectangle, use msElementsFromRect(top, left, width, height). var nodeList = document.msElementsFromRect(x,y,width,height) var nodeList = document.msElementsFromPoint(x,y) The returned nodeList is sorted by z-index so that you can tell the relative stacking order of the elements. See also Advanced Hit Testing APIs Demo for msElementsFromPoint() and msElementsFromRect() Microsoft API extensions ...
DocumentOrShadowRoot.styleSheets - Web APIs
The styleSheets read-only property of the DocumentOrShadowRoot interface returns a StyleSheetList of CSSStyleSheet objects, for stylesheets explicitly linked into or embedded in a document. Examples function getStyleSheet(unique_title) { for (var i=0; i<document.styleSheets.length; i++) { var sheet = document.styleSheets[i]; if (sheet.title == unique_title) { return sheet; } } } Notes The returned list is ordered as follows: StyleSheets retrieved from <link> headers are placed first, sorted in header order. StyleSheets retrieved from the DOM are placed after, sorted in tree order. Specifications Specification Status Comment Shadow DOMThe definition of 'DocumentOrShadowRoot' in that specification. Obsolete Initial definition...
DocumentTouch - Web APIs
The DocumentTouch interface used to provide convenience methods for creating Touch and TouchList objects, but DocumentTouch been removed from the standards. These two methods now live on the Document interface. Methods DocumentTouch.createTouch() Creates a new Touch object. DocumentTouch.createTouchList() Creates a new TouchList object. ...
contentDocument - Web APIs
If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null. Example of contentDocument var iframeDocument = document.getElementsByTagName("iframe")[0].contentDocument; iframeDocument.body.style.backgroundColor = "blue"; // This would turn the iframe blue. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLIFrameElement: contentDocument' in that specification. Living Standard ...
HTMLObjectElement.contentDocument - Web APIs
The contentDocument read-only property of the HTMLObjectElement interface Returns a Document representing the active document of the object element's nested browsing context, if any; otherwise null. Syntax var document = HTMLObjectElement.contentDocument; Value A Document. Specifications Specification Status Comment HTML Living StandardThe definition of 'contentDocument' in that specification. Living Standard Initial definition. ...
Node.ownerDocument - Web APIs
The ownerDocument read-only property of the Node interface returns the top-level document object of the node. Syntax var document = element.ownerDocument; Value document is the top-level Document object in which all the child nodes are created. If this property is used on a node that is itself a document, the value is null. Example // Given a node "p", get the top-level HTML // child of the document object var d = p.ownerDocument; var html = d.documentElement; Specifications Specification Status Comment DOMThe definition of 'Node: ownerDocument' in that specification. Living Standard ...
SecurityPolicyViolationEvent.documentURI - Web APIs
The documentURI read-only property of the SecurityPolicyViolationEvent interface is a USVString representing the URI of the document or worker in which the violation was found. Syntax let documentURI = violationEventInstance.documentURI; Value A USVString representing the URI of the document or worker in which the violation was found. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.documentURI); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'documentURI' in that specification. Working Draft Initial definition ...
Window.document - Web APIs
Web › API › Window › document
window.document returns a reference to the document contained in the window. Example console.log(window.document.title); Specifications Specification Status Comment HTML Living StandardThe definition of 'Window.document' in that specification. Living Standard HTML5The definition of 'Window.document' in that specification. Recommendation ...
XMLDocument.load() - Web APIs
Web › API › XMLDocument › load
document.load() is a part of an old version of the W3C DOM Level 3 Load & Save module. Can be used with document.async to indicate whether the request is synchronous or asynchronous (the default). As of at least Gecko 1.9, this no longer supports cross-site loading of documents (Use XMLHttpRequest or fetch() instead). Examples var xmlDoc = document.implementation.createDocument("", "test", null); function documentLoaded (e) { alert(new XMLSerializer().serializeToString(e.target)); // Gives querydata.xml contents as string } xmlDoc.addEventListener("load", documentLoaded, false); xmlDoc.load('querydata.xml'); See also the load sample in the XML tests directory. (To test this functionality, create the files on your local disk or on a webserver rather than loading the load.html file from...
<title>: The Document Title element - HTML: Hypertext Markup Language
Web › HTML › Element › title
It only contains text; tags within the element are ignored. <title>Grandma's Heavy Metal Festival Journal</title> Content categories Metadata content. Permitted content Text that is not inter-element whitespace. Tag omission Both opening and closing tags are required. Note that leaving off </title> should cause the browser to ignore the rest of the page. Permitted parents A <head> element that contains no other <title> element. Implicit ARIA role No corresponding role Permitted ARIA roles No role permitted. ...
Index - Web APIs
Web › API › Index
ysical orientation in relation to the Earth's reference coordinate system. 16 AbstractRange API, Abstract, Abstract Interface, AbstractRange, DOM, DOM API, Interface, Range, Reference The AbstractRange abstract interface is the base class upon which all DOM range types are defined. A range is an object that indicates the start and end points of a section of content within the document. 17 AbstractRange.collapsed API, AbstractRange, DOM, DOM API, Empty, Property, Range, Reference, collapsed The collapsed read-only property of the AbstractRange interface returns true if the range's start position and end position are the same. 18 AbstractRange.endContainer API, AbstractRange, DOM, DOM API, End, Node, Position, Property, Range, Read-only, Refer...
...Animation.timeline API, Animation, Experimental, Property, Reference, Web Animations, timeline, web animations api The Animation.timeline property of the Animation interface returns or sets the timeline associated with this animation. A timeline is a source of time values for synchronization purposes, and is an AnimationTimeline-based object. By default, the animation's timeline and the Document's timeline are the same. 81 Animation.updatePlaybackRate() API, Animation, Experimental, Interface, Method, Reference, Web Animations, playbackRate, updatePlaybackRate, waapi, web animations api The updatePlaybackRate() method of the Web Animations API's Animation Interface sets the speed of an animation after first synchronizing its playback position. 82 Animation...
...ionstart" event, elapsedTime is 0.0 unless there was a negative value for animation-delay, in which case the event will be fired with elapsedTime containing (-1 * delay). 90 AnimationEvent.initAnimationEvent() API, AnimationEvent, CSSOM, Method, Obsolete, Web Animations The AnimationEvent.initAnimationEvent() method Initializes an animation event created using the deprecated Document.createEvent("AnimationEvent") method. 91 AnimationEvent.pseudoElement API, AnimationEvent, CSS, CSSOM, Experimental, Property, Reference, Web Animations The AnimationEvent.pseudoElement read-only property is a DOMString, starting with '::', containing the name of the pseudo-element the animation runs on. If the animation doesn't run on a pseudo-element but on the element, an ...
...And 373 more matches
Index - Archive of obsolete content
Cache control, Custom Error pages, HTACCESS, Permanent Redirect, Redirect File Accessing : htaccess files can be opened using any text editor, like Windows Notepad, Vin, Sublime text editor or any other. Syntax highliting support for .htaccess files less. 3 2015 MDN Fellowship Program 2015, Archive, fellowship No summary! 4 API API, Archive Archived documentation about obsolete web standards APIs. 5 Navigator API, Navigator Features that used to hang off the Navigator interface, but have since been removed. 6 Navigator.mozNotification API, Deprecated, Mobile, Non-standard, Property, Reference Provides support for creating notification objects, which are used to display desktop notification alerts to the user.
...ported on Firefox Mobile and Firefox OS. See Displaying notifications for an example. 7 Window: deviceproximity event Sensors, events The deviceproximity event is fired when fresh data is available from a proximity sensor. 8 Window: userproximity event Sensors, events No summary! 9 Add-ons Add-ons, Archive, Extensions Archived add-ons documentation. 10 Add-on SDK Add-on SDK, Jetpack No summary! 11 Builder No summary! 12 Guides Add-on SDK No summary! 13 Content Scripts Add-on SDK Many add-ons need to access and modify the content of web pages. But the main add-on code doesn't get direct access to web content. Instead, SDK add-ons need to factor the code...
...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! 26 Getting Started Add-on SDK Learn how to contribute to the Add-on SDK. 27 Modules Add-...
...And 125 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
e, which provides strong backwards HTML compatibility with Internet Explorer and other legacy browsers. I'll also cover nonstandard technologies, such as XMLHttpRequest and rich text editing, that Mozilla does support because no W3C equivalent existed at the time. ...
... no W3C equivalent existed at the time. ...
...ll cover some basic ways you can make a Web application extensible in order to add new browser support later. Since different browsers sometimes use different APIs for the same functionality, you can often find multiple if() else() blocks throughout the code to differentiate between the browsers. The following code shows blocks designated for Internet Explorer: . . . var elm; if (ns4) elm = document.layers["myID"]; else if (ie4) elm = document.all["myID"] The above code isn't extensible, so if you want it to support a new browser, you must update these blocks throughout the Web application. The easiest way to eliminate the need to recode for a new browser is to abstract out functionality. Rather than multiple if() else() blocks, you increase efficiency by taking common tasks and abstrac...
...And 52 more matches
JXON - Archive of obsolete content
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. In this article we will show how to convert a parsed XML document (i.e. an instance of Document) to a JavaScript Object tree (i.e. a tree of nested instances of Object) and viceversa, with some different algorithms. It could be useful to read the XML introduction article first. If you want a complete bidirectional JXON ...
...ree of nested instances of Object) and viceversa, with some different algorithms. It could be useful to read the XML introduction article first. If you want a complete bidirectional JXON library (modelled on the JSON global object), skip to the dedicated paragraph (but please read the note about the const statement compatibility). ...
...ntroduction article first. If you want a complete bidirectional JXON library (modelled on the JSON global object), skip to the dedicated paragraph (but please read the note about the const statement compatibility). Note: If you are interested to address only some parts of an XML document (and are not starting in JavaScript/JSON for templating purposes), use XPath instead of converting the whole document into JSON. ...
...And 48 more matches
Introduction to using XPath in JavaScript - XPath
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. 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. ...
... 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. var xpathResult = document.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result ); Parameters The evaluate function takes a total of five parameters: xpathExpression: A string containing the XPath expression to be evaluated. contextNode: A node in the document against which the xpathExpression should be evaluated, including any and all of its child nodes. ...
...low. var xpathResult = document.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result ); Parameters The evaluate function takes a total of five parameters: xpathExpression: A string containing the XPath expression to be evaluated. contextNode: A node in the document against which the xpathExpression should be evaluated, including any and all of its child nodes. The document node is the most commonly used. namespaceResolver: A function that will be passed any namespace prefixes contained within xpathExpression which returns a string representing the namespace URI associated with that prefix. This enables conversion between the prefixes used in the XPath expressions and the possibly different prefixes used in the document. The function can be either: Created by...
...And 45 more matches
jspage - Archive of obsolete content
c)){case"object":b={};for(var e in c){b[e]=$unlink(c[e]); }break;case"hash":b=new Hash(c);break;case"array":b=[];for(var d=0,a=c.length;d<a;d++){b[d]=$unlink(c[d]);}break;default:return c;}return b;}var Browser=$merge({Engine:{name:"unknown",version:0},Platform:{name:(window.orientation!=undefined)?"ipod":(navigator.platform.match(/mac|win|linux/i)||["other"])[0].toLowerCase()},Features:{xpath:!!(document.evaluate),air:!!(window.runtime),query:!!(document.querySelector)},Plugins:{},Engines:{presto:function(){return(!window.opera)?false:((arguments.callee.caller)?960:((document.getElementsByClassName)?950:925)); },trident:function(){return(!window.ActiveXObject)?false:((window.XMLHttpRequest)?((document.querySelectorAll)?6:5):4);},webkit:function(){return(navigator.taintEnabled)?false:((Browser.Fea...
...gines:{presto:function(){return(!window.opera)?false:((arguments.callee.caller)?960:((document.getElementsByClassName)?950:925)); },trident:function(){return(!window.ActiveXObject)?false:((window.XMLHttpRequest)?((document.querySelectorAll)?6:5):4);},webkit:function(){return(navigator.taintEnabled)?false:((Browser.Features.xpath)?((Browser.Features.query)?525:420):419); },gecko:function(){return(!document.getBoxObjectFor&&window.mozInnerScreenX==null)?false:((document.getElementsByClassName)?19:18);}}},Browser||{});Browser.Platform[Browser.Platform.name]=true; Browser.detect=function(){for(var b in this.Engines){var a=this.Engines[b]();if(a){this.Engine={name:b,version:a};this.Engine[b]=this.Engine[b+a]=true; break;}}return{name:b,version:a};};Browser.detect();Browser.Request=function(){return $tr...
....Plugins.Flash=(function(){var a=($try(function(){return navigator.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"...
...And 37 more matches
HTTP Index - HTTP
Web › HTTP › Index
It was designed for communication between web browsers and web servers, but it can also be used for other purposes. ...
...ve. 2 A typical HTTP session HTTP In client-server protocols, like HTTP, sessions consist of three phases: 3 An overview of HTTP HTML, HTTP, Overview, WebMechanics, l10n:priority HTTP isthe foundation of any data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually the Web browser. A complete document is reconstructed from the different sub-documents fetched, for instance text, layout description, images, videos, scripts, and more 4 Basics of HTTP Guide, HTTP, Overview HTTP is a pretty extensible protocol. It relies on a few basic concepts like the notion of resources and URIs, a simple structure of messages, and a client-server structure for the communication flow. On top...
...hods or headers. 5 Choosing between www and non-www URLs Guide, HTTP, URL A recurring question among website owners is whether to choose non-www or www URLs. This page provides some advice on what's best. 6 Data URLs Base64, Guide, HTTP, Intermediate, URL Data URLs, URLs prefixed with the data: scheme, allow content creators to embed small files inline in documents. 7 Evolution of HTTP Guide, HTTP, NeedsUpdate, NeedsUpdate(HTTP/3) HTTP (HyperText Transfer Protocol) is the underlying protocol of the World Wide Web. HTTP has evolved from an early protocol to exchange files in a semi-trusted laboratory environment, to the modern maze of the Internet, now carrying images, videos in high resolution and 3D. 8 Identifying resources...
...And 36 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
This glossary provides definitions of words and abbreviations you need to know to successfully understand and build for the web. ...
...to a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding. 28 Baseline CSS, Glossary, SVG, alignment, typography The baseline is a term used in European and West Asian typography meaning an imaginary line upon which the characters of a font rest. 29 BiDi Accessibility, Glossary BiDi (BiDirectional) refers to a document containing both right-to-left and left-to-right text. Even when both directionalities occur in the same paragraph, the text in each language must appear in its proper directionality. 30 BigInt BigInt, Glossary, JavaScript, Reference, arbitrary precision format In JavaScript, BigInt is a numeric data type that can represent integers in the arbitrary precision format. In other ...
...eral-purpose lossless compression algorithm. 42 Browser Glossary, Navigation A Web browser or browser is a program that retrieves and displays pages from the Web, and lets users access further pages through hyperlinks. A browser is the most familiar type of user agent. 43 Browsing context Glossary A browsing context is the environment a browser displays a Document. In modern browsers, it usually is a tab, but can be a window or even only parts of a page, like a frame or an iframe. 44 Bezier curve Bezier curve, Glossary, Graphics, Reference A Bezier curve (pronounced [bezje]) is a mathematically described curve used in computer graphics and animation. In vector images, they are used to model smooth curves that can be scaled indefinitely...
...And 30 more matches
Index
Mozilla › Tech › XPCOM › Index
This is a quick overview of the cycle collector introduced into XPCOM for Firefox 3, including a description of the steps involved in modifying an existing C++ class to participate in XPCOM cycle collection. If you have a class that you think is involved in a cyclical-ownership leak, this page is for you. 14 Introduction to XPCOM for the DOM Developing Mozilla Warning: this document has not yet been reviewed by the DOM gurus, it might contain some errors. 15 Language bindings Embedding, Landing, Mozilla, XPCOM, XPCOM:Language Bindings An XPCOM Language Binding is a bridge between a particular language and XPCOM to provide access to XPCOM objects from that language, and to let modules written in that language be used as XPCOM objects by all other language...
...omponents inside Mozilla, and it lets you talk about their interfaces as well. 60 Using components Deprecated, Guide, NeedsContent, XPCOM, XPCOM:Language Bindings, XPConnect XPConnect works transparently in Mozilla and xpcshell to give you access to XPCOM components. 61 XPConnect wrappers Guide, NeedsContent, XPCOM, XPCOM:Language Bindings, XPConnect This document is a high-level overview of XPConnect wrapper objects (for the more technical description see XPConnect security membranes). For practical advice on dealing with wrappers, see Safely accessing content DOM from chrome. 62 appShellService XPCOM:Language Bindings, XPConnect Quitting Mozilla: 63 nsIProfile Interfaces, XPCOM, XPCOM:Language Bindings, XPConnect ...
...Connect security membranes). For practical advice on dealing with wrappers, see Safely accessing content DOM from chrome. 62 appShellService XPCOM:Language Bindings, XPConnect Quitting Mozilla: 63 nsIProfile Interfaces, XPCOM, XPCOM:Language Bindings, XPConnect This interface is obsolete; you should use nsIToolkitProfileService instead; however, reference documentation for nsIProfile is available if you're working with old code. 64 nsIRegistry XPCOM:Language Bindings, XPConnect nsIRegistry on MXR 65 xpcshell Automated testing, Developing Mozilla, Guide, JavaScript, JavaScript:Tools, Tools, XPCOM, XPCOM:Language Bindings, XPConnect xpcshell is an XPConnect-enabled JavaScript Shell. It is a console application that l...
...And 30 more matches
page-mod - Archive of obsolete content
ts "content scripts". a pattern that a page's URL must match, in order for the script(s) to be attached to that page. ...
... If you supply the scripts as separate files in the "data" directory, you specify them using wit...
...iptFile: "./my-script.js" }); 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, debug and review. A page-mod only attaches scripts to documents loaded in tabs. It will not attach scripts to add-on panels, page-workers, sidebars, or Firefox hidden windows. To stop a page-mod from making any more modifications, call its destroy() method. The PageMod constructor takes a number of other options to control its behavior: contentStyle Lists stylesheets to attach, supplied as strings. contentStyleFile Lists stylesheet...
...And 29 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
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 */ function Color(color) { if(color instanceof Color === true) { this.copy(color); return; } this.r = 0; this...
... return this.getHexa(); return this.getRGBA(); }; /*=======================================================================*/ /*=======================================================================*/ /*========== Capture Mouse Movement ==========*/ var setMouseTracking = function setMouseTracking(elem, callback) { elem.addEventListener('mousedown', function(e) { callback(e); document.addEventListener('mousemove', callback); }); document.addEventListener('mouseup', function(e) { document.removeEventListener('mousemove', callback); }); }; /*====================*/ // Color Picker Class /*====================*/ function ColorPicker(node) { this.color = new Color(); this.node = node; this.subscribers = []; var type = this.node.getAttribute('data-mode'); ...
...('hexa', 'hexa', this.inputChangeHexa.bind(this)); this.setColor(this.color); pickers[topic] = this; } /*************************************************************************/ // Function for generating the color-picker /*************************************************************************/ ColorPicker.prototype.createPickingArea = function createPickingArea() { var area = document.createElement('div'); var picker = document.createElement('div'); area.className = 'picking-area'; picker.className = 'picker'; this.picking_area = area; this.color_picker = picker; setMouseTracking(area, this.updateColor.bind(this)); area.appendChild(picker); this.node.appendChild(area); }; ColorPicker.prototype.createHueArea = function createHueArea() { var area = docume...
...And 29 more matches
Gecko info for Windows accessibility vendors
This FAQ explains how makers of Windows screen readers, voice dictation packages and magnification software can support Gecko-based software. The base of our support for these products is MSAA (Microsoft Active Accessibility), external readonly DOM support, and the keyboard API/user interface. Definitions Here are some basic definitions that you'll need for this document to make sense: Gecko: The rendering engine for Firefox, Thunderbird, Nvu, Mozilla Seamonkey and other applications. Gecko is the internal engine that Mozilla uses to render any kind of web content. It supports HTML, XHTML, Cascading Style Sheets (CSS) and the Document Object Model (DOM). Microsoft Active Accessibility (MSAA) an API devised by Microsoft so that accessibi...
...an track what's going on inside the user interface of any software package that supports it. If you seriously need to understand MSAA, you'll need to read the docs on MSDN and play with the sample apps and code 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 su...
...nous 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 to reload or for a new page to load. Data is therefore stored and retrieved dynamically much faster. Roles, states and events: please read the MSAA documentation on MSDN if you are unfamiliar with these. in general we abbreviate by removing redundant words. For example, we may say EVENT_ALERT instead of the full EVENT_SYSTEM_ALERT. MSAA tree vs. DOM tree - what's the relation? The MSAA tree and the DOM tree are parallel structures, although the MSAA tree is a subset of the DOM tree. QueryService() can be used to switch between the in...
...And 27 more matches
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
31 browserid XUL, XUL Reference No summary! 32 button.type XUL Attributes, XUL Reference No summary! 33 buttonaccesskeyaccept XUL Attributes, XUL Reference No summary! 34 buttonaccesskeycancel XUL Attributes, XUL Reference No summary! 35 buttonaccesskeydisclosure XUL Attri...
...uch as a tab bar or a treeview). 422 Deprecated and defunct markup Reference, XUL {many elements on this page are wrongly marked as deprecated, this page needs review} 423 Dynamically modifying XUL-based user interface Add-ons, DOM, Extensions, XUL This article discusses manipulating 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. 424 FileGuide See IO 425 Accessing Files File and Stream Guide: [ nsIScriptableIO | Accessing Files | Getting File Information | Reading from Files | Writing to Fil...
... 472 expandToolbar XUL Methods, XUL Reference No summary! 473 extra1 XUL Methods, XUL Reference No summary! 474 extra2 XUL Methods, XUL Reference No summary! 475 focus XUL Methods, XUL Reference No summary! 476 getBrowserAtIndex XUL Methods, XUL Reference No summary! 477 getBrowserForDocument Method, Mozilla, Reference, Reference(2), XUL, XUL Methods, XUL Reference No summary! 478 getBrowserForTab XUL Methods, XUL Reference No summary! 479 getBrowserIndexForDocument XUL Methods, XUL Reference No summary! 480 getButton XUL Methods, XUL Reference No summary! 481 getDefaultSession XUL Methods, XUL Ref...
...And 26 more matches
Introduction to the DOM - Web APIs
The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web. In this guide, we'll briefly introduce the DOM. We'll look at how the DOM represents an HTML or XML document in memory and how you use APIs to create web content and applications. What is the DOM? ...
... The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web. In this guide, we'll briefly introduce the DOM. We'll look at how the DOM represents an HTML or XML document in memory and how you use APIs to create web content and applications. What is the DOM? ...
...ject Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web. In this guide, we'll briefly introduce the DOM. We'll look at how the DOM represents an HTML or XML document in memory and how you use APIs to create web content and applications. What is the DOM? The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming 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) repres...
...And 26 more matches
Using the W3C DOM - Archive of obsolete content
W3C DOM standards are well supported by modern browsers, however the standards are moving target so support for newer features should be tested before use. ...
... The W3C Document Object Model provides interfaces DOM elements to scriptable objects. W3C DOM standards are well supported by modern browsers, however the standards are moving target so support for newer features should be tested before use. ...
...W3C DOM standards are well supported by modern browsers, however the standards are moving target so support for newer features should be tested before use. ...
...And 25 more matches
nsIDocShell
Note that out-of-process browsers do not have an nsIDocShell; instead you can access the nsIDocShell object from a frame script. ...
...nterface guidelines void finishRestore(); void firePageHideNotification(in boolean isUnload); Native code only! void fireUnloadNotification(); Native code only! ...
...ad); Native code only! void fireUnloadNotification(); Native code only! ...
...And 25 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
damental DOM level 1 methods and how to use them from JavaScript. 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). Example: Creating an HTML table dynamically (Sample1.html) HTML <input type="button" value="Generate a table." onclick="generate_table()"> JavaScript function generate_table() { // get the refere...
...pecification. 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). ...
... well as methods specific to HTML documents (DOM 1 HTML). ...
...And 25 more matches
Color picker tool - CSS: Cascading Style Sheets
; 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 */ function Color(color) { if(color instanceof Color === true) { this.copy(color); return; } this.r = 0; this...
... return this.getHexa(); return this.getRGBA(); }; /*=======================================================================*/ /*=======================================================================*/ /*========== Capture Mouse Movement ==========*/ var setMouseTracking = function setMouseTracking(elem, callback) { elem.addEventListener('mousedown', function(e) { callback(e); document.addEventListener('mousemove', callback); }); document.addEventListener('mouseup', function(e) { document.removeEventListener('mousemove', callback); }); }; /*====================*/ // Color Picker Class /*====================*/ function ColorPicker(node) { this.color = new Color(); this.node = node; this.subscribers = []; var type = this.node.getAttribute('data-mode'); ...
...('hexa', 'hexa', this.inputChangeHexa.bind(this)); this.setColor(this.color); pickers[topic] = this; } /*************************************************************************/ // Function for generating the color-picker /*************************************************************************/ ColorPicker.prototype.createPickingArea = function createPickingArea() { var area = document.createElement('div'); var picker = document.createElement('div'); area.className = 'picking-area'; picker.className = 'picker'; this.picking_area = area; this.color_picker = picker; setMouseTracking(area, this.updateColor.bind(this)); area.appendChild(picker); this.node.appendChild(area); }; ColorPicker.prototype.createHueArea = function createHueArea() { var area = docume...
...And 25 more matches
Browser Feature Detection - Archive of obsolete content
M APIs and lists the percentage of names that your browser actually defines followed by a list of each of the API names tested along with an indication of whether the name was defined for your browser. It is clear from these test results that Netscape 7.0x and Mozilla Firefox have the greatest DOM support although Internet Explorer, Safari, and Opera have sufficient DOM CSS 1 and DOM Level 1 & 2 document property and method support to enable cross browser web development. Test Summary Standard Netscape 7.0x Firefox 1.5 Safari 2 Opera 7 / 8.5-9.0 Internet Explorer 6 / 7 DOM Core 1 100% 100% 100% 75% / 91% 75% / 75% DOM Core 2 100% 100% 100% 70% / 94% 58% / 58% DOM 1 HTML 100% 100% 100% 100% / 100% ...
...0% 75% / 91% 75% / 75% DOM Core 2 100% 100% 100% 70% / 94% 58% / 58% DOM 1 HTML 100% 100% 100% 100% / 100% 100% / 100% DOM CSS 1 100% 100% 100% 100% / 100% 96% / 96% DOM CSS 2 100% 98% 67% 71% / 83% 38% / 42% Test Results Cross Reference DOM Core Level 1 Support for properties/methods in document name Firefox 1.5 IE 6 & 7 Opera 8.54 - 9.01 Document.doctype true true true Document.implementation true true true Document.documentElement true true true Document.createElement() true true true Document.createDocumentFragment() true true true Document.createTextNode() true ...
...efox 1.5 IE 6 & 7 Opera 8.54 - 9.01 Document.doctype true true true Document.implementation true true true Document.documentElement true true true Document.createElement() true true true Document.createDocumentFragment() true true true Document.createTextNode() true true true Document.createComment() true true true Document.createCDATASection() true false true Document.createProcessingInstruction() true false true Document.createAttribute() true true true Document.createEntityReference()Obsolete since Gecko 7 (method present but only returns null: bug 9850) false false Document.getElement...
...And 24 more matches
Mozilla
evel technical overview of the architecture of the extensible, object-based Mozilla application framework. Accessibility and Mozilla Accessibility is the idea that software (among other things) should be designed to be usable and, as much as possible, convenient to use for people with disabilities. Mozilla strives to make its software accessible; the documents below cover the ways in which we do so. Add-ons Add-ons allow developers to extend and modify the functionality of Firefox. Adding a new CSS property This page describes how to add a new CSS property to the style system. The style system is the part of the code in Gecko that is responsible for producing a computed value for eve...
...ng a new CSS property This page describes how to add a new CSS property to the style system. The style system is the part of the code in Gecko that is responsible for producing a computed value for every property for every element. See the Gecko Overview for more information about the style system. Adding a new event This draft document covers how to add a new event to the Mozilla (Firefox) source code. Adding a new word to the en-US dictionary Occasionally bugs are filed pointing out situations where perfectly legitimate words are missing from the English spell check dictionary in Firefox. This article describes the process for adding a word to the dictionary. Adding phi...
... the codebase. Android-specific test suites There are several Android-specific test suites that run on the Firefox for Android codebase: API change rules Until further notice, the following rules govern API changes: Application cache implementation overview This happens in nsHttpChannel::OpenCacheEntry(). All top level document loading (navigation) channels are set ChooseApplicationCache flag, which happens in nsDocShell::DoURILoad(). Channels having that flag set are searching for nsIApplicationCache object prior inspecting normal HTTP cache. nsIApplicationCacheService::ChooseApplicationCache is given the URL the channel is about to load. It synchronously returns an nsIApplicationCache object representing t...
...And 24 more matches
HTML attribute: rel - HTML: Hypertext Markup Language
Web › HTML › Attributes › rel
The rel attribute defines the relationship between a linked resource and the current document. Valid on <link>, <a>, <area>, and <form>, the supported values depend on the element on which the attribute is found. The type of relationships is given by the value of the rel attribute, which, if present, must have a value that is an unordered set of unique space-separated keywords, which are listed in the following table. Every keyword within a space seperated value should be unique within that value. Values for the rel attribute, and the elements for which each is relevant rel value Description <link> <a> and <area> <form> alternate Alternate representations of the current document. Link Link Not allowed author Author of the current docu...
...ption <link> <a> and <area> <form> alternate Alternate representations of the current document. Link Link Not allowed author Author of the current document or article. Link Link Not allowed bookmark Permalink for the nearest ancestor section. Not allowed Link Not allowed canonical Preferred URL for the current document. Link Not allowed Not allowed dns-prefetch Tells the browser to preemptively perform DNS resolution for the target resource's origin External Resource Not allowed Not allowed external Referenced document is not part of the same site as the current document. Not allowed Annotation Annotation help Link to context-sensitive help. Link...
... Tells the browser to preemptively perform DNS resolution for the target resource's origin External Resource Not allowed Not allowed external Referenced document is not part of the same site as the current document. Not allowed Annotation Annotation help Link to context-sensitive help. Link Link Link icon Icon representing the current document. External Resource Not allowed Not allowed license Indicates that the main content of the current document is covered by the copyright license described by the referenced document. Link Link Link manifest Web app manifest Link Not allowed Not allowed modulepreload Tells to browser to preemptively fetch the script and store it in the d...
...And 23 more matches
Timing element visibility with the Intersection Observer API - Web APIs
In this article, we'll build a mock blog which has a number of ads interspersed among the contents of the page, then use the Intersection Observer API to track how much time each ad is visible to the user. When an ad exceeds one minute of visible time, it will be replaced with a new one. ...
...A reference to the <main> element's HTMLElement object in the DOM. This is where we'll insert the articles and ads. nextArticleID Each article is given a unique ID number; this variable tracks the next ID to use, starting with 1. visibleAds A Set which we'll use to track the ads currently visible on the screen. previouslyVisibleAds Used to temporarily store the list of visible ads while the document is not visible (for example, if the user has tabbed to another page). adObserver Will hold our IntersectionObserver used to track the intersection between the ads and the <main> element's bounds. refreshIntervalID Used to store the interval ID returned by setInterval(). This interval will be used to trigger our periodic refreshes of the ads' content. Setting up To set things up, we run the...
...he intersection between the ads and the <main> element's bounds. refreshIntervalID Used to store the interval ID returned by setInterval(). This interval will be used to trigger our periodic refreshes of the ads' content. ...
...And 22 more matches
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. ...
..., the examples use common APIs, tricks, and patterns in JavaScript for manipulating the document object. ...
... in JavaScript for manipulating the document object. ...
...And 21 more matches
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
and was originally published in Japanese for the Firefox Developers Conference Summer 2007. Shimoda-san is a co-author of Firefox 3 Hacks (O'Reilly Japan, 2008). Before you learn how to develop extensions, let's learn about XUL, the XML-based User-interface Language, which is one of the building blocks for extensions. Introduction An overview of XUL XUL is an XML-based language, and was developed to be the GUI markup language for the Mozilla browser. ...
...languages, and XUL could be considered an evolutionary step from that. Similar approaches are found in XAML, which is used in Windows Vista, and Flex, which is used in Adobe Flash. Like web pages, which display the same regardless of platform, applications marked up in XUL will work the same in any environment where Firefox runs. Because HTML was originally conceived as a language for marking up documents, specifically web pages, it is inevitably lacking in functionality for marking up applications. XUL, on the other hand, was conceived from the ground up as a markup language for user interfaces, and makes it possible to insert UI components with sophisticated features just by writing tags, without any particular scripting. Unlike languages with formal specifications that have been standardized ...
..., was conceived from the ground up as a markup language for user interfaces, and makes it possible to insert UI components with sophisticated features just by writing tags, without any particular scripting. Unlike languages with formal specifications that have been standardized by bodies like the W3C, XUL currently does not have an explicit specification. Note: Although there is a specification document, its markup is based on implementations and markup as of 2001, and current XUL differs from it in many aspects. For the latest XUL specifications, please see the XUL Reference on MDC and the XUL page in the Mozilla wiki. For each element that I explain in this chapter, I will illustrate it with a source code example. You can type these examples up and open them in Firefox to see how they behave ...
...And 20 more matches
tabbrowser - Archive of obsolete content
<< XUL Reference home [ Examples | Attributes | Properties | Methods | Related ] This element is used for holding a set of read-only views of Web documents. It is similar to the browser element, except that multiple documents can be displayed, each in a separate tab. Note: Starting in Firefox 3 (XULRunner/Gecko 1.9), this is only used in the main Firefox window and cannot be used in other XUL windows by third-party applications or extensions. ...
...rting in Firefox 3 (XULRunner/Gecko 1.9), this is only used in the main Firefox window and cannot be used in other XUL windows by third-party applications or extensions. ...
...e used in other XUL windows by third-party applications or extensions. ...
...And 20 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
If you're implementing controls/widgets, you should also see the Accessible Toolkit Checklist. If you're interested in more about Gecko's MSAA implementation, read Gecko Info for Windows Accessibility Vendors to learn how MSAA clients can utilize Gecko's MSAA support. ...
... Active Accessibility (MSAA) API, used on Windows operating systems to support assistive technologies for users with disabilities. Third party assistive technology, such as screen readers, screen magnifiers and voice input software, want to track what's happening inside Mozilla. They need to know about focus changes and other events, and it needs to know what objects are contained in the current document or dialog box. Using this information, a screen reader will speak out loud important changes to the document or UI, and allow the user to track where they navigate. The screen reader user can navigate the web page using screen reader commands or browser commands, and the two pieces of software must remain in sync. Some screen readers can even show information on a refreshable braille display. Scr...
...user to track where they navigate. The screen reader user can navigate the web page using screen reader commands or browser commands, and the two pieces of software must remain in sync. Some screen readers can even show information on a refreshable braille display. Screen magnifiers will zoom to the focus, keeping it on the screen at all times, or even allow the user to enter a special low vision document reading mode, with a variety of features such as ticker mode where text is streamed on a single line. Finally, voice dictation software needs to know what's in the current document or UI in order to implement "say what you see" kinds of features. On Microsoft Windows, these kinds of assistive technology acquire this necessary information via a combination of hacks, MSAA and proprietary DOMs. MSA...
...And 20 more matches
Elements - Archive of obsolete content
Bindings This section is tested and adjusted for the current Firefox implementation. Please edit only if an actual behavior differs from the described one. Please do not edit only on the basis of another XBL specification. <!ELEMENT bindings ( binding* ) > Hierarchy: root element May contain: <binding> The bindings element is the root element of any XBL document. It should usually declare XBL as the default namespace (unless an XBL namespace prefix is used) and it may additionally declare other namespace prefixes used in your binding. bindings contains zero or more binding elements as children. Each binding child element defines a unique binding that can be attached to elements in other documents. An element can have only one binding attached (explicitly or inherited) at one momen...
...orld.html. Next: bindings > binding element. Notes In the current stable releases of Mozilla products (e.g. Firefox 2) it is impossible to attach bindings to table sub-elements (rows, cells etc.) You can attach binding only to the table element itself. This has been fixed for future versions of Mozilla products. See bug 83830 for more information and for workarounds. Default encoding in XML documents (including XBL files) is UTF-8. An explicit encoding declarations may be present to override the default, for example <?xml version="1.0" encoding="ISO-8859-1"?> URI in namespace declarations is an opaque string used to uniquely identify the namespace. It doesn't have to (and often it doesn't) point to some actual schema or a namespace-related resource. Namespaces in XML Besides the default na...
... scripting is disabled. In the latter case all methods and handlers will be blocked, but the anonymous content and styling will be still used. Given that the CSS declarations should be always used - unless you need to add bindings at runtime to individual elements. A binding element may contain a resources tag, a content tag, a implementation tag and a handlers tag. id - The id attribute is a document-unique identifier. For the binding element, this attribute is required, since it is used to attach bindings. extends - The extends attribute is used to specify the URL of a binding that this binding inherits from (see Inheritance of Implementations). The URL specifies a particular binding document. The # notation must be used to point to a specific binding id within a binding document. Note that...
...And 19 more matches
Border-image generator - CSS: Cascading Style Sheets
0%; 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) { this.select(); }); input.addEventListener('change', function(e) { var value = parseFloat(e.target.value); if (isNaN(value) === true) setValue(obj.topic, obj.value); else setValue(obj.topic, value); }); r...
...precision * 10 + 'px'; input.addEventListener('click', function(e) { this.select(); }); input.addEventListener('change', function(e) { var value = parseFloat(e.target.value); if (isNaN(value) === true) setValue(obj.topic, obj.value); else setValue(obj.topic, value); }); return input; }; var SliderComponent = function SliderComponent(obj, sign) { var slider = document.createElement('div'); var startX = null; var start_value = 0; slider.addEventListener("click", function(e) { document.removeEventListener("mousemove", sliderMotion); setValue(obj.topic, obj.value + obj.step * sign); }); slider.addEventListener("mousedown", function(e) { startX = e.clientX; start_value = obj.value; document.body.style.cursor = "e-resize"; document.ad...
...ll; var start_value = 0; slider.addEventListener("click", function(e) { document.removeEventListener("mousemove", sliderMotion); setValue(obj.topic, obj.value + obj.step * sign); }); slider.addEventListener("mousedown", function(e) { startX = e.clientX; start_value = obj.value; document.body.style.cursor = "e-resize"; document.addEventListener("mouseup", slideEnd); document.addEventListener("mousemove", sliderMotion); }); var slideEnd = function slideEnd(e) { document.removeEventListener("mousemove", sliderMotion); document.body.style.cursor = "auto"; slider.style.cursor = "pointer"; }; var sliderMotion = function sliderMotion(e) { slider.style.cursor = "e-resize"; var delta = (e.clientX - startX) / obj.sensivity | 0; var value = delta * ...
...And 19 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
Sending data from unprivileged document to chrome An easy way to send data from a web page to an extension is by using custom DOM events. In your extension's browser.xul overlay, write code which listens for a custom DOM event. Here we call the event MyExtensionEvent. var myExtension = { myListener: function(evt) { alert("Received from web page: " + evt.target.getAttribute("attribute1") + "/" + evt.target.getAttribute("attribute2")); } } document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); // The last value is a Mozilla-specific value to indicate untrusted content is allowed to trigger the event. The data from the web page (unprivileged code) will be the values of attribute1 and attribute2. To trigger the al...
...", function(e) { myExtension.myListener(e); }, false, true); // The last value is a Mozilla-specific value to indicate untrusted content is allowed to trigger the event. The data from the web page (unprivileged code) will be the values of attribute1 and attribute2. ...
... to trigger the event. The data from the web page (unprivileged code) will be the values of attribute1 and attribute2. To trigger the alert() in the listener and pass the data from the web page, write code such as this in the web page: var element = document.createElement("MyExtensionDataElement"); element.setAttribute("attribute1", "foobar"); element.setAttribute("attribute2", "hello world"); document.documentElement.appendChild(element); var evt = document.createEvent("Events"); evt.initEvent("MyExtensionEvent", true, false); element.dispatchEvent(evt); This code creates an arbitrary element -- <MyExtensionDataElement/> -- and inserts it into the web page's DOM. Values are set for two arbitrary attributes on the element. These can also be named anything you like, but we've chosen attribute...
...And 18 more matches
browser - Archive of obsolete content
<< XUL Reference home [ Examples | Attributes | Properties | Methods | Related ] A XUL <browser> element represents a frame which is expected to contain a view of a Web document. It is similar to an iframe except that it holds a page history and contains additional methods to manipulate the currently displayed page. Are you here looking for information about the Firefox web browser, or because you'd like to download the latest version of Firefox? Get Firefox Most of the properties and methods of the browser will rarely be used and can only be called from chrome URLs. Other URLs will need to use the document and history objects to change the displayed document. Attributes autocompleteenabled, autocompletepopup, autoscroll, disablehistory, disableglobalhistory, disablese...
...rowser will rarely be used and can only be called from chrome URLs. Other URLs will need to use the document and history objects to change the displayed document. ...
...ory objects to change the displayed document. ...
...And 18 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
ppeared. 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 involved testing whether the browser supported particular objects. An example of this approach involved testing for the existence of the document.images object. While object based detection was used in some circumstances, many web authors continued to use the vendor/version approach to distinguishing web browsers in their client side scripts. Since the user agent string was exposed as a property of the navigator object (e.g. navigator.userAgent), many web authors used the same logic in their client side scripts as they had used earlier in...
...tion to sharing several features which were not available in earlier versions, each implemented their own (incompatible) competing abilities to manipulate content in a web page. Since each vendor's browser implemented different objects to perform DHTML, web authors began to use object detection to distinguish vendor/version through the existence of particular JavaScript objects. The existence of document.layers was sufficient to be sure that the browser was Netscape Navigator 4 while the existence of document.all was sufficient to be sure that the browser was Microsoft Internet Explorer 4. An implicit assumption by many web authors around this time was the there were only two types of browser available... Netscape Navigator and Microsoft Internet Explorer. These strategies of classifying browser...
...ainable and violates the basic principles of web authoring! I strongly advise everyone to avoid this trap. Problems caused by inappropriate Browser Detection Excluding Unknown Browsers If you only provide tests for specific browsers in your detection logic, your site will not be usable if a visitor uses a different browser. ...
...And 18 more matches
Mozilla accessibility architecture
This page is maintained by Aaron Leventhal and by the Mozilla Accessibility Community. Feedback and constructive suggestions are encouraged. 1. Intro This document is for people who wish to understand the architecture of Mozilla's accessibility API module, which provides support for platform accessibility APIs. Accessibility APIs are used by 3rd party software like screen readers, screen magnifiers, and voice dictation software, which need information about document content and UI controls, as well as important events like changes of focus. ...
... screen magnifiers, and voice dictation software, which need information about document content and UI controls, as well as important events like changes of focus. Mozilla supports two accessibility APIs: Microsoft Active Accessibility (MSAA) on Windows and Accessibility Tool Kit (ATK) on Linux and Unix. We do not currently support the Carbon accessibility model for Apple's OS X. Please note, the documentation for implementing an MSAA server has moved. You may also wish to read Gecko Info for Windows Accessibility Vendors, a primer for vendors of 3rd party accessibility software, on how MSAA clients can utilize Gecko's support. If you're interested in Linux or UNIX accessibility, check out Mozilla's ATK project page. ...
...2. Accessible Nodes and Interfaces Every node in the DOM tree could be important to 3rd party assistive technology. ...
...And 18 more matches
Mozilla Web Developer FAQ
In the Quirks mode--for the purpose of backwards compatibility--Gecko mimics some behaviors of legacy browsers in ways that are spec violations. The Almost Standards mode is like the Standards mode except it addresses the issue of the next question by rendering table cells with images in the traditional way. ...
...In the Quirks mode--for the purpose of backwards compatibility--Gecko mimics some behaviors of legacy browsers in ways that are spec violations. The Almost Standards mode is like the Standards mode except it addresses the issue of the next question by rendering table cells with images in the traditional way. ...
...s mode--for the purpose of backwards compatibility--Gecko mimics some behaviors of legacy browsers in ways that are spec violations. The Almost Standards mode is like the Standards mode except it addresses the issue of the next question by rendering table cells with images in the traditional way. The mode is picked based on the doctype declaration (or the lack thereof) at the beginning of an HTML document. The easiest way to make sure that the Standards mode is activated for HTML, is to use this doctype declaration: <!DOCTYPE html> The easiest way to make sure that the Almost Standards mode is activated for HTML, is to use this doctype declaration: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> The easiest way to activate the Quirks...
...And 18 more matches
XML in Mozilla - Archive of obsolete content
al World Wide Web Consortium (W3C) Recommendations and drafts from the XML family of specifications are supported, as well as other related technologies. This page is outdated. Please help updating it with current information. Supported Core XML W3C Recommendations The core XML support includes parsing XML without validation (we use the Expat parser), displaying XML with CSS, manipulating XML documents with scripts via DOM, associating stylesheets with XML documents, and namespaces in XML. The core support is very good with few bugs. DTDs and Other External Entities Mozilla does not load external entities from the web. Mozilla can load external entities whose system identifier uses the chrome protocol. This feature is used mainly to localize Mozilla to different languages (the UI strings are s...
...Other External Entities Mozilla does not load external entities from the web. Mozilla can load external entities whose system identifier uses the chrome protocol. This feature is used mainly to localize Mozilla to different languages (the UI strings are stored in external DTD files). Another exception is an entity whose system identifier is a relative path, and the XML declaration states that the document is not standalone (default), in which case Mozilla will try to look for the entity under <bin>/res/dtd directory. Mozilla may also make an exception with XHTML documents, see below. Mozilla will read internal (DTD) subsets, and in special circumstances external DTDs as explained above and will use this information to recognize ID type attributes, default attribute values, and general entities. Ot...
...ault), in which case Mozilla will try to look for the entity under <bin>/res/dtd directory. Mozilla may also make an exception with XHTML documents, see below. Mozilla will read internal (DTD) subsets, and in special circumstances external DTDs as explained above and will use this information to recognize ID type attributes, default attribute values, and general entities. Other Notes A lot of the Document Object Model (DOM, W3C Recommendations and drafts) applies to XML. Likewise, the Cascading Style Sheets (CSS, W3C Recommendations and drafts) style language can be used to style XML documents. The code for most the core XML can be found in the following directories on the Mozilla mercurial repository: content/xml/, parser/expat/ and parser/htmlparser/. The newsgroup to discuss XML in Mozilla depe...
...And 17 more matches
Introduction to XUL - Archive of obsolete content
which will work on multiple platforms. But proper UI descriptions which take into account various platforms' differing ideas about proper placement of such things as dialog buttons will require some platform-specific work. A single XUL specification can only cross-platform to a degree. UI designers and build engineers will need to maintain separate, platform-specific versions of at least some XUL documents. "XPToolkit" is rather synonymous with XPFE. Though the former term seems more concrete than the other, and therefore is not an exact replacement, no one is completely certain why we have both. "XUL" already introduced, is an application of XML used to describe the layout of most windows in the Mozilla browser, including and especially the main, browser window. Scope This paper makes no atte...
...rm seems more concrete than the other, and therefore is not an exact replacement, no one is completely certain why we have both. "XUL" already introduced, is an application of XML used to describe the layout of most windows in the Mozilla browser, including and especially the main, browser window. Scope This paper makes no attempt to explain requirements. We don't have a current "requirements" document. XPToolkit Architecture is a better place to gain an understanding of such things. This paper contains a short introduction to Mozilla front-end architecture, concentrating on the task of building UIs. It is, as always, incomplete. Mozilla applications will be built of "small" components like dialog buttons and mail inbox folders, which we collectively term "widgets." Within a widget, drawing an...
...x folders, which we collectively term "widgets." Within a widget, drawing and user interactions are completely under control of the individual widget, and set when the widget was built. Relative placement of widgets, their interactions with each other, and optionally some of their configuration, will be controlled by a UI layout specified in a script whose structure is defined in this and related documents. Widgets are pieces of the application largely self-contained, generally corresponding to a rectangle of window real estate. Widgets will generally live grouped in separate, dynamically loaded libraries. A widget may expect to own a piece of a window (a toolbar or toolbar set), or it may be expected to work within or without a window (menubars, depending on the platform). It may not be a part o...
...And 17 more matches
Mozilla DOM Hacking Guide
Mozilla gives you the opportunity not only to use very powerful and complete DOM support, but also to work on a world-class implementation of one of the greatest Internet technologies ever created. Mozilla's DOM is coded almost entirely in C++. Seriously hacking on it requires excellent knowledge of C++ and XPCOM, Mozilla's own component model. ...
...illa's own component model. In this document I will try to outline the main aspects of the implementation, beginning with the Class Info mechanism, which lies at the heart of the DOM, then with the description of various interfaces and classes. Since I am myself still learning how it works, don't expect this to be a complete reference quite yet. If you can contribute any time or knowledge to this document, it is greatly appreciated! Target audience: People interested in learning how the DOM is implemented. Prior knowledge of C++ and XPCOM is assumed. If you don't know XPCOM yet, and would like to be able to read this document quickly, you can read the Introduction to XPCOM for the DOM. Otherwise, for more detailed XPCOM documentation, please see the XPCOM project page. Class Info and Helper Clas...
...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. ...
...And 17 more matches
Event reference
la-specific events are listed so that add-ons can use them to interact with the browser. Most common categories Resource events Event Name Fired When error A resource failed to load. abort The loading of a resource has been aborted. load A resource and its dependent resources have finished loading. beforeunload The window, the document and its resources are about to be unloaded. unload The document or a dependent resource is being unloaded. Network events Event Name Fired When online The browser has gained access to the network. offline The browser has lost access to the network. Focus events Event Name Fired When focus An el...
...ed. compositionend The composition of a passage of text has been completed or canceled. View events Event Name Fired When fullscreenchange An element was toggled to or from fullscreen mode. fullscreenerror It was impossible to switch to fullscreen mode for technical reasons or because the permission was denied. resize The document view has been resized. scroll The document view or an element has been scrolled. Clipboard events Event Name Fired When cut The selection has been cut and copied to the clipboard copy The selection has been copied to the clipboard paste The item from the clipboard has been pasted Keyboard events Event...
...Each event is lis...
...And 17 more matches
HTML elements reference - HTML: Hypertext Markup Language
Web › HTML › Element
asily. An alphabetical list of all elements is provided in the sidebar on every element's page as well as this one. For more information about the basics of HTML elements and attributes, see the section on elements in the Introduction to HTML article. Main root Element Description <html> The HTML <html> element represents the root (top-level element) of an HTML document, so it is also referred to as the root element. All other elements must be descendants of this element. Document metadata Metadata contains information about the page. This includes information about styles, scripts and data to help software (search engines, browsers, etc.) use and render the page. Metadata for styles and scripts may be defined in the page or link to another file that ha...
...n about the page. This includes information about styles, scripts and data to help software (search engines, browsers, etc.) use and render the page. Metadata for styles and scripts may be defined in the page or link to another file that has the information. Element Description <base> The HTML <base> element specifies the base URL to use for all relative URLs in a document. <head> The HTML <head> element contains machine-readable information (metadata) about the document, like its title, scripts, and style sheets. <link> The HTML External Resource Link element (<link>) specifies relationships between the current document and an external resource. This element is most commonly used to link to stylesheets, but is also used to establish sit...
...also used to establish site icons (both "favicon" style icons and icons for the home screen and apps on mobile devices) among other things. <meta> The HTML <meta> element represents metadata that cannot be represented by other HTML meta-related elements, like <base>, <link>, <script>, <style> or <title>. <style> The HTML <style> element contains style information for a document, or part of a document. <title> The HTML Title element (<title>) defines the document's title that is shown in a browser's title bar or a page's tab. Sectioning root Element Description <body> The HTML <body> Element represents the content of an HTML document. There can be only one <body> element in a document. Content sectioning Cont...
...And 17 more matches
Fullscreen API - Web APIs
ay wish to consider using a library such as Fscreen for vendor agnostic access to the Fullscreen API. Interfaces The Fullscreen API has no interfaces of its own. Instead, it augments several other interfaces to add the methods, properties, and event handlers needed to provide full-screen functionality. These are listed in the following sections. Methods The Fullscreen API adds methods to the Document and Element interfaces to allow turning off and on full-screen mode. Methods on the Document interface Document.exitFullscreen() Requests that the user agent switch from full-screen mode back to windowed mode. Returns a Promise which is resolved once full-screen mode has been completely shut off. Methods on the Element interface Element.requestFullscreen() Asks the user agent to place ...
...de has been completely shut off. Methods on the Element interface Element.requestFullscreen() Asks the user agent to place the specified element (and, by extension, its descendants) into full-screen mode, removing all of the browser's UI elements as well as all other applications from the screen. Returns a Promise which is resolved once full-screen mode has been activated. Properties The Document interface provides properties that can be used to determine if full-screen mode is supported and available, and if full-screen mode is currently active, which element is using the screen. DocumentOrShadowRoot.fullscreenElement The fullscreenElement property tells you the Element that's currently being displayed in full-screen mode on the DOM (or shadow DOM). If this is null, the document is n...
...rties that can be used to determine if full-screen mode is supported and available, and if full-screen mode is currently active, which element is using the screen. DocumentOrShadowRoot.fullscreenElement The fullscreenElement property tells you the Element that's currently being displayed in full-screen mode on the DOM (or shadow DOM). If this is null, the document is not in full-screen mode. document.fullscreenEnabled The fullscreenEnabled property tells you whether or not it is possible to engage full-screen mode. This is false if full-screen mode is not available for any reason (such as the "fullscreen" feature not being allowed, or full-screen mode not being supported). Event handlers The Fullscreen API defines two events which can be used to detect when full-screen mode is turned on a...
...And 16 more matches
Pointer Lock API - Web APIs
(from https://w3c.github.io/pointerlock/#extensions-to-the-element-interface) pointerLockElement and exitPointerLock() The Pointer lock API also extends the Document interface, adding both a new property and a new method. The new property is used for accessing the c...
...uest pointer lock on a canvas element: canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock; canvas.requestPointerLock() If a user has exited pointer lock via the default unlock gesture, or pointer lock has not previously been entered for this document, an event generated as a result of an engagement gesture must be received by the document before requestPointerLock will succeed. (from https://w3c.github.io/pointerlock/#extensions-to-the-element-interface) pointerLockElement and exitPointerLock() The Pointer lock API also extends the Document interface, adding both a new property and a new method. The new property is used for accessing the currently locked element (if any), and is named pointerLockElement and the new method on Do...
...d is named pointerLockElement and the new method on Document is exitPointerLock() and, as the name implies, it is used to exit the pointer lock. The pointerLockElement property is useful for determining if any element is currently pointer locked (e.g., for doing a Boolean check) and also for obtaining a reference to the locked element, if any. ...
...And 16 more matches
Box-shadow generator - CSS: Cascading Style Sheets
node.getAttribute('data-value') | 0; var snap = node.getAttribute('data-snap'); var topic = node.getAttribute('data-topic'); this.min = min; this.max = max > 0 ? max : 100; this.step = step === 0 ? 1 : step; this.value = value <= max && value >= min ? value : (min + max) / 2 | 0; this.snap = snap === "true" ? ...
...tent = '-'; node.addEventListener("click", function() { decrement(topic); }); } if (type === "add") { node.textContent = '+'; node.addEventListener("click", function() { increment(topic); }); } } var setInputComponent = function setInputComponent(node) { var topic = node.getAttribute('data-topic'); var unit_type = node.getAttribute('data-unit'); var input = document.createElement('input'); var unit = document.createElement('span'); unit.textContent = unit_type; input.setAttribute('type', 'text'); node.appendChild(input); node.appendChild(unit); input.addEventListener('click', function(e) { this.select(); }); input.addEventListener('change', function(e) { setValue(topic, e.target.value | 0); }); subscribe(topic, function(value) {...
...clientWidth; var offset = slider.pointer.clientWidth; var pos = (value - slider.min) * width / delta; slider.value = value; slider.pointer.style.left = pos - offset / 2 + "px"; slider.node.setAttribute('data-value', value); notify.call(slider); } var setMouseTracking = function setMouseTracking(elem, callback) { elem.addEventListener("mousedown", function(e) { callback(e); document.addEventListener("mousemove", callback); }); document.addEventListener("mouseup", function(e) { document.removeEventListener("mousemove", callback); }); } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscri...
...And 16 more matches
Authoring MathML - MathML
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. ...
...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. ...
... is well-integrated in HTML5 and in particular you can use usual Web features like CSS, DOM, Javascript or SVG. This is out of the scope of this document but anyone with basic knowledge of Web languages will easily be able to mix these features with MathML. Check out our demos and MathML references for more details. Using MathML MathML in HTML pages You can use Presentation MathML inside HTML5 documents: <!DOCTYPE html> <html> <head> <title>MathML in HTML5</title> </head> <body> <h1>MathML in HTML5</h1> <p> Square root of two: <math> <msqrt> <mn>2</mn> </msqrt> </math> </p> </body> </html> Content MathML is not supported by browsers. It's recommended to convert your Content MathML markup into Presentation MathML before publishing it, for example with...
...And 16 more matches
HTML to DOM - Archive of obsolete content
ion, 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. ...
... 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. ...
...e 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. ...
...And 15 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
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: Acquisition of Information Data acquisition can be implemented using JavaScript and remote procedure calls using SOAP-based RPC mechanism or using interfaces like XMLHTTPRequest (currently offered in Netscape 7 and Internet Explorer 6). Data Bind: Mutation in the Current Document This step takes care of applying the changes into the curre...
...here are basically two steps in this process: Data Load: Acquisition of Information Data acquisition can be implemented using JavaScript and remote procedure calls using SOAP-based RPC mechanism or using interfaces like XMLHTTPRequest (currently offered in Netscape 7 and Internet Explorer 6). Data Bind: Mutation in the Current Document This step takes care of applying the changes into the current document, based on the data loaded, and uses DOM interfaces. The mechanism can be as simple as copying new content to the current document, or as complex as performing dynamic transformations on the data source before applying the changes into the current document. For example, if a given web site's framework uses XSLT to format XML contents as HTML, would be appropriate to reuse XSLT to format new data t...
...The next section illustrates a case of implementation using JavaScript, IFRAMEs and DOM. Inner-Browsing with IFRAMES and JavaScript A very simple way to approach inner-browsing is to use HTML IFRAMES to retrieve data from a web server and update the main page. ...
...And 15 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. ...
...TD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US"> <head> <title>Problem 1 - &lt; 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 - &lt; in XHTML</h1> <p> This document is not well formed due to the use of a raw &lt;. </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/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US"> <head> <title>Problem 2 - Comments in XHTML</title> ...
... </p> <dl> <dt>Mozilla 1.1+/Opera 7</dt> <dd>Do not apply CSS or execute the JavaScript.</dd> <d...
...And 15 more matches
Index - Learn web development
ost, Learn, Web, publish, website Google App Engine is a powerful platform that lets you build and run applications on Google's infrastructure -- whether you need to build a multi-tiered web application from scratch or host a static website. Here's a step-by-step guide to hosting your website on Google App Engine. ...
...ite. It was invented by Brendan Eich (co-founder of the Mozilla project), the Mozilla Foundation, and the Mozilla Corporation. 43 Publishing your website Beginner, CodingScripting, FTP, GitHub, Google App Engine, Learn, Web, l10n:priority, publishing, web server Publishing a website is a complex topic because there are many ways to go about it. This article doesn't attempt to document all the possible methods. Instead, it explains the advantages and disadvantages of three approaches that are practical for beginners. Then it steps through one method that can work right away for many readers. 44 The web and web standards Beginner, Front-end, Learn, Web, Web Standards This article provides some useful background on the Web -- how it came about, what web stand...
... Learn, Simple, l10n:priority, step by step Before doing anything, you need some ideas. What should your website actually do? A website can do basically anything, but, for your first try, you should keep things simple. We'll start by creating a simple webpage with a heading, an image, and a few paragraphs. 46 How to contribute to the Learning Area on MDN Beginner, Contribute, Documentation, Guide, Learn, MDN Meta, l10n:priority On this page, you'll find everything you need to start helping improve MDN's learning content. There are many things you can do, depending on how much time you have and whether you are a beginner, a web developer, or a teacher. 47 Index Index, Learn, MDN Meta Found 348 pages: 48 JavaScript -- Dynamic client-side scr...
...And 15 more matches
Applying styles and colors - Web APIs
nothing too spectacular happening here. We use the two variables i and j to generate a unique RGB color for each square, and only modify the red and green values. The blue channel has a fixed value. By modifying the channels, you can generate all kinds of palettes. By increasing the steps, you can achieve something that looks like the color palettes Photoshop uses. ...
...ct(j * 25, i * 25, 25, 25); } } } <canvas id="canvas" width="150" height="150"></canvas> draw(); The result looks like this: ScreenshotLive sample A strokeStyle example This example is similar to the one above, but uses the strokeStyle property to change the colors of the shapes' outlines. We use the arc() method to draw circles instead of squares. ...
...loop draws a set of circles with an increasing radius. The final result is a radial gradient. By overlaying ever more circles on top of each other, we effectively reduce the transparency of the circles that have already been drawn. By increasing the step count and in effect drawing more circles, the background would completely disappear from the center of the image. ...
...And 15 more matches
Creating a cross-browser video player - Developer guides
ing with the individual buttons, a number of initialisation calls are required. To begin with, it's a good idea to first check if the browser actually supports the <video> element and to only setup the custom controls if it does. This is done by simply checking if a created <video> element supports the canPlayType() method, which any supported HTML5 <video> element should. ...
...yType() method, which any supported HTML5 <video> element should. var supportsVideo = !!document.createElement('video').canPlayType; if (supportsVideo) { // set up custom controls // ... } Once it has been confirmed that the browser does indeed support HTML5 video, it's time to set up the custom controls. ...
...nt should. var supportsVideo = !!document.createElement('video').canPlayType; if (supportsVideo) { // set up custom controls // ... } Once it has been confirmed that the browser does indeed support HTML5 video, it's time to set up the custom controls. ...
...And 15 more matches
XPath snippets - XPath
a few simple utility functions based on standard interfaces from the DOM Level 3 XPath specification that expose XPath functionality to JavaScript code. 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. Example: Defining a custom node-specific evaluateXPath() utility function // Evaluate an XPath expression aExpression against a given DOM node // or Document object (aNode), returning the results as an array // thanks wanderingstan at morethanwarm dot mail dot com for the // initial work. function evaluateXPath(aNode, aExpr) { ...
...ng a custom node-specific evaluateXPath() utility function // Evaluate an XPath expression aExpression against a given DOM node // or Document object (aNode), returning the results as an array // thanks wanderingstan at morethanwarm dot mail dot com for the // initial work. function evaluateXPath(aNode, aExpr) { var xpe = new XPathEvaluator(); var nsResolver = xpe.createNSResolver(aNode.ownerDocument == null ? aNode.documentElement : aNode.ownerDocument.documentElement); var result = xpe.evaluate(aExpr, aNode, nsResolver, 0, null); var found = []; var res; while (res = result.iterateNext()) found.push(res); return found; } This function uses the new XPathEvaluator() constructor, which is supported in Firefox, Chrome, Opera and Safari, but not in Edge or Internet Explorer. ...
...ode.documentElement : aNode.ownerDocument.documentElement); var result = xpe.evaluate(aExpr, aNode, nsResolver, 0, null); var found = []; var res; while (res = result.iterateNext()) found.push(res); return found; } This function uses the new XPathEvaluator() constructor, which is supported in Firefox, Chrome, Opera and Safari, but not in Edge or Internet Explorer. ...
...And 15 more matches
dev/panel - Archive of obsolete content
}); In the constructor definition there are a number of mandatory and optional parameters for you to supply. Name Type Description lab...
...options object containing a single property debuggee. debuggee is a MessagePort object that you can use to exchange messages with the debugger server. Optional dispose Function A function that will be called when the panel is about to be destroyed. You can use it to do any cleanup. Optional onReady Function An event handler that will be called when the document in the panel becomes interactive. It's equivalent to document.readyState === "interactive". At this point you can send the panel document messages. Optional onLoad Function An event handler that will be called after the document in the panel is fully loaded. It's equivalent to document.readyState === "complete". Optional Once you've defined the panel's constructor you ...
...el, label: "My Panel", tooltip: "My new devtool's panel", icon: "./my-icon.png", url: "./my-panel.html", // when the panel is created, // take a reference to the debuggee setup: function(options) { this.debuggee = options.debuggee; }, dispose: function() { this.debuggee = null; }, onReady: function() { // in this function you can communicate // with the panel document } }); // export the constructor exports.MyPanel = MyPanel; // create a new tool, initialized // with the new constructor const myTool = new Tool({ panels: { myPanel: MyPanel } }); Panel document environment The panel document loaded from the url property can of course include CSS and JavaScript just like a normal web page: <html> <head> <meta charset="utf-8"> <link href="./my-p...
...And 14 more matches
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
turn { namespace: jsonToDOM.namespaces[reElemNameParts[1]], shortName: reElemNameParts[2] }; } // Note that 'elemNameOrArray' is: either the full element name (eg. [html:]div) or an array of elements in JSON notation function tag(elemNameOrArray, elemAttr) { // Array of elements? Parse each one... ...
...em)); } }); return elem; } return tag.apply(null, jsonTemplate); } In the above, the namespaces object defines the namespace prefixes which can be used in the given DOM tree. ...
... } }); return elem; } return tag.apply(null, jsonTemplate); } In the above, the namespaces object defines the namespace prefixes which can be used in the given DOM tree. ...
...And 14 more matches
Common causes of memory leaks in extensions - Extensions
appropriately in certain circumstances, such as when a window is closed, a page unloads, or an extension is disabled or removed. While bug 695480 should prevent most of these compartment leaks, add-ons still need to be aware of the practices that caused these leaks, as the fix causes many add-ons which would have otherwise caused a leak to instead throw errors when attempting to access nodes from documents which no longer exist. Storing references to window objects and DOM nodes The most common problem is extensions holding onto references to content windows for too long. For example, in XUL overlay code: var contentWindows = []; function inBrowserXulOverlay(contentWindow) { // forgetting or failing to pop the content window thing again contentWindows.push(contentWindow); } This will kee...
...pop the content window thing again contentWindows.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 inJavascriptCodeModule(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(...
...ction inJavascriptCodeModule(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. ...
...And 14 more matches
Using files from web applications - Web APIs
or details. Accessing selected file(s) Consider this HTML: <input type="file" id="input" multiple> The File API makes it possible to access a FileList containing File objects representing the files selected by the user. The multiple attribute on the input element allows the user to select multiple files. ...
...t multiple files. Accessing the first selected file using a classical DOM selector: const selectedFile = document.getElementById('input').files[0]; Accessing selected file(s) on a change event It is also possible (but not mandatory) to access the FileList through the change event. You need to use EventTarget.addEventListener() to add the change event listener, like this: const inputElement = document.getElementById("input"); inputElement.addEventListener("change", handleFiles, false); function handleFiles() { const fileList = this.files; /* now you can work with the file list */ } Getting information about selected file(s) The FileList object provided by the DOM lists all of the files selected by the user, each specified as a File object. You can determine how many files the user selected...
... } let sOutput = nBytes + " bytes"; // optional code for multiples approximation const aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]; for (nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) { sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple] + " (" + nBytes + " bytes)"; } // end of optional code document.getElementById("fileNum").innerHTML = nFiles; document.getElementById("fileSize").innerHTML = sOutput; } document.getElementById("uploadInput").addEventListener("change", updateSize, false); </script> </body> </html> Using hidden file input elements using the click() method You can hide the admittedly ugly file <input> element and present your own interface for opening the file pick...
...And 14 more matches
The HTML DOM API - Web APIs
the browser navigation history Supporting and connective interfaces for other APIs such as Web Components, Web Storage, Web Workers, WebSocket, and Server-sent events. HTML DOM concepts and usage In this article, we'll focus on the parts of the HTML DOM that involve engaging with HTML elements. Discussion of other areas, such as Drag and Drop, WebSockets, Web Storage, etc. ...
...ctive interfaces for other APIs such as Web Components, Web Storage, Web Workers, WebSocket, and Server-sent events. HTML DOM concepts and usage In this article, we'll focus on the parts of the HTML DOM that involve engaging with HTML elements. Discussion of other areas, such as Drag and Drop, WebSockets, Web Storage, etc. can be found in the documentation for those APIs. Structure of an HTML document The Document Object Model (DOM) is an architecture that describes the structure of a document; each document is represented by an instance of the interface Document. A document, in turn, consists of a hierarchical tree of nodes, in which a node is a fundamental record representing a single object within the document (such as an element or text node). Nodes may be strictly organizational, provid...
...They're empty vessels. ...
...And 14 more matches
Rich-Text Editing in Mozilla - Developer guides
Note: This document is out-of-date; you are advised to consult the more up-to-date document available at Making content editable. Mozilla 1.3 introduces an implementation of Microsoft(R) Internet Explorer's designMode feature. The rich-text editing support in Mozilla 1.3 supports the designMode feature which turns HTML documents into rich-text editors. Starting in Firefox 3, Mozilla also supports Internet Explorer's contentEditable attribute which allows any element to become editable or non-editable (the latter for when preventing change to fixed elements in an editable environment). Setting Up Rich-Text Editing Rich-text editing is initialized by setting the designMode property of a document to "On", such as the document inside an iframe. Once designMode has been set to "On", the do...
... to "On", such as the document inside an iframe. Once designMode has been set to "On", the document becomes a rich-text editing area and the user can type into it as if it were a textarea. The most basic keyboard commands such as copy and paste are available, all others need to be implemented by the website. Similarly, setting contentEditable to "true" allows you to make individual elements of a document editable. Executing Commands When an HTML document has been switched to designMode, the document object exposes the document.execCommand method which allows one to run commands to manipulate the contents of the editable region. Most commands affect the document's selection (bold, italics, etc), while others insert new elements (adding a link) or affect an entire line (indenting). When using con...
...The styleWithCSS command can be used to toggle between CSS and HTML markup creation. ...
...And 14 more matches
Forms related code snippets - Archive of obsolete content
"> /*\ |*| |*| 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. ...
...veloper 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. ...
...zilla.org/docs/Code_snippets/Forms |*| https://developer.mozilla.org/User:fusionchess |*| |*| This snippet is released under the GNU Public License, version 3 or later. ...
...And 13 more matches
Layout System Overview - Archive of obsolete content
These layout modes are referred to as 'Standards' and 'NavQuirks' modes. ...
...These layout modes are referred to as 'Standards' and 'NavQuirks' modes. (DOCTYPE and modes are explained in more detail in article Mozilla's DOCTYPE sniffing. Galley and Page Presentations: The presentation generally is constrained by the width of the window in which the presentation is to be displayed, and a height that extends as far as necessary. ...
...This paged presentation presents several challenges not present in the galley presentation, namely how to break up elements that are larger than a single page, and how to handle changes to page dimensions. The original design of the Layout system allowed for multiple, possibly different, presentations to be supported simultaneously from the same content model. In other words, the same HTML or XML document could be viewed as a normal galley presentation in a browser window, while simultaneously being presented in a paged presentation to a printer, or even an aural presentation to a speech-synthesizer. To date the only real use of this multiple presentation ability is seen in printing, where multiple presentations are managed, all connected to the same content model. (note: it is unclear if this is ...
...And 13 more matches
Using the Editor from XUL - Archive of obsolete content
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. ...
...Script function to get executed when the XUL is done loading. 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. that which you get from window._content. Having an id attribute, id="content-frame", allows us to find this element with document.getElementById("content-frame"), and to style it from CSS. EditorOnLoad() is called. It does some getting of window.arguments (which is a way callers can pass parameters to new windows -- we use this to get the URL to be loaded), then it calls EditorStartup(), where the real work happens. It passes two parameters; the first indicates whether we want a plain text or HTML editor (pass text...
... window.arguments (which is a way callers can pass parameters to new windows -- we use this to get the URL to be loaded), then it calls EditorStartup(), where the real work happens. It passes two parameters; the first indicates whether we want a plain text or HTML editor (pass text or html here), and the second is the <iframe> element on which we wish to create the editor. We could either pass document.getElementById("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 g...
...And 13 more matches
Getting started with CSS - Learn web development
You can copy the code from below if you want to work on your own computer. Save the code below as index.html in a folder on your machine. ...
...You can copy the code from below if you want to work on your own computer. Save the code below as index.html in a folder on your machine. ...
...You can copy the code from below if you want to work on your own computer. Save the code below as index.html in a folder on your machine. ...
...And 13 more matches
Introduction to events - Learn web development
aken (that is, some code running) when the event occurs. For example, in an airport, when the runway is clear for take off, a signal is communicated to the pilot. As a result, the plane can safely takeoff. In the case of the Web, events are fired inside the browser window, and tend to be attached to a specific item that resides in it -- this might be a single element, set of elements, the HTML document loaded in the current tab, or the entire browser window. There are many different types of events that can occur. For example: The user selects a certain element or hovers the cursor over a certain element. The user chooses 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 err...
... 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>Change color</button> button { margin: 10px }; The JavaScript looks like so: const btn = document.querySelector('button'); function random(number) { return Math.floor(Math.random() * (number+1)); } btn.onclick = function() { const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundColor = rndCol; } In this code, we store a reference to the button inside a constant called btn, using the Document.querySelector() function. We also ...
...g web events There are a number of ways to add event listener code to web pages so it runs when the associated event fires. In this section, we review the various mechanisms and discuss which ones you should use. Event handler properties These are the properties that exist to contain event handler code we have seen most frequently during the course. Returning to the above example: const btn = document.querySelector('button'); btn.onclick = function() { const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundColor = rndCol; } The onclick property is the event handler property being used in this situation. It is essentially a property like any other available on the button (e.g. btn.textContent, or btn.style), but it is a special typ...
...And 13 more matches
Performance best practices for Firefox front-end engineers
when we have a free second where presumably the user isn't doing something. See also the blog post Collective scheduling with requestIdleCallback. As of bug 1353206, you can also schedule idle events in non-DOM contexts by using Services.tm.idleDispatchToMainThread. See the nsIThreadManager.idl file for more details. Hide your panels If you're adding a new XUL <xul:popup> or <xul:panel> to a document, set the hidden attribute to true by default. By doing so, you cause the binding applied on demand rather than at load time, which makes initial construction of the XUL document faster. Get familiar with the pipeline that gets pixels to the screen Learn how pixels you draw make their way to the screen. Knowing the path they will take through the various layers of the browser engine will help yo...
...lations into a single batch so it all happens once, in a single frame tick, instead of across multiple frames. See Detecting and avoiding synchronous reflow below for more information. This also means that requestAnimationFrame() is 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...
...hich 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). It is expected that over time, script will update the DOM, requiring us to recalculate styles. Normally, the changes to the DOM just result in the standard style calculation occurring immediately after the JavaScript has finished running during the 16ms...
...And 13 more matches
Index
specific properties, advantages and disadvantages, which is why all of them are still being used (nobody has yet dared to replace the older with the newer ones because of risks for side effects). When using the ASN.1 parser(s), a template definition is passed to the parser, which will analyze the ASN.1 data stream accordingly. The templates are usually closely aligned to definitions found in RFC documents. A data block described as DER is usually in ASN.1 format. You must know which data you are expecting, and use the correct template for parsing, based on the context of your software's interaction. Data described as PEM is a base64 encoded presentation of DER, usually wrapped between human readable BEGIN/END lines. NSS prefers the binary presentation, but is often capable to use base64 or ASC...
... has multiple implementations for the same or similar concepts. For example, there are multiple presentations of certificates, and the NSS internals (and sometimes even the application using NSS) might have to convert between them. Key responsibilites of NSS are verification of signatures and certificates. In order to verify a digital signature, we have to look at the application data (e.g., a document that was signed), the signature data block (the digital signature), and a public key (as found in a certificate that is believed to be the signer, e.g., identified by metadata received together with the signature). The signature is verified if it can be shown that the signature data block must have been produced by the owner of the public key (because only that owner has the associated private ke...
...ioning the Extended Validation (EV) principle, which is an effort by software vendors and CAs to define a stricter set of rules for issuing certificates for web site certificates. Instead of simply verifying that the requester of a certificate is in control of an administrative email address at the desired web site's domain, it's required that the CA performs a verification of real world identity documents (such as a company registration document with the country's authority), and it's also required that a browser software performs a revocation check with the CA, prior to granting validity to the certificate. In order to distinguish an EV certificate, CAs will embed a policy OID in the certificate, and the browser is expected to verify that a trust chain permits the end entity (EE) certificate to ...
...And 13 more matches
nsIHTMLEditor
id increaseFontSize(); void indent(in AString aIndent); void insertElementAtSelection(in nsIDOMElement aElement, in boolean aDeleteSelection); void insertFromDrop(in nsIDOMEvent aEvent); void insertHTML(in AString aInputString); void insertHTMLWithContext(in AString aInputString, in AString aContextStr, in AString aInfoStr, in AString aFlavor, in nsIDOMDocument aSourceDoc, in nsIDOMNode aDestinationNode, in long aDestinationOffset, in boolean aDeleteSelection); void insertLinkAroundSelection(in nsIDOMElement aAnchorElement); boolean isAnonymousElement(in nsIDOMElement aElement); void makeOrChangeList(in AString aListType, in boolean entireList, in AString aBulletType); boolean nodeIsBlock(in nsIDOMNode node); ...
...t, in boolean aDeleteSelection); void insertLinkAroundSelection(in nsIDOMElement aAnchorElement); boolean isAnonymousElement(in nsIDOMElement aElement); void makeOrChangeList(in AString aListType, in boolean entireList, in AString aBulletType); boolean nodeIsBlock(in nsIDOMNode node); void pasteNoFormatting(in long aSelectionType); void rebuildDocumentFromSource(in AString aSourceString); void removeAllDefaultProperties(); void removeAllInlineProperties(); void removeDefaultProperty(in nsIAtom aProperty, in AString aAttribute, in AString aValue); void removeInlineProperty(in nsIAtom aProperty, in AString aAttribute); void removeInsertionListener(in nsIContentFilter inFilter); void removeList...
...entsWithHTML(in AString aSourceToInsert); void selectElement(in nsIDOMElement aElement); void setBackgroundColor(in AString aColor); void setBodyAttribute(in AString aAttr, in AString aValue); void setCaretAfterElement(in nsIDOMElement aElement); void setCSSInlineProperty(in nsIAtom aProperty, in AString aAttribute, in AString aValue); void setDocumentTitle(in AString aTitle); void setInlineProperty(in nsIAtom aProperty, in AString aAttribute, in AString aValue); void setParagraphFormat(in AString aParagraphFormat); void updateBaseURL(); Attributes Attribute Type Description isCSSEnabled boolean A boolean which is true is the HTMLEditor has been instantiated with CSS knowledge and...
...And 13 more matches
AbstractRange - Web APIs
As an abstract interface, you will not directly instantiate an object of type AbstractRange. Instead, you will use the Range or StaticRange interfaces. To understand the difference between those two interfaces, and how to choose which is appropriate for your needs. ...
...located. startOffset Read only An integer value indicating the offset, in characters, from the beginning of the node's contents to the last character of the contents referred to by the range object. This value must be less than the length of the node indicated in startContainer. Methods The AbstractRange interface offers no methods. Usage notes Range types All ranges of content within a document are described using instances of interfaces based on AbstractRange. There are two such interfaces: Range The Range interface has been around for a long time and has only recently been redefined to be based upon AbstractRange as the need arose to define other forms of range data. Range provides methods that allow you to alter the range's endpoints, as well as methods to compare ranges, detect ...
...hat will only be used once, since it avoids the performance and resource impact of the more complex Range interface. Contents of elements When trying to access the contents of an element, keep in mind that the element itself is a node, but so is any text inside it. ...
...And 13 more matches
EventTarget.addEventListener() - Web APIs
addEventListener() works by adding a function or an object that implements EventListener to the list of event listeners for the specified event type on the EventTarget on which it's called. ...
...e 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. HTML <table id="outside"> <tr><td id="t1">one</td></tr> <tr><td id="t2">two</td></tr> </table> JavaScript // Function to change the content of t2 function modifyText() { const t2 = document.getElementById("t2"); if (t2.firstChild.nodeValue == "three") { t2.firstChild.nodeValue = "two"; } else { t2.firstChild.nodeValue = "three"; } } // Add event listener to table const el = document.getElementById("outside"); el.addEventListener("click", modifyText, false); In this code, modifyText() is a listener for click events registered using addEventListener(). A click anywher...
...bles up to the handler and runs modifyText(). Result Event listener with anonymous function Here, we'll take a look at how to use an anonymous function to pass parameters into the event listener. ...
...And 13 more matches
Window - Web APIs
Web › API › Window
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 ...
...DE4" stroke-width="2px" /><text x="38.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Window</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Constructors See also the DOM Interfaces. DOMParser DOMParser can parse XML or HTML source stored in a string into a DOM Document. DOMParser is specified in DOM Parsing and Serialization. Image Used for creating an HTMLImageElement. Option Used for creating an HTMLOptionElement. StaticRange Read only Returns a StaticRange() constructor which creates a StaticRange object. Worker Used for creating a Web worker. XMLSerializer Converts a DOM tree into XML or HTML source. Properties This interface inherits proper...
...stomElements Read only Returns a reference to the CustomElementRegistry object, which can be used to register new custom elements and get information about previously registered custom elements. Window.crypto Read only Returns the browser crypto object. Window.devicePixelRatio Read only Returns the ratio between physical pixels and device independent pixels in the current display. Window.document Read only Returns a reference to the document that the window contains. Window.DOMMatrix Read only Returns a reference to a DOMMatrix object, which represents 4x4 matrices, suitable for 2D and 3D operations. Window.DOMMatrixReadOnly Read only Returns a reference to a DOMMatrixReadOnly object, which represents 4x4 matrices, suitable for 2D and 3D operations. Window.DOMPoint Read only ...
...And 13 more matches
Feature-Policy - HTTP
This header is still in an experimental state, and is subject to change at any time. Be wary of this when implementing it on your website. The header has now been renamed to Permissions-Policy in the spec, and this article will eventually be updated to reflect that change. For more information, see the main Feature Policy article. ...
...se header Forbidden header name yes Syntax Feature-Policy: <directive> <allowlist> <directive> The Feature Policy directive to apply the allowlist to. See Directives below for a list of the permitted directive names. <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': T...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. ...
...And 13 more matches
Index - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Index
2 Common XSLT Errors XSLT 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. 3 Index Index, Reference, XSLT Found 54 pages: 4 PI Parameters ...
... 7 Basic Example XSLT The basic example will load 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 w...
...data, it can load quickly even on dialup. 10 JavaScript/XSLT Bindings DOM, JavaScript, XML, XSLT JavaScript can run XSLT transformations through the XSLTProcessor object. Once instantiated, an XSLTProcessor has an XSLTProcessor.importStylesheet() method that takes as an argument the XSLT stylesheet to be used in the transformation. The stylesheet has to be passed in as an XML document, which means that the .xsl file has to be loaded by the page before calling XSLTProcessor.importStylesheet(). This can be done via XMLHttpRequest or XMLDocument.load(). 11 Resources XSLT No summary! 12 Setting Parameters XSLT While running transformations using precoded .xsl and .xml files is quite useful, configuring the .xsl file from JavaScript may be ...
...And 13 more matches
Useful string methods - Learn web development
seful to test whether the method call isn't equal to a certain result. ...
...y Christmas my love', 'A happy Christmas to all the family', 'You\'re all I want for Christmas', 'Get well soon']; for (let i = 0; i < greetings.length; i++) { let input = greetings[i]; // Your conditional test needs to go inside the parentheses // in the line below, replacing what's currently there if (greetings[i]) { let listItem = document.createElement('li'); listItem.textContent = input; list.appendChild(listItem); } } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98...
...hild(listItem); } } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solutio...
...And 12 more matches
What is JavaScript? - Learn web development
JavaScript can do a lot more than that -- let's explore w...
...k out the design yourself, go and find the correct wood, cut all the panels to the right size and shape, find the correct-sized screws, and then put them together to make a bookshelf. They generally fall into two categories. Browser APIs are built into your web browser, and are able to expose data from the surrounding computer environment, or do useful complex things. For example: The DOM (Document Object Model) API allows you to manipulate HTML and CSS, creating, removing and changing HTML, dynamically applying new styles to your page, etc. Every time you see a popup window appear on a page, or some new content displayed (as we saw above in our simple demo) for example, that's the DOM in action. The Geolocation API retrieves geographical information. This is how Google Maps is able to fin...
...ed about in our How CSS works article). When you load a web page in your browser, you are running your code (the HTML, CSS, and JavaScript) inside an execution environment (the browser tab). This is like a factory that takes in raw materials (the code) and outputs a product (the web page). A very common use of JavaScript is to dynamically modify HTML and CSS to update a user interface, via the Document Object Model API (as mentioned above). Note that the code in your web documents is generally loaded and executed in the order it appears on the page. If the JavaScript loads and tries to run before the HTML and CSS it is affecting has been loaded, errors can occur. You will learn ways around this later in the article, in the Script loading strategies section. Browser security Each browser tab h...
...And 12 more matches
HTML parser threading
HTML Parser Threading The HTML parser parses data received from the network off the main thread. (There's currently one parser thread serving all parser instances.) Data received from document.write() is parsed on the main thread. Main Objects nsHtml5Parser contains the code for dealing with data from document.write(). (For historical reasons, it also contains unrelated fragment parsing code that should be refactored into a separate class in due course.) nsHtml5StreamParser contains the code for dealing with data from the network. nsHtml5Parser owns nsHtml5StreamParser. Script-created parsers (i.e. parsers created using document.open()) don't have an nsHtml5StreamParser instance. nsHtml5Parser has one tokenizer/tree builder pair for parsing data from document.write(). It also has another l...
...nsHtml5StreamParser has one tokenizer/tree builder pair for parsing data from the network. ...
...nsHtml5StreamParser has one tokenizer/tree builder pair for parsing data from the network. Additionally, each nsHtml5Parser has an associated nsHtml5TreeOpExecutor that turns the output (tree operations; discussed later) of the portable parser core into actions performed on the Gecko DOM. ...
...And 12 more matches
DOMParser - Web APIs
Web › API › DOMParser
You can perform the opposite operation--converting a DOM tree into XML or HTML source--using the XMLSerializer interface. In the case of an HTML document, you can also replace portions of the DOM with new DOM trees built from HTML by setting the value of the Element.innerHTML and outerHTML properties. These properties can also be read to fetch HTML fragments corresponding to the corresponding DOM subtree. ...
... replace portions of the DOM with new DOM trees built from HTML by setting the value of the Element.innerHTML and outerHTML properties. These properties can also be read to fetch HTML fragments corresponding to the corresponding DOM subtree. Syntax let domparser = new DOMParser() Methods DOMParser.parseFromString() Syntax let doc = domparser.parseFromString(string, mimeType) Return Either Document or XMLDocument depending on the mimeType argument. Parameters This method has 2 parameters (both required): string The DOMString to be parsed. It must contain either HTML, xml, xhtml+xml, or svg document. mimeType A DOMString. This string determines a class of the the method's return value. The possible values are the following: mimeType doc.constructor ...
...epending on the mimeType argument. Parameters This method has 2 parameters (both required): string The DOMString to be parsed. It must contain either HTML, xml, xhtml+xml, or svg document. mimeType A DOMString. This string determines a class of the the method's return value. ...
...And 12 more matches
Guide to the Fullscreen API - Web APIs
that you'd like to present in full-screen mode (such as a <video>, for example), you can present it in full-screen mode by simply calling its requestFullscreen() method. Let's consider this <video> element: <video controls id="myvideo"> <source src="somevideo.webm"></source> <source src="somevideo.mp4"></source> </video> We can put that video into full-screen mode as follows: var elem = document.getElementById("myvideo"); if (elem.requestFullscreen) { elem.requestFullscreen(); } This code checks for the existence of the requestFullscreen() method before calling it. Presentation differences It's worth noting a key difference here between the Gecko and WebKit implementations at this time: Gecko automatically adds CSS rules to the element to stretch it to fill the screen: "width: 100%;...
... #myvideo:-webkit-full-screen { width: 100%; height: 100%; } On the other hand, if you're trying to emulate WebKit's behavior on Gecko, you need to place the element you want to present inside another element, which you'll make fullscreen instead, and use CSS rules to adjust the inner element to match the appearance you want. Notification When fullscreen mode is successfully engaged, the document which contains the element receives a fullscreenchange event. When fullscreen mode is exited, the document again receives a fullscreenchange event. Note that the fullscreenchange event doesn't provide any information itself as to whether the document is entering or exiting fullscreen mode, but if the document has a non null fullscreenElement, you know you're in fullscreen mode. When a fullscree...
...quest failed. In Chrome and newer versions of Opera however, no such warning is generated. Note: Fullscreen requests need to be called from within an event handler or otherwise they will be denied. Getting out of full screen mode The user always has the ability to exit fullscreen mode of their own accord; see Things your users want to know. You can also do so programmatically by calling the Document.exitFullscreen() method. Other information The Document provides some additional information that can be useful when developing fullscreen web applications: DocumentOrShadowRoot.fullscreenElement The fullscreenElement property tells you the Element that's currently being displayed fullscreen. If this is non-null, the document is in fullscreen mode. If this is null, the document is not in fu...
...And 12 more matches
Using CSS transitions - CSS: Cascading Style Sheets
ight background-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 0.5s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transformv color; transition-duration: 0.5s; transition-timing-function: ease-in-out; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-duration: 1s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; ...
...th height background-color font-size left top -webkit-transform transform color; -webkit-transition-duration: 1s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 1s; transition-timing-function: ease-in-out; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-duration: 2s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; ...
...th height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 2s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 2s; transition-timing-function: ease-in-out; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-duration: 4s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; ...
...And 12 more matches
Index - HTTP
Web › HTTP › Headers › Index
P, HTTP, Reference, Security, header The HTTP Content-Security-Policy response header allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. This helps guard against cross-site scripting attacks (XSS). 29 CSP: base-uri CSP, Directive, Document directive, HTTP, Security The HTTP Content-Security-Policy base-uri directive restricts the URLs which can be used in a document's <base> element. If this value is absent, then any URI is allowed. If this directive is absent, the user agent will use the value in the <base> element. 30 CSP: block-all-mixed-content CSP, Directive, HTTP, Mixed Content, Reference, Security ...
...t-src CSP, Directive, HTTP, Reference, Security The HTTP Content-Security-Policy object-src directive specifies valid sources for the <object>, <embed>, and <applet> elements. 42 CSP: plugin-types CSP, Directive, Flash, HTTP, Java, Plugins, Security The HTTP Content-Security-Policy (CSP) plugin-types directive restricts the set of plugins that can be embedded into a document by limiting the types of resources which can be loaded. 43 CSP: referrer CSP, Directive, HTTP, Reference, Security The HTTP Content-Security-Policy (CSP) referrer directive used to specify information in the Referer header (with a single r as this was a typo in the original spec) for links away from a page. This API is deprecated and removed from browsers. 44 CSP: ...
...e r as this was a typo in the original spec) for links away from a page. This API is deprecated and removed from browsers. 44 CSP: report-uri CSP, Directive, HTTP, Reference, Security The deprecated HTTP Content-Security-Policy (CSP) report-uri directive instructs the user agent to report attempts to violate the Content Security Policy. These violation reports consist of JSON documents sent via an HTTP POST request to the specified URI. 45 CSP: require-sri-for CSP, Directive, HTTP, Reference, Security The HTTP Content-Security-Policy require-sri-for directive instructs the client to require the use of Subresource Integrity for scripts or styles on the page. 46 CSP: sandbox CSP, Directive, HTTP, Security The HTTP Content-Security-Policy...
...And 12 more matches
Connecting to Remote Content - Archive of obsolete content
ttpRequest()) because this way works both in chrome and non-chrome code. Following initialization, onload and onerror handlers are registered to a callback function to handle the response returned from the remote server. In both cases aEvent.target is an nsIXMLHttpRequest. In the onload callback function, the responseText parameter contains the server response as text. If the response is an XML document, the responseXML property will hold an XMLDocument object that can be manipulated using DOM methods. Sometimes the server doesn't specify an XML Content-Type header, which is necessary for the XML parsing to happen automatically. You can use overrideMimeType to force the response to be parsed as XML. request.overrideMimeType("text/xml"); // do this before sending the request! The open method t...
...content XML is possibly the most popular data interchange format. ...
...shop> <name>Orange</name> </shop> </shops> <total>2</total> </data> When a valid XML response comes back from the remote server, the XML document object can be manipulated using different DOM methods, to display the data in the UI or store it into a local datasource. ...
...And 11 more matches
Dynamically modifying XUL-based user interface - Archive of obsolete content
This article discusses manipulating 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. You may also want to read some introductory documents about DOM, like the About the Document Object Model article or the Introduction page of the Gecko DOM Reference. Introduction As you know, XUL is an XML language used in various Mozilla-based applications, such as Firefox and Thunderbird, to describe the user interface. In XUL applications JavaScript d...
... want to read some introductory documents about DOM, like the About the Document Object Model article or the Introduction page of the Gecko DOM Reference. Introduction As you know, XUL is an XML language used in various Mozilla-based applications, such as Firefox and Thunderbird, to describe the user interface. In XUL applications JavaScript defines the behavior, using DOM APIs to access the XUL document. 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. The most well known DOM method is probably document.getElementById(), which returns an element, given its id. You may also have used other calls, such as el...
...L (or HTML) document, you have already used DOM calls. The most well known DOM method is probably document.getElementById(), which returns an element, given its id. You may also have used other calls, such as element.setAttribute(), or, if you wrote an extension, the addEventListener() method. All of these are defined in DOM. There are also DOM methods that create, move, or delete elements from a document. They will be demonstrated in a later section. Right now, let's learn what a document is. What is a document? A document is a data structure which is manipulated through DOM APIs. A logical structure of every document is a tree, with nodes being elements, attributes, processing instructions, comments, etc. Use the DOM Inspector tool to see the tree representation of any document. Todo: simple e...
...And 11 more matches
Windows Media in Netscape - Archive of obsolete content
tscape 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 Player directly as an ActiveX control within Netscape 7.1. This section presents t...
... Both ActiveXObject and GeckoActiveXObject can take WMPlayer.OCX.7 as an argument to create the control if Windows Media Player 7 or 9 are present. Unlike using the ProgID as an argument, using WMPlayer.OCX.7 as an argument to both these APIs creates a fully usable reference to the Windows Media Player 7 or 9 cont...
... be passed in curly braces "{}". The name GeckoActiveXObject rather than ActiveXObject was introduced for two reasons: GeckoActiveXObject is limited to creating instances of Windows Media Player ActiveX controls. It therefore can not be used everywhere ActiveXObject is used. ActiveXObject is used by many web developers to detect the presence of Internet Explorer in much the same fashion as document.all is used. For example if (window.ActiveXObject) { // Internet Explorer only script } Server-side Detection Using User-agent Strings Netscape 7.1's user agent string on Windows has the general pattern: Mozilla/5.0 (Windows; U; <em>operating system version</em>; <em>language</em>; rv:1.4) Gecko/20030624 Netscape/7.1 (ax<em>[;optional comments]</em>) The "Vendor Comment" (ax) following the...
...And 11 more matches
What’s in the head? Metadata in HTML - Learn web development
Previous Overview: Introduction to HTML Next The head of an HTML document is the part that is not displayed in the web browser when the page is loaded. It contains information such as the page <title>, links to CSS (if you choose to style your HTML content with CSS), links to custom favicons, and other metadata (data about the HTML, such as the author, and important keywords that describe the document.) In this article we'll cover all of the above and more, in order to give you a good basis for working with markup. Prerequisites: Basic HTML familiarity, as covered in Getting started with HTML. Objective: To learn about the HTML head, its purpose, the most important items it can contain, and what effect it can have on the HTML document. What is the HTML hea...
...er all of the above and more, in order to give you a good basis for working with markup. Prerequisites: Basic HTML familiarity, as covered in Getting started with HTML. Objective: To learn about the HTML head, its purpose, the most important items it can contain, and what effect it can have on the HTML document. What is the HTML head? Let's revisit the simple HTML document we covered in the previous article: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My test page</title> </head> <body> <p>This is my page</p> </body> </html> The HTML head is the contents of the <head> element -- unlike the contents of the <body> element (which are displayed on the page when loaded in a browser), the head's content is not displayed on the page. ...
...ml> <head> <meta charset="utf-8"> <title>My test page</title> </head> <body> <p>This is my page</p> </body> </html> The HTML head is the contents of the <head> element -- unlike the contents of the <body> element (which are displayed on the page when loaded in a browser), the head's content is not displayed on the page. Instead, the head's job is to contain metadata about the document. In the above example, the head is quite small: <head> <meta charset="utf-8"> <title>My test page</title> </head> In larger pages however, the head can get quite full. Try going to some of your favorite websites and use the developer tools to check out their head contents. Our aim here is not to show you how to use everything that can possibly be put in the head, but rather to teach you how...
...And 11 more matches
Looping code - Learn web development
itle> <style> html { width: 100%; height: inherit; background: #ddd; } canvas { display: block; } body { margin: 0; } button { position: absolute; top: 5px; left: 5px; } </style> </head> <body> <button>Update</button> <canvas></canvas> <script> const btn = document.querySelector('button'); const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); let WIDTH = document.documentElement.clientWidth; let HEIGHT = document.documentElement.clientHeight; canvas.width = WIDTH; canvas.height = HEIGHT; function random(number) { return Math.floor(Math.random()*number); } function draw() { c...
...s decrement) the counter variable, to bring it closer to the point where the condition is no longer true. Some curly braces that contain a block of code -- this code will be run each time the loop iterates. Let's look at a real example so we can visualize what these do more clearly. ...
... 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: ...
...And 11 more matches
Making decisions in your code — conditionals - Learn web development
Wear shorts! Go to the beach, or the park, and get an ice cream.'; } else if (choice === 'rainy') { para.textContent = 'Rain is falli...
...Wear shorts! Go to the beach, or the park, and get an ice cream.'; } else if (choice === 'rainy') { para.textContent = 'Rain is falling outside; take a rain coat and an umbrella, a...
...Wear shorts! Go to the beach, or the park, and get an ice cream.'; break; case 'rainy': para.textContent = 'Ra...
...And 11 more matches
Drawing graphics - Learn web development
to select if we have multiple canvases on the page, but we have removed the width and height attributes for now (you could add them back in if you wanted, but we will set them using JavaScript in a below section). Canvases with no explicit width and height default to 300 pixels wide by 150 pixels high. Now add the following lines of JavaScript inside the <script> element: const canvas = document.querySelector('.myCanvas'); const width = canvas.width = window.innerWidth; const height = canvas.height = window.innerHeight; Here we have stored a reference to the canvas in the canvas constant. In the second line we set both a new constant width and the canvas' width property equal to Window.innerWidth (which gives us the viewport width). In the third line we set both a new constant height ...
... useful values to have available for later (for example, if you want to draw something exactly halfway across the width of the canvas). If you save and load your example in a browser now, you'll see nothing, which is fine, but you'll also see scrollbars -- this is a problem for us, which happens because the <body> element has a margin that, added to our full-window-size canvas, results in a document that's wider than the window. To get rid of the scrollbars, we need to remove the margin and also set overflow to hidden. Add the following into the <head> of your document: <style> body { margin: 0; overflow: hidden; } </style> The scrollbars should now be gone. Note: You should generally set the size of the image using HTML attributes or DOM properties, as explained above...
...g clicked or not with three variables: curX, curY, and pressed. When the mouse moves, we fire a function set as the onmousemove event handler, which captures the current X and Y values. We also use onmousedown and onmouseup event handlers to change the value of pressed to true when the mouse button is pressed, and back to false again when it is released. ...
...And 11 more matches
Accessibility API cross-reference
o to be nearly the same. However, only about one third of the states and roles in Sun's accessibility API's are the same as in MSAA. To do Fill out Mac API column.(Mac OS X - Carbon Accessibility API and Accessibility Constants) Finish ARIA column - add explanation of the term 'Abstract role' Fill out HTML column Create AOM column Fill out XUL column. ...
...ty Role ARIA (role=*) HTML Tagged PDF Relevant XUL For alerts, in Java/Gnome for any alert, in MSAA if no other role applies. ARIA live region. ALERT ALERT ALERT alert, alertdialog Content changes over time, such as animated gif ANIMATION n/a no spec n/a A section that forms an independent part of a document, page, or site. article <article> <Part> or <Art> Object representing entire app. ARIA role denotes interactive (not browsable) content operable in ways that differ from any of the other interactive ARIA roles, and may be only a part of the main document. APPLICATION FRAME n/a application See <Div> and <NonStruct> A region ...
...DER COLUMN_HEADER, TABLE_COLUMN_HEADER columnheader <th scope=col> Edit control with drop down list box, different from DROPLIST COMBOBOX COMBO_BOX COMBO_BOX combobox Abstract role - A form of widget that performs an action but does not receive input data. command A supporting section of the document, designed to be complementary to the main content at a similar level in the DOM hierarchy, but remains meaningful when separated from the main content. complementary <aside> n/a but <Div> or even <p> have been suggested for this purpose A widget that may contain navigable descendants or owned children. composite (abstract role) ...
...And 11 more matches
Using images - Web APIs
bs the current frame from the video and uses it as an image. HTMLCanvasElement You can use another <canvas> element as your image source. These sources are collectively referred to by the type CanvasImageSource. There are several ways to get images for use on a canvas. ...
...deo and uses it as an image. HTMLCanvasElement You can use another <canvas> element as your image source. These sources are collectively referred to by the type CanvasImageSource. There are several ways to get images for use on a canvas. ...
...These sources are collectively referred to by the type CanvasImageSource. There are several ways to get images for use on a canvas. Using images from the same page We can obtain a reference to images on the same page as the canvas by using one of: The document.images collection The document.getElementsByTagName() method If you know the ID of the specific image you wish to use, you can use document.getElementById() to retrieve that specific image Using images from other domains Using the crossorigin attribute of an <img> element (reflected by the HTMLImageElement.crossOrigin property), you can request permission to load an image from another domain for use in your call to drawImage(). If the hosting domain permits cross-domain access to the image, the image can be used in your canvas wit...
...And 11 more matches
Using the W3C DOM Level 1 Core - Web APIs
The W3C's DOM Level 1 Core is an API for manipulating the DOM trees of HTML and XML documents (among other tree-like types of documents). Due to the ubiquity of the DOM, this API is supported in all major browsers, including Mozilla Firefox and Microsoft Internet Explorer, and serves as a base for scripting on the web. What is a DOM tree? ...
... DOM Level 1 Core is an API for manipulating the DOM trees of HTML and XML documents (among other tree-like types of documents). Due to the ubiquity of the DOM, this API is supported in all major browsers, including Mozilla Firefox and Microsoft Internet Explorer, and serves as a base for scripting on the web. What is a DOM tree? ...
...lating the DOM trees of HTML and XML documents (among other tree-like types of documents). Due to the ubiquity of the DOM, this API is supported in all major browsers, including Mozilla Firefox and Microsoft Internet Explorer, and serves as a base for scripting on the web. What is a DOM tree? ...
...And 11 more matches
Intersection Observer API - Web APIs
Historically, detecting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish. As the web has matured, the need for this kind of information has grown. ...
...e target element and its root is the intersection ratio. This is a representation of the percentage of the target element which is visible as a value between 0.0 and 1.0. Creating an intersection observer Create the intersection observer by calling its constructor and passing it a callback function to be run whenever a threshold is crossed in one direction or the other: let options = { root: document.querySelector('#scrollArea'), rootMargin: '0px', threshold: 1.0 } let observer = new IntersectionObserver(callback, options); A threshold of 1.0 means that when 100% of the target is visible within the element specified by the root option, the callback is invoked. Intersection observer options The options object passed into the IntersectionObserver() constructor let you control the circu...
...ility passes another 25%, you would specify the array [0, 0.25, 0.5, 0.75, 1]. The default is 0 (meaning as soon as even one pixel is visible, the callback will be run). A value of 1.0 means that the threshold isn't considered passed until every pixel is visible. Targeting an element to be observed Once you have created the observer, you need to give it a target element to watch: let target = document.querySelector('#listItem'); observer.observe(target); // the callback we setup for the observer will be executed now for the first time // it waits until we assign a target to our observer (even if the target is currently not visible) Whenever the target meets a threshold specified for the IntersectionObserver, the callback is invoked. The callback receives a list of IntersectionObserverEntry ...
...And 11 more matches
Microdata DOM API - Web APIs
Microdata were implemented in some browsers for a long time. Nowadays, they have been abandoned and removed from all browsers and are therefore deprecated. You can't use them anymore and this document is kept as information only. Microdata becomes even more useful when scripts can use it to expose information to the user, for example offering it in a form that can be used by other applications. The document.getItems(typeNames) method provides access to the top-level microdata items. It returns a NodeList containing the items with the specified types, or all types if no argument is specified. Each item is represented in the DOM by the element on which the relevant itemscope attribute is found. These elements have their element.itemScope IDL attribute set to true. The type(s) of items can...
...ist containing the items with the specified types, or all types if no argument is specified. Each item is represented in the DOM by the element on which the relevant itemscope attribute is found. These elements have their element.itemScope IDL attribute set to true. The type(s) of items can be obtained using the element.itemType IDL attribute on the element with the itemscope attribute. ...
...nt is specified. Each item is represented in the DOM by the element on which the relevant itemscope attribute is found. These elements have their element.itemScope IDL attribute set to true. The type(s) of items can be obtained using the element.itemType IDL attribute on the element with the itemscope attribute. Methods document . getItems( [ types ] ) Returns a NodeList of the elements in the Document that create items, that are not part of other items, and that are of the types given in the argument, if any are listed. The types argument is interpreted as a space-separated list of types. The document.getItems(typeNames) method takes a string that contains an unordered set of unique space-separated tokens that are case-sensitive, representing types. When called, the method must return a live...
...And 11 more matches
Node - Web APIs
Web › API › Node
The DOM Node interface is an abstract base class upon which many other DOM API objects are based, thus letting those object types to be used similarly and often interchangeably. As an abstract class, there is no such thing as a plain Node object. All objects that implement Node functionality are based on one of its subclasses. Most notable are Document, Element, and DocumentFragment. In addition, every kind of DOM node is represented by an interface based on Node. These include Attr, CharacterData (which Text, Comment, and CDATASection are all based on), ProcessingInstruction, DocumentType, Notation, Entity, and EntityReference. In some cases, a particular feature of the base Node interface may not apply to one of its child interfaces; in that case, the inheriting node may return null or throw ...
...ze="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Node</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties In addition to the properties below, Node inherits properties from its parent, EventTarget. Node.baseURIRead only Returns a DOMString representing the base URL of the document containing the Node. Node.baseURIObject Read only (Not available to web content.) The nsIURI object representing the base URI for the element. Node.childNodesRead only Returns a live NodeList containing all the children of this node. NodeList being live means that if the children of the Node change, the NodeList object is automatically updated. Node.firstChildRead only Returns a Node r...
... this node. NodeList being live means that if the children of the Node change, the NodeList object is automatically updated. Node.firstChildRead only Returns a Node representing the first direct child node of the node, or null if the node has no child. Node.isConnectedRead only A boolean indicating whether or not the Node is connected (directly or indirectly) to the context object, e.g. the Document object in the case of the normal DOM, or the ShadowRoot in the case of a shadow DOM. Node.lastChildRead only Returns a Node representing the last direct child node of the node, or null if the node has no child. Node.nextSiblingRead only Returns a Node representing the next node in the tree, or null if there isn't such node. Node.nodeNameRead only Returns a DOMString containing the name o...
...And 11 more matches
Viewport concepts - CSS: Cascading Style Sheets
ins the concept of the viewport -- what it is, its impact in terms of CSS, SVG, and mobile devices -- and differentiates between the visual viewport and the layout viewport. What is a viewport? A viewport represents the area in computer graphics being currently viewed. In web browser terms, it is generally the same as the browser window, excluding the UI, menu bar, etc. That is, the part of the document you are viewing. Documents like this article may be very long. Your viewport is everything that is currently visible, notably, the "what is a viewport section", and perhaps some of the navigation menu. The size of the viewport depends on the size of the screen, whether the browser is in fullscreen mode or not, and whether or not the user zoomed in. Content outside the viewport, such as the See A...
...ocuments like this article may be very long. Your viewport is everything that is currently visible, notably, the "what is a viewport section", and perhaps some of the navigation menu. The size of the viewport depends on the size of the screen, whether the browser is in fullscreen mode or not, and whether or not the user zoomed in. Content outside the viewport, such as the See Also section in this document, is likely to not be visible onscreen until scrolled into view. On larger monitors where applications aren't necessarily full screen, the viewport is the size of the browser window. On most mobile devices and when the browser is in fullscreen mode, the viewport is the entire screen. In fullscreen mode, the viewport is the device screen, the window is the browser window, which can be as big a...
...een until scrolled into view. On larger monitors where applications aren't necessarily full screen, the viewport is the size of the browser window. On most mobile devices and when the browser is in fullscreen mode, the viewport is the entire screen. ...
...And 11 more matches
<input type="button"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › button
ectively). To make buttons do anything, you have to write JavaScript code to do the work. ...
... write JavaScript code to do the work. ...
...ld with any <input> for which it makes sense -- you use the accesskey global attribute. In this example, s is specified as the access key (you'll need to press s plus the particular modifier keys for your browser/OS combination; see accesskey for a useful list of those). ...
...And 11 more matches
Scripting - SVG: Scalable Vector Graphics
Web › SVG › Scripting
s to go back to the previous page. The evt.preventDefault() method lets you do this. Using eventListeners with objects The methods addEventListener() and removeEventListener() are very useful when writing interactive SVG. You can pass an object that implements the handleEvent interface as the second parameter to these methods. ...
...You can pass an object that implements the handleEvent interface as the second parameter to these methods. ...
...ass an object that implements the handleEvent interface as the second parameter to these methods. ...
...And 11 more matches
Using custom elements - Web Components
n an HTML page, rather than having to make do with a long, nested batch of elements that together provide a custom page feature. This article introduces the use of the Custom Elements API. Note: Custom elements are supported by default in Firefox, Chrome, and Edge (76). Opera and Safari so far support only autonomous custom elements. High-level view The controller of custom elements on a web document is the CustomElementRegistry object -- this object allows you to register a custom element on the page, return information on what custom elements are registered, etc. To register a custom element on the page, you use the CustomElementRegistry.define() method. This takes as its arguments: A DOMString representing the name you are giving to the element. Note that custom element names require a...
... Always call super first in constructor super(); // Element functionality written in here ... } } This is just a simple example, but there is more you can do here. It is possible to define specific lifecycle callbacks inside the class, which run at specific points in the element's lifecycle. For example, connectedCallback is invoked each time the custom element is appended into a document-connected element, while attributeChangedCallback is invoked when one of the custom element's attributes is added, removed, or changed. You'll learn more about these in the Using the lifecycle callbacks section below. There are two types of custom elements: Autonomous custom elements are standalone -- they don't inherit from standard HTML elements. You use these on a page by literally writin...
...d when one of the custom element's attributes is added, removed, or changed. You'll learn more about these in the Using the lifecycle callbacks section below. There are two types of custom elements: Autonomous custom elements are standalone -- they don't inherit from standard HTML elements. You use these on a page by literally writing them out as an HTML element. ...
...And 11 more matches
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
This document describes the JavaScript interface in Mozilla 1.2 and up to the XSLT Processing Engine (TransforMiiX). 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. ...
...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. ...
...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. ...
...And 11 more matches
ui/frame - Archive of obsolete content
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. ...
...an 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. ...
...cript 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", title: "City info", items: [frame] }); The toolbar is positioned between t...
...And 10 more matches
Tabbed browser - Archive of obsolete content
king with windows in chrome code for details. Multiple meanings for the word 'browser' The word 'browser' is used several ways. Of course the entire application Firefox is called "a browser". Within the Firefox browser are tabs and inside each tab is a browser, both in the common sense of a web page browser and the XUL sense of a browser element. Furthermore another meaning of 'browser' in this document and in some Firefox source is "the tabbrowser element" in a Firefox XUL window. Getting access to the browser From main window Code running in Firefox's global ChromeWindow, common for extensions that overlay into browser.xul, can access the tabbrowser element using the global variable gBrowser. // gBrowser is only accessible from the scope of // the browser window (browser.xul) gBrowser.addT...
...active gBrowser.selectedTab = gBrowser.addTab("http://www.google.com/"); Manipulating content of a new tab If you want to work on the content of the newly opened tab, you'll need to wait until the content has finished loading. // WRONG WAY (the page hasn't finished loading yet) var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/")); alert(newTabBrowser.contentDocument.body.innerHTML); // BETTER WAY var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/")); newTabBrowser.addEventListener("load", function () { newTabBrowser.contentDocument.body.innerHTML = "<div>hello world</div>"; }, true); (The event target in the onLoad handler will be a 'tab' XUL element). See tabbrowser for getBrowserForTab(). Note that the code above doe...
...e to try to re-use an existing tab which already displays the desired URL--if one is already open. Following this practice minimizes the proliferation of tabs and browsers created by your extension. Reusing by URL/URI A common feature found in many extensions is to point the user to chrome:// URIs in a browser window (for example, help or about information) or external (on-line http(s)://) HTML documents when the user clicks an extension's button or link. The following code demonstrates how to re-use an existing tab that already displays the desired URL/URI. If no such tab exists, a new one is opened with the specified URL/URI. function openAndReuseOneTabPerURL(url) { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.
...And 10 more matches
editor - Archive of obsolete content
<< XUL Reference home [ Examples | Attributes | Properties | Methods | Related ] A frame which is expected to contain an editable document. Set the value of the editortype attribute to html to create an editor document. Mozilla provides two types of editors, the HTML editor and the plaintext editor. The editor does not provide any editing user interface; you would supply that yourself. However, text editing, image resizing, and table row and cell editing capabilities are provided. If you do not set the editortype attribute on an editor, you must enable editing using the makeEditable method. ...
...ment. Mozilla provides two types of editors, the HTML editor and the plaintext editor. The editor does not provide any editing user interface; you would supply that yourself. However, text editing, image resizing, and table row and cell editing capabilities are provided. If you do not set the editortype attribute on an editor, you must enable editing using the makeEditable method. To specify the document to load in the editor use the src attribute. However, an issue is that if you specify the src attribute initially on the editor tag in the XUL file, the document does not become editable by default. To enable editing on an editor, do either of the following: Set the src attribute on the editor after the outer window has loaded, for example, in the onload handler. You might also set the src att...
...ment does not become editable by default. To enable editing on an editor, do either of the following: Set the src attribute on the editor after the outer window has loaded, for example, in the onload handler. You might also set the src attribute based on what the user selects from a file dialog. In this case, set the editortype attribute on the editor. Call the makeEditable method to make the document loaded in the editor editable. Enable the design mode of the document loaded in the editor. To edit a new document, set the src attribute to about:blank. To access most of the functionality of the editor, your application must be part of an extension or part of the chrome. XUL applications loaded via a URL from a web server will not be able to access most of the features of the editor. See t...
...And 10 more matches
Writing JavaScript for XHTML - Archive of obsolete content
Whilst authored to the stricter rules of XML, they are sent with the media type for HTML (text/html). The receiving 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. ...
...er 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 are 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 plai...
...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, 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. The easy solution is to do away with the commenting entirely: <script type="text/javascript"> window.alert("Hello World!"); </script> This will work so long as your ...
...And 10 more matches
HTML text fundamentals - Learn web development
content makes the reading experience easier and more enjoyable. In HTML, each paragraph has to be wrapped in a <p> element, like so: <p>I am a paragraph, oh yes I am.</p> Each heading has to be wrapped in a heading element: <h1>I am the title of the story.</h1> There are six heading elements: <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>. Each element represents a different level of content in the document; <h1> represents the main heading, <h2> represents subheadings, <h3> represents sub-subheadings, and so on. Implementing structural hierarchy For example, in this story, the <h1> element represents the title of the story, the <h2> elements represent the title of each chapter, and the <h3> elements represent sub-sections of each chapter: <h1>The Crushing Bore</h1> <p>By Chris Mills</p> <h2>Ch...
... all others sit below this in the hierarchy. Make sure you use the headings in the correct order in the hierarchy. Don't use <h3> elements to represent subheadings, followed by <h2> elements to represent sub-subheadings--that doesn't make sense and will lead to weird results. Of the six heading levels available, you should aim to use no more than three per page, unless you feel it is necessary. Documents with many levels (i.e., a deep heading hierarchy) become unwieldy and difficult to navigate. On such occasions, it is advisable to spread the content over multiple pages if possible. Why do we need structure? To answer this question, let's take a look at text-start.html--the starting point of our running example for this article (a nice hummus recipe). You should save a copy of this file on y...
...d difficult to navigate. On such occasions, it is advisable to spread the content over multiple pages if possible. Why do we need structure? To answer this question, let's take a look at text-start.html--the starting point of our running example for this article (a nice hummus recipe). You should save a copy of this file on your local machine, as you'll need it for the exercises later on. ...
...And 10 more matches
Client-side storage - Learn web development
This article explains the very basics of how these work. ...
...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 previously logged in). Saving data and assets locally so a site will be quicker (and potentially less expensive) to download, or be usable without a network connection. Saving web application generated documents locally for use offline Often client-side and server-side storage are used together. For example, you could download a batch of music files (perhaps used by a web game or music player application), store them inside a client-side database, and play them as needed. The user would only have to download the music files once -- on subsequent visits they would be retrieved from the database instead...
...pt code into it. Create an index.js file in the same directory as your HTML file. We'll start off by creating references to all the HTML features we need to manipulate in this example -- we'll create them all as constants, as these references do not need to change in the lifecycle of the app. ...
...And 10 more matches
Mozilla’s UAAG evaluation report
This UAAG evaluation report covers nightly builds of the Mozilla web browser itself, running on Windows 2000, as of February 20, 2002. We are claiming to support HTML 4, CSS 2, PNG, JPG and GIF. ...
...This UAAG evaluation report covers nightly builds of the Mozilla web browser itself, running on Windows 2000, as of February 20, 2002. We are claiming to support HTML 4, CSS 2, PNG, JPG and GIF. ...
...This UAAG evaluation report covers nightly builds of the Mozilla web browser itself, running on Windows 2000, as of February 20, 2002. ...
...And 10 more matches
Introduction to XPCOM for the DOM
Warning: this document has not yet been reviewed by the DOM gurus, it might contain some errors. This document is an introduction to the use of XPCOM in the context of the DOM code. The use of XPCOM and nsCOMPtr's described in this document covers about 80% of what you need to know to read the DOM code, and even write some. For more advanced topics, please see the XPCOM page. The tracking bug for this document is bug 99592. Target audience: People who would like a quick introduction to the use of C++ and XPCOM in the DOM code. The understanding of the content of this document is a requirement to read the rest of the DOM Hacking Guide. Important note: This document assumes some knowledge of C++, specially the object-oriented part of it. I learned C++ by reading "C++ Primer" from Stanle...
...lly, we will look at the implementation of our new interface through the creation of an nsIDOMFabian interface (Fabian is my first name ;-). XPIDL XPIDL stands for Cross-Platform Interface Definition Language. Instead of coding interfaces directly in C++ , one can use XPIDL. It simplifies greatly the task of defining interfaces, and offers some interesting features, like automatic generation of documentation, and XPT generation. The first thing to do is to decide what our interface, nsIDOMFabian, will do. For the purpose of this document, I have chosen to implement a new HTML interface called nsIDOMFabian. It will be implemented by the class nsHTMLDocument. The syntax of XPIDL is straightforward: #include "domstubs.idl"; [scriptable, uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)] interface ...
...fined in XPIDL contains methods and attributes, which are transformed into C++ functions by the XPIDL compiler. The class that implements the interface has to explicitly implement each method and implement the setter and the getter of each attribute defined on the interface. If the attribute is read-only, only a getter is necessary, of course. I have chosen to implement nsIDOMFabian in the nsHTMLDocument class, which is defined in nsHTMLDocument.h. There are three things to do: modify the class declaration, the class body, then code the functions declared on the interface. Modification of the class declaration and class body: #include "nsIDOMFabian.h" class nsHTMLDocument: public ... , public nsIDOMFabian { // ... NS_DECL_NSIDOMFABIAN // ... }; Fi...
...And 10 more matches
nsIContentViewer
?????????????????????"] .createInstance(Components.interfaces.nsIContentViewer); Method overview void clearHistoryEntry(); void close(in nsISHEntry historyEntry); void destroy(); [noscript,notxpcom,nostdcall] nsIViewPtr findContainerView(); void getBounds(in nsIntRectRef aBounds); Native code only! [noscript,notxpcom] nsIDocumentPtr getDocument(); void hide(); void init(in nsIWidgetPtr aParentWidget, [const] in nsIntRectRef aBounds); Native code only! void loadComplete(in unsigned long aStatus); void loadStart(in nsISupports aDoc); void move(in long aX, in long aY); void open(in nsISupports aState, in nsISHEntry aSHEntry); void pageHide(in boolean isUnload);...
... void move(in long aX, in long aY); void open(in nsISupports aState, in nsISHEntry aSHEntry); void pageHide(in boolean isUnload); boolean permitUnload([optional] in boolean aCallerClosesWindow); boolean requestWindowClose(); void resetCloseWindow(); void setBounds([const] in nsIntRectRef aBounds); Native code only! void setDocumentInternal(in nsIDocumentPtr aDocument, in boolean aForceReuseInnerWindow); Native code only! [noscript,notxpcom,nostdcall] void setNavigationTiming(in nsDOMNavigationTimingPtr aTiming); void setPageMode(in boolean aPageMode, in nsIPrintSettings aPrintSettings); void show(); void stop(); void unload(); Obsolete since Gecko 1.8 Attributes ...
...Can return null. Read only. isTabModalPromptAllowed boolean Read only. presContext nsPresContextPtr Read only. Native code only! Note: Prior to Geck...
...And 10 more matches
nsIDOMWindowUtils
an aIgnoreRootScrollFrame, in boolean aFlushLayout); void enterModalState(); nsIDOMElement findElementWithViewId(in nsViewID aId); void focus(in nsIDOMElement aElement); void forceUpdateNativeMenuAt(in AString indexString); void garbageCollect([optional] in nsICycleCollectorListener aListener); short getCursorType(); AString getDocumentMetadata(in AString aName); nsIDOMWindow getOuterWindowWithId(in unsigned long long aOuterWindowID); long getPCCountScriptCount(); AString getPCCountScriptSummary(in long aScript); AString getPCCountScriptContents(in long aScript); void getScrollXY(in boolean aFlushLayout, out long aScrollX, out long aScrollY); AString getVisitedDepe...
... void removeSheet(in nsIURI sheetURI, in unsigned long type); void resumeTimeouts(); void sendCompositionEvent(in AString aType); Obsolete since Gecko 9 void sendCompositionEvent(in AString aType, in AString aData, in AString aLocale); Obsol...
...e Type Description currentInnerWindowID unsigned long long The ID of the window's current inner window. Read only. Exceptions thrown NS_ERROR_NOT_AVAILABLE There is no current inner window displayDPI float The DPI of the display. Read only. docCharsetIsForced boolean Whether the charset of the window's current document has been forced by the user. Cannot be accessed from unprivileged context (not content-accessible) Read only. elementsRestyled Read only unsigned long long The number of elements which have been restyled for the current document. Keep in mind that during a restyle operation, an element may be restyled multiple times (for example, when an inline element contains blocks). This numb...
...And 10 more matches
nsIWebProgressListener
s State transition flags These flags indicate the various states that requests may transition through as they are being loaded. These flags are mutually exclusive. For any given request, onStateChange() is called once with the STATE_START flag, zero or more times with the STATE_TRANSFERRING flag or once with the STATE_REDIRECTING flag, and then finally once with the STATE_STOP flag. Note: For document requests, a second STATE_STOP is generated (see the description of STATE_IS_WINDOW for more details). Constant Value Description STATE_START 0x00000001 This flag indicates the start of a request. This flag is set when a request is initiated. The request is complete when onStateChange() is called for the same request with the STATE_STOP flag set. STATE_REDIR...
... flags These flags further describe the entity for which the state transition is occurring. These flags are not mutually exclusive (that is an onStateChange() event may indicate some combination of these flags). ...
... which the state transition is occurring. These flags are not mutually exclusive (that is an onStateChange() event may indicate some combination of these flags). Constant Value Description STATE_IS_REQUEST 0x00010000 This flag indicates that the state transition is for a request, which includes but is not limited to document requests. ...
...And 10 more matches
Working with windows in chrome code
access the opened window. The return value of window.open (and similar methods) is a Window object (usually ChromeWindow) - the same type as the window variable. Technically speaking, it implements a number of interfaces, including nsIDOMJSWindow and nsIDOMWindow, but it also contains the user-defined properties for global variables and functions of the window. ...
...pen (and similar methods) is a Window object (usually ChromeWindow) - the same type as the window variable. Technically speaking, it implements a number of interfaces, including nsIDOMJSWindow and nsIDOMWindow, but it also contains the user-defined properties for global variables and functions of the window. So, for example, to access the DOM document corresponding to the window, you can use win.document. Note however, that the open() call returns before the window is fully loaded, so some calls, like win.document.getElementById() will fail. To overcome this difficulty, you can move the initialization code to a load handler of the window being opened or pass a callback function, as described below. You can get a Window object from a document using document.defaultView. Content windows When a ...
..., like win.document.getElementById() will fail. To overcome this difficulty, you can move the initialization code to a load handler of the window being opened or pass a callback function, as described below. You can get a Window object from a document using document.defaultView. Content windows When a XUL window contains a widget capable of displaying a page, such as <browser> or <iframe>, the document in that widget is, naturally, separate from the document of the chrome window itself. There also is a Window object for each sub-document, although there's no window in a common sense for the sub-document. The same holds for chrome windows opened inside a tab of <tabbrowser>. The elements above the chrome document opened in the tab are separate from your chrome document. The following two subse...
...And 10 more matches
Using the CSS Typed Object Model - Web APIs
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(). ...
... 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(). ...
...('a'); // get the <dl> we'll be populating const stylesList = document.querySelector('#regurgitation'); // Retrieve all computed styles with computedStyleMap() const defaultComputedStyles = myElement.computedStyleMap(); // iterate thru the map of all the properties and values, adding a <dt> and <dd> for each for (const [prop, val] of defaultComputedStyles) { // properties const cssProperty = document.createElement('dt'); cssProperty.appendChild(document.createTextNode(prop)); stylesList.appendChild(cssProperty); // values const cssValue = document.createElement('dd'); cssValue.appendChild(document.createTextNode(val)); stylesList.appendChild(cssValue); } The computedStyleMap() method returns a StylePropertyMapReadOnly object containing the size property, which indicates how many prope...
...And 10 more matches
SVGSVGElement - Web APIs
ion and size of the viewport (implicit or explicit) that corresponds to the given <svg> element. When the browser is actually rendering the content, then the position and size values represent the actual values when rendering. The position and size values are unitless values in the coordinate system of the parent element. If no parent element exists (i.e., <svg> element represents the root of the document tree), if this SVG document is embedded as part of another document (e.g., via the HTML <object> element), then the position and size are unitless values in the coordinate system of the parent document. (If the parent uses CSS or XSL layout, then unitless values represent pixel units for the current CSS or XSL viewport.) SVGSVGElement.pixelUnitToMillimeterX A float representing the size of th...
...the physical size of a "screen unit", this float attribute will express that information; otherwise, user agents will provide a suitable default value (such as .28mm). SVGSVGElement.screenPixelToMillimeterY Corresponding size of a screen pixel along the y-axis of the viewport. SVGSVGElement.useCurrentView The initial view (i.e., before magnification and panning) of the current innermost SVG document fragment can be either the "standard" view, i.e., based on attributes on the <svg> element such as viewBox) or on a "custom" view (i.e., a hyperlink into a particular <view> or other element). If the initial view is the "standard" view, then this attribute is false. If the initial view is a "custom" view, then this attribute is true. SVGSVGElement.currentView An SVGViewSpec defining the initial...
...e <svg> element such as viewBox) or on a "custom" view (i.e., a hyperlink into a particular <view> or other element). If the initial view is the "standard" view, then this attribute is false. If the initial view is a "custom" view, then this attribute is true. SVGSVGElement.currentView An SVGViewSpec defining the initial view (i.e., before magnification and panning) of the current innermost SVG document fragment. The meaning depends on the situation: If the initial view was a "standard" view, then: the values for viewBox, preserveAspectRatio and zoomAndPan within currentView will match the values for the corresponding DOM attributes that are on SVGSVGElement directly the values for transform and viewTarget within currentView will be null If the initial view was a link into a <view> elem...
...And 10 more matches
Border-radius generator - CSS: Cascading Style Sheets
er: 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('change', function(e) { var value = parseInt(e.target.value); if (isNaN(value) === true) setValue(obj.topic, obj.value); else setValue(obj.topic, value); }); subscribe(obj.topic, function(value) { input.value = v...
...select(); }); input.addEventListener('change', function(e) { var value = parseInt(e.target.value); if (isNaN(value) === true) setValue(obj.topic, obj.value); else setValue(obj.topic, value); }); subscribe(obj.topic, function(value) { input.value = value + obj.unit; }); return input; } var SliderComponent = function SliderComponent(obj, sign) { var slider = document.createElement('div'); var startX = null; var start_value = 0; slider.addEventListener("click", function(e) { setValue(obj.topic, obj.value + obj.step * sign); }); slider.addEventListener("mousedown", function(e) { startX = e.clientX; start_value = obj.value; document.body.style.cursor = "e-resize"; document.addEventListener("mousemove", sliderMotion); }); document.
... var start_value = 0; slider.addEventListener("click", function(e) { setValue(obj.topic, obj.value + obj.step * sign); }); slider.addEventListener("mousedown", function(e) { startX = e.clientX; start_value = obj.value; document.body.style.cursor = "e-resize"; document.addEventListener("mousemove", sliderMotion); }); document.addEventListener("mouseup", function(e) { document.removeEventListener("mousemove", sliderMotion); document.body.style.cursor = "auto"; slider.style.cursor = "pointer"; }); var sliderMotion = function sliderMotion(e) { slider.style.cursor = "e-resize"; var delta = (e.clientX - startX) / obj.sensivity | 0; var value = delta * obj.step + start_value; setValue(obj.topic, value); } return slider; } var InputSlider = fun...
...And 10 more matches
HTML5 Parser - Developer guides
Web › Guide › HTML › HTML5 › HTML5 Parser
from Gecko 1.x and WebKit, which read it as two tags, foo and bar. If you previously tested your code in IE and Opera, then you probably don't have any tags like this. If you tested your site only with Gecko 1.x or WebKit (for example, Firefox-only intranets or WebKit-oriented mobile sites), then you might have tags that match this pattern, and they will behave differently with Gecko 2. Calling document.write() during parsing Prior to HTML5, Gecko and WebKit allowed calls to document.write() during parsing to insert content into the source stream. This behavior was inherently racy, as the content was inserted into a timing-dependent point in the source stream. If the call happened after the parser was done, the inserted content replaced the document. In IE, such calls are either ignored or impl...
...ing parsing Prior to HTML5, Gecko and WebKit allowed calls to document.write() during parsing to insert content into the source stream. This behavior was inherently racy, as the content was inserted into a timing-dependent point in the source stream. If the call happened after the parser was done, the inserted content replaced the document. In IE, such calls are either ignored or imply a call to document.open(), replacing the document. In HTML5, document.write() can only be called from a script that is created by a <script> tag that does not have the async or defer attributes set. With the HTML5 parser, calls to document.write() in any other context either are ignored or replace the document. ...
..., such calls are either ignored or imply a call to document.open(), replacing the document. In HTML5, document.write() can only be called from a script that is created by a <script> tag that does not have the async or defer attributes set. With the HTML5 parser, calls to document.write() in any other context either are ignored or replace the document. Some contexts from which you should not call document.write() include: scripts created using document.createElement() event 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, wi...
...And 10 more matches
Using HTML sections and outlines - Developer guides
Important: There are no implementations of the proposed outline algorithm in web browsers nor assistive technology; it was never part of a final W3C specification. Therefore the outline algorithm should not be used to convey document structure to users. Authors are advised to use heading rank (h1-h6) to convey document structure. The HTML5 specification introduced several semantic sectioning elements to help organize the structure of documents. Semantic sectioning elements are specifically designed to communicate structural meaning to browsers and other technologies interpreting the document on behalf of users, such as screen readers and voice assistants. Semantic sectioning elements clarify the larger-scale structures within a document. They are intended to enhance the limited semantics of e...
...s a section that contains navigation links that appear often on a site. You can have primary and secondary menus, but you cannot nest a <nav> element inside another <nav> element. HTML Article Element (<article>) defines a piece of self-contained content. It does not refer to the main content alone and can be used for comments and widgets. HTML Section Element (<section>) defines a section of a document to indicate a related grouping of semantic meaning. It makes sense to use the section element to provide extra context for the parent element. HTML Aside Element (<aside>) defines a section that, though related to the main element, doesn't belong to the main flow, like an explanation box or an advertisement. The aside element has its own outline, but doesn't belong to the main one. Other Seman...
...o provide extra context for the parent element. HTML Aside Element (<aside>) defines a section that, though related to the main element, doesn't belong to the main flow, like an explanation box or an advertisement. The aside element has its own outline, but doesn't belong to the main one. Other Semantic HTML elements used in Sectioning HTML Body Element (<body>) defines all the content of a document. It contains all the content and HTML tags. HTML Header Element (<header>) defines a page area that typically contains a logo, title, and navigation. The header can also be used inside other semantic elements such as <article> or <section>. A section header might contain the section's heading, author name, etc. <article>, <section>, <aside>, and <nav> can have their own <header>. Despite its nam...
...And 10 more matches
Navigation and resource timings - Web Performance
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. ...
... 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. ...
... 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. ...
...And 10 more matches
Interacting with page scripts - Archive of obsolete content
sn't a supported API, so it could be removed or changed in a future version of the SDK. Expose objects to page scripts Until Firefox 30, you could use unsafeWindow to perform the reverse procedure, and make objects defined in content scripts available to page scripts: // content-script.js unsafeWindow.contentScriptObject = {"greeting" : "hello from add-on"}; // page-script.js var button = document.getElementById("show-content-script-var"); button.addEventListener("click", function() { // access object defined by content script console.log(window.contentScriptObject.greeting); // "hello from add-on" }, false); After Firefox 30, you can still do this for primitive values, but can no longer do it for objects. Instead, you need to use the global cloneInto() function to clone the obje...
...riptObject; The "page.html" file adds two buttons and assigns an event listener to each: one listener displays a property of the cloned object, and the other listener displays a property of the assigned object: <html> <head> </head> <body> <input id="works" type="button" value="I will work"/> <input id="fails" type="button" value="I will not work"/> <script> var works = document.getElementById("works"); works.addEventListener("click", function() { alert(clonedContentScriptObject.greeting); }, false); var fails = document.getElementById("fails"); fails.addEventListener("click", function() { alert(assignedContentScriptObject.greeting); }, false); </script> </body> </html> If you run the example, clicking "I will work" ...
...Since structured cloning doesn't work for functions, this means that you can't export functions that take fu...
...And 9 more matches
tabs - Archive of obsolete content
Attaching stylesheets New in Firefox 34. You can't attach style sheets to a tab using tab.attach(), but from Firefox 34 onwards ...
...rivate windows If your add-on has not opted into private browsing, then you won't see any tabs that are hosted by private browser windows. Tabs hosted by private browser windows won't be seen if you enumerate the tabs module itself, and you won't receive any events for them. To learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module. Converting to XUL tabs To convert from the high-level Tab objects used in this API to the low-level XUL tab objects used in the tabs/utils API and by traditional add-ons, use the viewFor() function exported by the viewFor module. To convert back the other way, from a XUL tab to a high-level Tab object, use the modelFor() function, exported by the modelFor ...
...In particular, your code might not work w...
...And 9 more matches
Displaying web content in an extension without security issues - Archive of obsolete content
o 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 use all of them. Displaying untrusted data as content In Firefox, there is a distinction between chrome and content documents. The top document in a window is always a chrome document. If you look at the frames it loads, those will usually be chrome documents as well. However, if the document is loaded into <iframe type="content"> or <browser type="content">, it will be considered a content document, and so will be all the frames it loads (the "type" attribute is ignored at that point). So if we look at the frame hiera...
... well. However, if the document is loaded into <iframe type="content"> or <browser type="content">, it will be considered a content document, and so will be all 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 b...
...This also means that you won't be able to establish a security boundary between your extension and untrusted data if your extension opens as a tab in the browser -- so displaying your extension in a browser tab is a bad choice. ...
...And 9 more matches
XUL Questions and Answers - Archive of obsolete content
Return to mozilla-dev-tech-xul summaries The frequently asked questions should be moved to XUL FAQ (make sure they have a clear answer.) Where can I get more information about creating MozSearch plugins? Creating MozSearch plugins contains more help information about creating MozSearch plugin on Firefox 2. More documentation on Search plugins is available in the Search plugins category. Is localizing remote XUL possible? Loading remote DTDs for XML documents is currenty not supported in XUL. The following bugs were reported on this issue: bug 22942, bug 133698. Is there an editor widget in XUL that supports syntax highlighting? Daniel Glazman has been working on this for his projects. He said the code will be open-source, but it is not released yet (as of Oct 2006). Some teas...
...a button that matches one of these common usages, use the icon attribute to indicate this. How to use Dynamic Objects in Toolbar There may be a few ways to implement this: By building your menupopup from an RDF datasource, which could be generated on the server. By getting data (e.g. JSON string) from the server, parsing it on client, 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 prope...
...end 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. ...
...And 9 more matches
Arrays - Learn web development
simple string concatenation, which should be familiar to you. ...
...o you. ...
... document.querySelector('.output p'); let total = 0; list.innerHTML = ''; totalBox.textContent = ''; // number 1 'Underpants:6.99' 'Socks:5.99' 'T-shirt:14.99' 'Trousers:31.99' 'Shoes:23.99'; for (let i = 0; i <= 0; i++) { // number 2 // number 3 // number 4 // number 5 let itemText = 0; const listItem = document.createElement('li'); listItem.textContent = itemText; list.appendChild(listItem); } totalBox.textContent = 'Total: $' + total.toFixed(2); </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> const textarea = document.getElementById('code'); const reset = document.getElementById('reset...
...And 9 more matches
Embedding the editor
Introduction This document describes the current state of editor embeddability, problems with the existing implementation, some possible embedding scenarios that we need to deal with, and an embedding solution that will fulfill them. Finally, steps towards that final solution are described. Embedding applications Here are some embedding scenarios that editor needs to deal with. Note here that I use the term 'Composer' to mean an HTML-savvy compose widget that does rich text editing, and 'Editor' to mean a plain text editor (as well as the underlying technology for Composer). <htmlarea> is intended as a shorthand for a rich-text multiline text widget embedded in an HTML document, and is not meant to infer that future versions of Mozilla will support this specific tag. Composer embedded in a...
...to get basic editing functionality, be able to have any number of <editor>s per window, and control whether those <editor>s are in HTML or plain text mode. Composer embedded in a native application In this application, the <iframe> on which the editor lives is embedded directly in the native application; this is equivalent to embedding the browser via nsIWebBrowser, but instead having an editable document. The composer chrome (toolbars etc) may be implemented by the embedder using native widgets, or using some amount of XUL. That chrome needs to be configurable - dockable floating toolbars, toolbar shared between composer widgets, or 1 per widget. This type of embedding requires that the composer code is agnostic to where its UI is coming from; communication between the core editor and the UI need...
...e - dockable floating toolbars, toolbar shared between composer widgets, or 1 per widget. This type of embedding requires that the composer code is agnostic to where its UI is coming from; communication between the core editor and the UI needs to go through one or more interfaces that insulate the editor from its host application. (The current nsEditorShell makes assumptions about the hosting XUL document, which need to be broken.) Composer embedded in a web page (<htmlarea>) IE 5 supports the <HTMLArea> element; if Mozilla is to support something similar, editor needs to be embeddable to the extent that this can be done. It is likely that we'd use XBL to implement this type of widget, as is the plan for other form controls. As is the case for composer embedded in a native application, there is a ...
...And 9 more matches
nsIEditor
<< XPCOM API Reference editor/nsIEditor.idlScriptable Provides methods and attributes used when editing page content. ...
...Name, in AString sourceAttrValue, in boolean aSuppressTransaction); void removeAttributeOrEquivalent(in nsIDOMElement element, in DOMString sourceAttrName, in boolean aSuppressTransaction); void postCreate(); void preDestroy(in boolean aDestroyingFrames); Selected Content Removal void deleteSelection(in short action, in short stripWrappers); Document Info and File Methods void resetModificationCount(); long getModificationCount(); void incrementModificationCount(in long aModCount); void incrementModificationCount(in long aModCount); Transaction Methods void doTransaction(in nsITransaction txn); void enableUndo(in boolean enable); void undo(in unsigned long count); ...
...te); void syncRealTimeSpell(); void setSpellcheckUserOverride(in boolean enable); Clipboard Methods void cut(); boolean canCut(); void copy(); boolean canCopy(); void paste(in long aSelectionType); boolean canPaste(in long aSelectionType); Selection Methods void selectAll(); void beginningOfDocument(); void endOfDocument(); Drag/Drop Methods boolean canDrag(in nsIDOMEvent aEvent); void doDrag(in nsIDOMEvent aEvent); void insertFromDrop(in nsIDOMEvent aEvent); Node Manipulation Methods void setAttribute(in nsIDOMElement aElement, in AString attributestr,in AString attvalue); boolean getAttributeValue(in nsIDOMElement aEle...
...And 9 more matches
nsIWebBrowserPersist
Inherits from: nsICancelable Last changed in Gecko 36.0 (Firefox 36.0 / Thunderbird 36.0 / SeaMonkey 2.33) Implemented by: @mozilla.org/embedding/browser/nsWebBrowser;1 and @mozilla.org/embedding/browser/nsWebBrowserPersist;1. ...
...la.org/embedding/browser/nsWebBrowserPersist;1. ...
...rowser/nsWebBrowserPersist;1. ...
...And 9 more matches
Introduction to DOM Inspector - Firefox Developer Tools
t download and install it from the Mozilla add-ons web site. (Note: this is now a dead link.) When you first start the DOM Inspector, you are presented with a two-pane application window that looks a little like the main Mozilla browser. Like the browser, the DOM Inspector includes an address bar, and some of the same menus. In SeaMonkey additional global menus will be available. ...
...ow a dead link.) When you first start the DOM Inspector, you are presented with a two-pane application window that looks a little like the main Mozilla browser. Like the browser, the DOM Inspector includes an address bar, and some of the same menus. In SeaMonkey additional global menus will be available. Inspecting a Document When the DOM Inspector opens, it may or may not load an associated document, depending on the host application. If the DOM Inspector doesn't automatically load a document or loads a document other than the one you'd like to inspect, you can select the desired document a few different ways. Inspecting Content Documents The Inspect Content Document menupopup can be accessed from the File menu, and it will list currently loaded content documents. In Firefox and SeaMonkey ...
...A browser window and the DOM Inspector are likely be already open and displayed in this list. ...
...And 9 more matches
Using dynamic styling information - Web APIs
g, 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 detail below. ...
...ever, 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 detail below. Note also that, as with individual element's DOM styles, when speaking of manipulating the stylesheets, this is not actually manipulating the physical document(s), but merely the internal representation of the document. ...
...ot actually manipulating the physical document(s), but merely the internal representation of the document. The basic style object exposes the Stylesheet and the CSSStylesheet interfaces. Those interfaces contain members like insertRule, selectorText, and parentStyleSheet for accessing and manipulating the individual style rules that make up a CSS stylesheet. To get to the style 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 = ...
...And 9 more matches
Basic animations - Web APIs
of our solar system. ...
...Path(); ctx.arc(150, 150, 105, 0, Math.PI * 2, false); // Earth orbit ctx.stroke(); ctx.drawImage(sun, 0, 0, 300, 300); window.requestAnimationFrame(draw); } init(); <canvas id="canvas" width="300" height="300"></canvas> ScreenshotLive sample An animated clock This example draws an animated clock, showing your current time. ...
... // image larger than canvas x = CanvasXSize - imgW; } if (imgW > CanvasXSize) { // image width larger than canvas clearX = imgW; } else { clearX = CanvasXSize; } if (imgH > CanvasYSize) { // image height larger than canvas clearY = imgH; } else { clearY = CanvasYSize; } // get canvas context ctx = document.getElementById('canvas').getContext('2d'); // set refresh rate return setInterval(draw, speed); } function draw() { ctx.clearRect(0, 0, clearX, clearY); // clear the canvas // if image is <= Canvas Size if (imgW <= CanvasXSize) { // reset, start from beginning if (x > CanvasXSize) { x = -imgW + x; } // draw additional image1 ...
...And 9 more matches
Web accessibility for seizures and physical reactions - Accessibility
epilepsy is actually a kind of "reflex epilepsy"--seizures occurring in response to a trigger. In the case of photosensitive epilepsy, seizures are triggered specifically by flashing lights, but other types of reflex epilepsies may be triggered by the act of reading, or by noises. Patterns and images can also trigger epilepsy. The fact that static images may cause seizures and other disorders is documented in such articles as "Gamma Oscillations and photosensitive epilepsy", where it is noted "Certain visual images, even in the absence of motion or flicker, can trigger seizures in patients with photosensitive epilepsy" The Epilepsy Foundation, in its article, "Shedding Light on Photosensitivity, One of Epilepsy's Most Complex Conditions" talks about static images and patterns. "Static or moving p...
...tripes in any orientation" In addition to stripes, checkered patterns have also been known to cause photosensitive seizures, according to Cedars-Sinai. Although static images are possible as triggers, they are less consistent. The trigger that is well established and strong is flashing/strobe lights. Dr. Selim Benbadis of USF's Comprehensive Epilepsy Program notes, "The only thing that is really documented is flashing lights, which can trigger seizures in patients with photosensitive epilepsy. Only a few types of epilepsies are photosensitive though, and the vast majority of epilepsies are not." In addition to seizures brought about by photosensitivity, listening to certain pieces of music can also trigger what are called musicogenic seizures, although these types of seizures seem to be much more...
...3 times per second, is large enough, and bright enough. Section 508 prohibits flickering effects with a frequency greater than 3 Hz (flickers per second) and lower than 55 Hz. The Epilepsy Foundation's article "Take advantage of media queries with <style> In setting up media queries, you are enabling controls by the user; these controls are made available in the browser or in the OS. See the MDN document, "Accessibility: What users can to to browse more safely" to see more details of how a user accesses the controls. prefers-reduced-motion Support for prefers-reduced-motion in modern browsers is growing. @media screen and (prefers-reduced-motion: reduce) { } @media screen and (prefers-reduced-motion) { } To see a great example of how to use the code prefers-reduced-motion, visit the MDN docum...
...And 9 more matches
<input type="datetime-local"> - HTML: Hypertext Markup Language
ill 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 for this purpose. Additional attributes In addition to the attributes common to all ...
...al">, we create a new <input> element, try setting its type to datetime-local, then immediately check what its type is set to. Browsers that don't support datetime-local return text, since that's what datetime-local falls back to. If <input type="datetime-local"> is not supported, we hide the native picker and show the fallback picker UI (<select>) instead. ...
...e-local, then immediately check what its type is set to. Browsers that don't support datetime-local return text, since that's what datetime-local falls back to. If <input type="datetime-local"> is not supported, we hide the native picker and show the fallback picker UI (<select>) instead. ...
...And 9 more matches
<input type="time"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › time
put. 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 seconds (see Using the step attribute), the format is always hh:mm:ss. You can learn m...
..."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() { valueSpan.innerText = startTime.value; }, false); When a form including a time input is submitted, the value is encoded before being included in the form's data. The form's data entry for a time input will always be in the form name=hh%3Amm, or name=hh%3Amm%3ass if...
...possible value, then wrap back around to the beginning again. For example, specifying a min of 14:00 and a max of 2:00 means that the permitted time values start at 2:00 PM, run through midnight to the next day, ending at 2:00 AM. See more in the making min and max cross midnight section of this article. list The values of the list attribute is the id of a <datalist> element located in the same document. The <datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. max A string indicating the latest time to accept, specified in the same ...
...And 9 more matches
JavaScript modules - JavaScript
10.3Samsung Internet Android Full support 8.0nodejs Full support 13.2.0Notes Full support 13.2.0Notes Notes Modules must either have a filename ending in .mjs, or the nearest parent package.json file must contain "type": "module". See Node's ECMAScript Modules documentation for more details. Full support 12.0.0Notes Disabled Notes Modules must either have a filename ending in .mjs, or the nearest parent package.json file must contain "type": "module". See Node's ECMAScript Modules documentation for more details.Disabled From version 12.0.0: this feature is behind the --experimental-modules runtime flag. ...
...ding in .mjs, or the nearest parent package.json file must contain "type": "module". See Node's ECMAScript Modules documentation for more details.Disabled From version 12.0.0: this feature is behind the --experimental-modules runtime flag. Full support 8.5.0Notes Disabled Notes Module filenames must end with .mjs, not .js. ...
... 11.3Samsung Internet Android Full support 8.0nodejs Full support 13.2.0Notes Full support 13.2.0Notes Notes Dynamic import can be used in either CommonJS or ES module files, to import either CommonJS or ES module files. ...
...And 9 more matches
Communicating With Other Scripts - Archive of obsolete content
ipts embedded in the web page or included using <script> tags) main.js Your content scripts can communicate with your add-on's "main.js" (or any other modules you're written for your add-on) by sending it messages, using either the port.emit() API or the postMessage() API. See the articles on using postMessage() and using port for details. ...
...-on) by sending it messages, using either the port.emit() API or the postMessage() API. See the articles on using postMessage() and using port for details. Content Scripts Content scripts loaded into the same document at the same time using the same method can interact with each other directly as well as with the web content itself. However, content scripts which have been loaded into different documents cannot interact directly with each other. Content scripts that have been loaded into the same document by different methods, or the same method called more than once, can pass messages directly to each other using the DOM postMessage() API or a CustomEvent. Any two content scripts can communicate by using the main add-on script to manually relay messages between the content scripts. For exampl...
...See the section below on using postMessage() before Firefox 31. You can communicate between the content script and page scripts using window.postMessage(). Messaging From Content Script To Page Script Suppose we have a page called "listen.html" hosted at "my-domain.org", and we want to send messages from the add-on to a script embedded in that page. In the main add-on code, we h...
...And 8 more matches
widget - Archive of obsolete content
="pause.png" id="pause-button"> <img src="stop.png" id="stop-button"> </body> </html> We just include three icons, and assign an ID to each one. This HTML file, and the icon files it references, are saved in the add-on's data directory. ...
...nd assign an ID to each one. This HTML file, and the icon files it references, are saved in the add-on's data directory. Next, we write a content script that listens for click events on each icon and sends the corresponding message to the main add-on code: var play_button = document.getElementById("play-button"); play_button.onclick = function() { self.port.emit("play"); } var pause_button = document.getElementById("pause-button"); pause_button.onclick = function() { self.port.emit("pause"); } var stop_button = document.getElementById("stop-button"); stop_button.onclick = function() { self.port.emit("stop"); } We save this file in the add-on's data directory as "button-script.js". Finally. in the add-on's "main.js" file, we create the widget, assign it the HTML file and the content scri...
... crucial difference is that these scripts access the postMessage and port objects through the addon object, whereas content scripts access them through the self object. To show the difference, convert the player add-on above to use normal page scripts instead of content scripts. ...
...And 8 more matches
Binding Attachment and Detachment - Archive of obsolete content
Bindings can be attached to elements through CSS using the -moz-binding property. -moz-binding Value: none | [,]* <uri> | inherit Initial Value: none Applies to: all elements (not generated content or pseudo-elements) Inherited: no Percentages: N/A The value of the -moz-binding property is a set of URLs that identify specific bindings. An individual URL in the set consists of the binding document's URL and the binding's document-unique identifier. In the following example, a binding is referenced that will be attached to all HTML checkbox elements. input[type="checkbox"] { -moz-binding: url("http://www.mozilla.org/xbl/htmlBindings.xml#checkbox"); } Bindings attached through CSS will only remain on the bound element as long as the element continues to match the style rule. If at any ...
...le. If at any time a resolution of style on the element determines that a different binding should be attached, the old binding (and all bindings that it explicitly extends in its inheritance chain) will be detached. No bindings will be attached to elements that match the style rule, but are inside an element that has style display:none set. See bug 307098. Whenever an element is removed from a document, any bindings attached via CSS loaded by the document will be detached. Attachment using element.style property None of the XBL inheritance properties of element.style.MozBinding described here are implemented (if ever). Bindings can be attached to elements through the scripting by assigning the element.style.MozBinding property. Respectively bindings can be detached by setting element.style...
...tachment using element.style property None of the XBL inheritance properties of element.style.MozBinding described here are implemented (if ever). Bindings can be attached to elements through the scripting by assigning the element.style.MozBinding property. Respectively bindings can be detached by setting element.style.MozBinding to empty string. Note: Some older papers mentioned DOM methods document.addBinding and document.removeBinding; these were subsequently discarded as redundant and not implemented. var checkbox = document.getElementById("mycheckbox"); checkbox.style.MozBinding = "url(http://www.mozilla.org/xbl/htmlBindings.xml#checkbox)"; This attachment is not necessarily synchronous. Scripts that invoke this method should not assume that the binding is installed immediately after...
...And 8 more matches
Adding Methods to XBL-defined Elements - Archive of obsolete content
d. 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"); element.getMaximum() // this will fail By the way, it is safe to call methods from the constructor, other methods on the object and event handlers. Accessing the Anonymous Content There may be times when you want to modify some aspect of the elements defined in the content element, either from a method body or elsewhere. These elements are created anonymously and a...
...ement is implemented to use it. However, there is a special way of getting this anonymous content. Elements with an XBL behavior attached to them have a special property which holds an array of the anonymous child elements inside it. Each element of the array stores each direct child element of the XBL-defined element. This special property cannot be accessed directly. Instead, you must call the document's getAnonymousNodes() method: var value=document.getAnonymousNodes(element); Here, 'element' should be set to a reference to the element that you want to get the anonymous content of. The function returns an array of elements, which is the anonymous content. To get elements below that, you can use the regular DOM functions because they aren't hidden. Note that it is possible for an XBL-bound el...
...s 'this' as the parameter to getAnonymousNodes(). The next example can be used to create text with a label. The method 'showTitle' can be used to show or hide the label. It works by getting a reference to the title element using the anonymous array and changing the visibility of it. ...
...And 8 more matches
iframe - Archive of obsolete content
<< XUL Reference home [ Examples | Attributes | Properties | Methods | Related ] An inner frame that works much like the HTML <iframe> element. The src attribute can be used to specify the content of the frame. This content is a separate document. The children of the iframe are ignored. Currently, XUL iframes running in remote processes are not supported. If you want to run content in a remote process, use a XUL browser element. Warning: When used in chrome-privileged documents (either HTML or XUL) such as Firefox addons, the contents of the frame may have the same permissions as Firefox itself. This can be a serious security vulnerability, for example if you use src="http://...". When used in this case, please see Displaying web content in an extension without security issu...
... the contents of the frame may have the same permissions as Firefox itself. This can be a serious security vulnerability, for example if you use src="http://...". When used in this case, please see Displaying web content in an extension without security issues. More information is available in the XUL tutorial. ...
...Default is false. src Type: URI The URI of the content to appear in the element. type Type: one of the values below. The type of browser, which can be used to set access of the do...
...And 8 more matches
Using the Right Markup to Invoke Plugins - Archive of obsolete content
to diligently specifyobtainment mechanisms. At a minimum, web authors will have to nest some alternate text inside their object elements telling users where to obtain the missing component. Adding an additional layer of convenience in the form of automatic retrieval is the subject of a bug 180411 in the Mozilla open source code. Some plugins don't understand all the param elements that their documentation suggests should configure them in Mozilla-based browsers. An example is versions of the Macromedia Flash player plugin upto Flash Player 6 r. 47, which don't understand the <param name="movie" value="animation.swf"> param element, which is supposed to tell the Flash player which animation to start playing. In order to work around this, developers are encouraged to use the data attribute to t...
...object elements based on architecture. For example, on browsers that support ActiveX, such as IE, create an object element with a classid attribute, and on browsers that support the Netscape Plugin architecture, use a MIME type. ...
...iveX, such as IE, create an object element with a classid attribute, and on browsers that support the Netscape Plugin architecture, use a MIME type. ...
...And 8 more matches
Third-party APIs - Learn web development
hen 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 access them from JavaScript you first need to connect to the API functionality and make it available on your page. This typically involves first linking to a JavaScript library available on the server via a <script>...
...apquest.control({ position: 'bottomright' })); There are other types of control available, for example mapquest.searchControl() and mapquest.satelliteControl(), and some are quite complex and powerful. Have a play around and see what you can come up with. Adding a custom marker Adding a marker (icon) at a certain point on the map is easy -- you just use the L.marker() method (which seems to be documented in the related Leaflet.js docs). Add the following code to your example, again inside window.onload: L.marker([53.480759, -2.242631], { icon: L.mapquest.icons.marker({ primaryColor: '#22407F', secondaryColor: '#3B5998', shadow: true, size: 'md', symbol: 'A' }) }) .bindPopup('This is Manchester!') .addTo(map); As you can see, this at its simplest takes two parameters, a...
...g an mapquest.icons.marker() method, which as you can see contains information such as color and size of marker. Onto the end of the first method call we chain .bindPopup('This is Manchester!'), which defines content to display when the marker is clicked. Finally, we chain .addTo(map) to the end of the chain to actually add the marker to the map. Have a play with the other options shown in the documentation and see what you can come up with! Mapquest provides some pretty advanced functionality, such as directions, searching, etc. Note: If you have trouble getting the example to work, check your code against our finished version -- see expanded-example.html (also see it running live here). What about Google Maps? Google Maps is arguably the most popular maps API, so why didn't we use it for...
...And 8 more matches
Server-side web frameworks - Learn web development
rk provides an ORM, and refers to the object used to define the structure of a record as the model. The model specifies the field types to be stored, which may provide field-level validation on what information can be stored (e.g. an email field would only allow valid email addresses). The field definitions may also specify their maximum size, default values, selection list options, help text for documentation, label text for forms etc. The model doesn't state any information about the underlying database as that is a configuration setting that may be changed separately of our code. The first code snippet below shows a very simple Django model for a Team object. This stores the team name and team level as character fields and specifies a maximum number of characters to be stored for each record. ...
...el__exact). #best/views.py from django.shortcuts import render from .models import Team def youngest(request): list_teams = Team.objects.filter(team_level__exact="U09") context = {'youngest_teams': list_teams} return render(request, 'best/index.html', context) Rendering data Web frameworks often provide templating systems. These allow you to specify the structure of an output document, using placeholders for data that will be added when a page is generated. Templates are often used to create HTML, but can also create other types of document. Web frameworks often provide a mechanism to make it easy to generate other formats from stored data, including JSON and XML. For example, the Django template system allows you to specify variables using a "double-handlebars" syntax (e.g.
...ks in the following section). With so many choices, it can become difficult to work out what framework provides the best starting point for your new web application. Some of the factors that may affect your decision are: Effort to learn: The effort to learn a web framework depends on how familiar you are with the underlying programming language, the consistency of its API, the quality of its documentation, and the size and activity of its community. If you're starting from absolutely no programming experience then consider Django (it is one of the easiest to learn based on the above criteria). If you are part of a development team that already has significant experience with a particular web framework or programming language, then it makes sense to stick with that. Productivity: Productivity...
...And 8 more matches
Introduction to client-side frameworks - Learn web development
amiliarity 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 a place to read things, but to do things. JavaScript's popularity steadily increased. Developers who worked with JavaScript wrote tools to solve the problems they faced, and packaged them into reusable packages called libraries, so they could share their solutions with others. This shared ecosystem of libraries helped shape the growth of the web. Now, JavaScript is an e...
...te is an array of objects structured like this: const state = [ { id: 'todo-0', name: 'Learn some frameworks!' } ] How do we show one of those tasks to our user? We want to represent each task as a list item - an HTML <li> element inside of an unordered list element (a <ul>). ...
...s: const state = [ { id: 'todo-0', name: 'Learn some frameworks!' } ] How do we show one of those tasks to our user? We want to represent each task as a list item - an HTML <li> element inside of an unordered list element (a <ul>). How do we make it? That could look something like this: function buildTodoItemEl(id, name) { const item = document.createElement('li'); const span = document.createElement('span'); const textContent = document.createTextNode(name); span.appendChild(textContent) item.id = id; item.appendChild(span); item.appendChild(buildDeleteButtonEl(id)); return item; } Here, we use the document.createElement() method to make our <li>, and several more lines of code to create the properties and children it needs. The tenth line of this snippet refer...
...And 8 more matches
Inner and outer windows
In order to represent these levels of complexity, two "types" of window need to be considered. These don't technically refer to windows as the user sees them, but rather a perspective on what the user is looking at. ...
...In order to represent these levels of complexity, two "types" of window need to be considered. These don't technically refer to windows as the user sees them, but rather a perspective on what the user is looking at. ...
...In order to represent these levels of complexity, two "types" of window need to be considered. These don't technically refer to windows as the user sees them, but rather a perspective on what the user is looking at. ...
...And 8 more matches
source-editor.jsm
per tab. Editor mode constants 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...
...paces (that is, the expandTab property is true), the returned string is comprised of the number of spaces specified by the tabSize property when the editor was initialized by calling init(). Otherwise, the returned string is simply "\t". getLineCount() Returns the number of lines of text in the editor. Number getLineCount(); Parameters None. Return value The number of lines of text in the document being edited. getLineDelimiter() Returns a string containing the character or characters that are used as the end of each line of text. This may be, for example, "\n", "\r", or "\r\n". String getLineDelimiter(); Parameters None. Return value A string containing the character or characters that delineate lines of text. getLineEnd Returns the character offset of the character after the sp...
...offset of the first character of the specified line in the text. Number getLineStart( Number aLineIndex ); Parameters aLineIndex Zero-based offset to the line number to which to return the end offset. Return value The offset to the first character in the specified line, or -1 if the specified line number is out of range. getMode() Returns the current syntax highlighting mode for the document's contents. String getMode(); Parameters None. Return value A string indicating the type of file being edited, as previously set using either the mode property when configuring the editor, or by a call to setMode(). See Editor mode constants for possible values. getSelectedText() Returns the currently-selected text. String getSelectedText(); Parameters None. Return value The current...
...And 8 more matches
NSS functions
s new flag or addition to structure. SSL functions The public functions listed here are used to configure sockets for communication via the SSL and TLS protocols. In addition to the functions listed here, applications that support SSL use some of the Certificate functions, Crypto functions, and Utility functions described below on this page. Other sources of information: The NSS_reference documents the functions most commonly used by applications to support SSL. The NSS home page links to additional SSL documentation. If documentation is available for a function listed below, the function name is linked to either its MDC wiki page or its entry in the old SSL Reference. The Mozilla Cross Reference (MXR) link for each function provides access to the function definition, prototype definiti...
...entation is available for a function listed below, the function name is linked to either its MDC wiki page or its entry in the old SSL Reference. The Mozilla Cross Reference (MXR) link for each function provides access to the function definition, prototype definition, and source code references. The NSS version column indicates which versions of NSS support the function. ...
...he new SSL shared libraries. Applications that want to use the SSL shared libraries must convert to calling the new replacement functions listed below. Each function name is linked to its entry in the old SSL Reference. The Mozilla Cross Reference (MXR) link for each function provides access to the function definition, prototype definition, and source code references. ...
...And 8 more matches
ChildNode.after() - Web APIs
Web › API › ChildNode › after
ode's parent, just after this ChildNode. DOMString objects are inserted as equivalent Text nodes. Syntax [Throws, Unscopable] void ChildNode.after((Node or DOMString)... nodes); Parameters nodes A set of Node or DOMString objects to insert. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...MString objects are inserted as equivalent Text nodes. Syntax [Throws, Unscopable] void ChildNode.after((Node or DOMString)... nodes); Parameters nodes A set of Node or DOMString objects to insert. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...rows, Unscopable] void ChildNode.after((Node or DOMString)... nodes); Parameters nodes A set of Node or DOMString objects to insert. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...And 8 more matches
Element.innerHTML - Web APIs
Web › API › Element › innerHTML
ment property innerHTML gets or sets the HTML or XML markup contained within the element. Note: If a <div>, <span>, or <noembed> node has a child text node that includes the characters (&), (<), or (>), innerHTML returns these characters as the HTML entities "&amp;", "&lt;" and "&gt;" respectively. Use Node.textContent to get a raw copy of these text nodes' contents. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML(). Syntax const content = element.innerHTML; element.innerHTML = htmlString; Value A DOMString containing the HTML serialization of the element's descendants. Setting the value of innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string...
...endants. Setting the value of innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString. Exceptions SyntaxError An attempt was made to set the value of innerHTML using a string which is not properly-formed HTML. NoModificationAllowedError An attempt was made to insert the HTML into a node whose parent is a Document. Usage notes The innerHTML property can be used to examine the current HTML source of the page, including any changes that have been made since the page was initially loaded. Reading the HTML contents of an element Reading innerHTML causes the user agent to serialize the HTML or XML fragment comprised of the element's descendants. The resulting string is returned. let contents = myElement.i...
...: The returned HTML or XML fragment is generated based on the current contents of the element, so the markup and formatting of the returned fragment is likely not to match the original page markup. Replacing the contents of an element Setting the value of innerHTML lets you easily replace the existing contents of an element with new content. ...
...And 8 more matches
Capabilities, constraints, and settings - Web APIs
aStreamTrack have constrainable properties. Determining if a constraint is supported If you need to know whether or not a given constriant is supported by the user agent, you can find out by calling navigator.mediaDevices.getSupportedConstraints() to get a list of the constrainable properties which the browser knows, like this: let supported = navigator.mediaDevices.getSupportedConstraints(); document.getElementById("frameRateSlider").disabled = !supported["frameRate"]; In this example, the supported constraints are fetched, and a control that lets the user configure the frame rate is disabled if the frameRate constraint isn't supported. How constraints are defined A single constraint is an object whose name matches the constrainable property whose desired value or range of values is being ...
...erenced by videoTrack is updated so that its resolution as closely as possible matches 1920x1080 pixels (1080p high definition). Retrieving current constraints and settings It's important to remember the difference between constraints and settings. Constraints are a way to specify what values you need, want, and are willing to accept for the various constrainable properties (as described in the documentation for MediaTrackConstraints), while settings are the actual values of each constrainable property at the current time. Getting the constraints in effect If at any time you need to fetch the set of constraints that are currently applied to the media, you can get that information by calling MediaStreamTrack.getConstraints(), as shown in the example below. function switchCameras(track, camera)...
...alize the variables which will hold the MediaTrackConstraints objects for the video and audio tracks, as well as the variables which will hold references to the video and audio tracks themselves, to null. let videoConstraints = null; let audioConstraints = null; let audioTrack = null; let videoTrack = null; And we get references to all of the elements we'll need to access. ...
...And 8 more matches
Getting Started - Developer guides
tion needs to check the request's state. If the state has the value of XMLHttpRequest.DONE (corresponding to 4), that means that the full server response was received and it's OK for you to continue processing it. if (httpRequest.readyState === XMLHttpRequest.DONE) { // Everything is good, the response was received. } else { // Not ready yet. } The full list of the readyState values is documented at XMLHTTPRequest.readyState and is as follows: 0 (uninitialized) or (request not initialized) 1 (loading) or (server connection established) 2 (loaded) or (request received) 3 (interactive) or (processing request) 4 (complete) or (request finished and response is ready) Next, check the HTTP response status codes of the HTTP response. The possible codes are listed at the W3C. In the fo...
... have a 404 (Not Found) // or 500 (Internal Server Error) response code. } After checking the state of the request and the HTTP status code of the response, you can do whatever you want with the data the server sent. You have two options to access that data: httpRequest.responseText - returns the server response as a string of text httpRequest.responseXML - returns the response as an XMLDocument object you can traverse with JavaScript DOM functions Note that the steps above are valid only if you used an asynchronous request (the third parameter of open() was unspecified or set to true). If you used a synchronous request you don't need to specify a function, but this is highly discouraged as it makes for an awful user experience. Step 3 - A Simple Example Let's put it all together wit...
... that the steps above are valid only if you used an asynchronous request (the third parameter of open() was unspecified or set to true). If you used a synchronous request you don't need to specify a function, but this is highly discouraged as it makes for an awful user experience. Step 3 - A Simple Example Let's put it all together with a simple HTTP request. ...
...And 8 more matches
Parsing and serializing XML - Developer guides
ontent and convert it into a DOM tree, or, conversely, serialize an existing DOM tree into XML. In this article, we'll look at the objects provided by the web platform to make the common tasks of serializing and parsing XML easy. XMLSerializer Serializes DOM trees, converting them into strings containing XML. DOMParser Constructs a DOM tree by parsing a string containing XML, returning a XMLDocument or Document as appropriate based on the input data. XMLHttpRequest Loads content from a URL; XML content is returned as an XML Document object with a DOM tree built from the XML itself. XPath A technology for creating strings that contain addresses for specific portions of an XML document, and locating XML nodes based on those addresses. Creating an XML document Using one of the following ...
...based on the input data. XMLHttpRequest Loads content from a URL; XML content is returned as an XML Document object with a DOM tree built from the XML itself. XPath A technology for creating strings that contain addresses for specific portions of an XML document, and locating XML nodes based on those addresses. Creating an XML document Using one of the following approaches to create an XML document (which is an instance of Document. ...
... create an XML document (which is an instance of Document. ...
...And 8 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
tion. This table is followed by a list describing each attribute in greater detail, along with which input types they are associated with.Those that are common to most or all input types are defined in greater detail below. Attributes that are unique to particular input types--or attributes which are common to all input types but have special behaviors when used on a given input type--are instead documented on those types' pages. This element includes the global attributes. Those with extra importance as it relates to <input> are highlighted. Attributes for the <input> element include global HTML attributes and: Attribute Type or Types Description accept file Hint for expected file type in file upload controls alt image alt attribute for the image...
...nt for hidden than for other input types. autofocus A Boolean attribute which, if present, indicates that the input should automatically have focus when the page has finished loading (or when the <dialog> containing the element has been displayed). Note: An element with the autofocus attribute may gain focus before the DOMContentLoaded event is fired. No more than one element in the document may have the autofocus attribute. If put on more than one element, the first one with the attribute receives focus. The autofocus attribute cannot be used on inputs of type hidden, since hidden inputs cannot be focused. Warning: Automatically focusing a form control can confuse visually-impaired people using screen-reading technology and people with cognitive impairments. When autofocus is ...
... Note: Although not required by the specification, Firefox will by default persist the dynamic disabled state of an <input> across page loads. Use the autocomplete attribute to control this feature. form A string specifying the <form> element with which the input is associated (that is, its form owner). This string's value, if present, must match the id of a <form> element in the same document. If this attribute isn't specified, the <input> element is associated with the nearest containing form, if any. The form attribute lets you place an input anywhere in the document but have it included with a form elsewhere in the document. Note: An input can only be associated with one form. formaction Valid for the image and submit input types only. See the submit input type for mo...
...And 8 more matches
Standard metadata names - HTML: Hypertext Markup Language
Web › HTML › Element › meta › name
The <meta> element can be used to provide document metadata in terms of name-value pairs, with the name attribute giving the metadata name, and the content attribute giving the value. Standard metadata names defined in the HTML specification The HTML specification defines the following set of standard metadata names: application-name: the name of the application running in the web page. Note: Browsers may use this to identify the application. It is different from the <title> element, which usually contain the application name, but may also contain information like the document name or a status. Simple web pages shouldn't define an application-name. author: the name of the document's author. description: a short and accurate summary of the content of the page. Severa...
... no-referrer-when-downgrade Send the full URL when the destination is at least as secure as the current page (HTTP(S)->HTTPS), but send no referrer when it's less secure (HTTPS->HTTP). ...
...enerator: the identifier of the software that generated the page. keywords: words relevant to the page's content separated by commas. referrer: controls the HTTP Referer header for to requests sent from the document: Values for the content attribute of <meta name="referrer"> no-referrer Do not send a HTTP Referer header. origin Send the origin of the document. no-referrer-when-downgrade Send the full URL when the destination is at least as secure as the current page (HTTP(S)->HTTPS), but send no referrer when it's less secure (HTTPS->HTTP). This is the default behaviour. origin-when-cross-origin Send the full URL (stripped of parameters) for same-origin requests, but only send the origin for other cases. ...
...And 8 more matches
MIME types (IANA media types) - HTTP
It is defined and standardized in IETF's RFC 6838. The Internet Assigned Numbers Authority (IANA) is responsible for all official MIME types, and you can find the most up-to-date and complete list at their Media Types page. Important: Browsers use the MIME type, not the file extension, to determine how to process a URL, so it's important that web servers send the correct MIME type in the response's Content-Type header. ...
...used. MIME types are case-insensitive but are traditionally written in lowercase, with the exception of parameter values, whose case may or may not have specific meaning. Types There are two classes of type: discrete and multipart. Discrete types are types which represent a single file or medium, such as a single text or music file, or a single video. A multipart type is one which represents a document that's comprised of multiple component parts, each of which may have its own individual MIME type; or, a multipart type may encapsulate multiple files being sent together in one transaction. For example, multipart MIME types are used when attaching multiple files to an email. Discrete types The discrete types currently registered with the IANA are: applicationList at IANA Any kind of binary...
...data (or binary data whose true type is unknown) is application/octet-stream. Other common examples include application/pdf, application/pkcs8, and application/zip. audio List at IANA Audio or music data. Examples include audio/mpeg, audio/vorbis. example Reserved for use as a placeholder in examples showing how to use MIME types. These should never be used outside of sample code listings and documentation. example can also be used as a subtype; for instance, in an example related to working with audio on the web, the MIME type audio/example can be used to indicate that the type is a placeholder and should be replaced with an appropriate one when using the code in the real world. font List at IANA Font/typeface data. Common examples include font/woff, font/ttf, and font/otf. image List at I...
...And 8 more matches
Link prefetching FAQ - HTTP
Does prefetching work with HTTPS? Starting in Gecko 1.9.1 (Firefox 3.5), HTTPS content can be prefetched. ...
... Does prefetching work with HTTPS? Starting in Gecko 1.9.1 (Firefox 3.5), HTTPS content can be prefetched. ...
... Does prefetching work with HTTPS? Starting in Gecko 1.9.1 (Firefox 3.5), HTTPS content can be prefetched. ...
...And 8 more matches
Closures - JavaScript
unit: body { font-family: Helvetica, Arial, sans-serif; font-size: 12px; } h1 { font-size: 1.5em; } h2 { font-size: 1.2em; } Such interactive text size buttons can change the font-size property of the body element, and the adjustments are picked up by other elements on the page thanks to the relative units. ...
...n makeSizer(size) { return function() { document.body.style.fontSize = size + 'px'; }; } var size12 = makeSizer(12); var size14 = makeSizer(14); var size16 = makeSizer(16); size12, size14, and size16 are now functions that resize the body text to 12, 14, and 16 pixels, respectively. You can attach them to buttons (in this case hyperlinks) as demonstrated in the following code example. document.getElementById('size-12').onclick = size12; document.getElementById('size-14').onclick = size14; document.getElementById('size-16').onclick = size16; <a href="#" id="size-12">12</a> <a href="#" id="size-14">14</a> <a href="#" id="size-16">16</a> Run the code using JSFiddle. Emulating private methods with closures Languages such as Java allow you to declare methods as private, meaning that t...
...word in ECMAScript 2015, a common problem with closures occurred when you created them inside a loop. To demonstrate, consider the following example code. ...
...And 8 more matches
Same-origin policy - Web security
Definition of an origin Two URLs have the same origin if the protocol, port (if specified), and host are the same for both. You may see this referenced as the "scheme/host/port tuple", or just "tuple". ...
... Definition of an origin Two URLs have the same origin if the protocol, port (if specified), and host are the same for both. You may see this referenced as the "scheme/host/port tuple", or just "tuple". ...
... 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, e...
...And 8 more matches
Using templates and slots - Web Components
ed 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 components. Let's define a web component that uses our template as the content of its shadow DOM. We'...
...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 components. Let's define a web component that uses our template as the content of its shadow DOM. We'll call it <my-paragraph>: customElements.define('my-paragraph', class extends HTMLElement { constructor() { super(); let template = document.getElementById('my-paragraph'); let templateContent = template.content; const shadowRoot = this.attachShadow({mode: 'open'}) .appendChild(templateContent.cloneNode(true)); } } ); The key point to note here is that we append a clone of the template content to the shadow root, created using the Node.cloneNode() method. And because we are appending its contents to a shad...
...ation inside the template in a <style> element, which is then encapsulated inside the custom element. This wouldn't work if we just appended it to the standard DOM. So for example: <template id="my-paragraph"> <style> p { color: white; background-color: #666; padding: 5px; } </style> <p>My paragraph</p> </template> Now we can use it by just adding it to our HTML document: <my-paragraph></my-paragraph> Note: Templates are well-supported in browsers; the Shadow DOM API is supported by default in Firefox (version 63 onwards), Chrome, Opera, Safari, and Edge (starting with version 79). Adding flexibility with slots So far so good, but the element isn't very flexible. We can only display one bit of text inside it, meaning that at the moment it is even less usef...
...And 8 more matches
Content Scripts - Archive of obsolete content
ows the main code and content scripts to communicate with each other This complete add-on illustrates all of these principles. Its "main.js" attaches a content script to the current tab using the tabs module. In this case the content script is passed in as a string. The content script simply replaces the content of the page: // main.js var tabs = require("sdk/tabs"); var contentScriptString = 'document.body.innerHTML = "<h1>this page has been eaten</h1>";' tabs.activeTab.attach({ contentScript: contentScriptString }); The following high-level SDK modules can use content scripts to modify web pages: page-mod: enables you to attach content scripts to web pages that match a specific URL pattern. tabs: exports a Tab object for working with a browser tab. The Tab object includes an attach() ...
...the page in which the menu is invoked. Additionally, some SDK user interface components - panel, sidebar, frame - are specified using HTML, and use separate scripts to interact with this content. In many ways these are like content scripts, but they're not the focus of this article. To learn about how to interact with the content for a given user interface module, please see the module-specific documentation: panel, sidebar, frame. Almost all the examples presented in this guide are available as complete, but minimal, add-ons in the addon-sdk-content-scripts repository on GitHub. Loading content scripts You can load a single script by assigning a string to either the contentScript or the contentScriptFile option. The contentScript option treats the string itself as a script: // main.js var...
...ed in this guide are available as complete, but minimal, add-ons in the addon-sdk-content-scripts repository on GitHub. Loading content scripts You can load a single script by assigning a string to either the contentScript or the contentScriptFile option. The contentScript option treats the string itself as a script: // main.js var pageMod = require("sdk/page-mod"); var contentScriptValue = 'document.body.innerHTML = ' + ' "<h1>Page matches ruleset</h1>";'; pageMod.PageMod({ include: "*.mozilla.org", contentScript: contentScriptValue }); The contentScriptFile option treats the string as a resource:// URL pointing to a script file stored in your add-on's data directory. jpm doesn't make a "data" directory by default, so you must add it and put your content script...
...And 7 more matches
JavaScript Daemons Management - Archive of obsolete content
ript timers (HTML5 standard syntax). ...
...| \*/ /* if (document.all && !window.setTimeout.isPolyfill) { var __nativeST__ = window.setTimeout; window.setTimeout = function (vCallback, nDelay) { var aArgs = Array.prototype.slice.call(arguments, 2); return __nativeST__(vCallback instanceof Function ? function () { vCallback.apply(null, aArgs); } : vCallback, nDelay); }; window.setTimeout.isPolyfill = true; } if (document.all && !window.setInterval.isPolyfill) { var __nativeSI__ = window.setInterval; window.setInterval = function (vCallback, nDelay) { var aArgs = Array.prototype.slice.call(arguments, 2); return __nativeSI__(vCallback instanceof Function ? function () { vCallback.apply(null, aArgs); } : vCallback, nDelay); }; window.setInterval.isPolyfill = true; } */ daemon-safe.js Wh...
...; oLetter.elem.style.top = Math.sin(oLetter.pos) * nDist + "px"; oLetter.elem.style.left = Math.cos(oLetter.pos) * nDist * 5 + "px"; } } function prepare () { // build letters list // http://tyleregeto.com/text-animation-in-javascript this.textContent = ""; aLetters.length = 0; for (var oSpan, oLetter, nLetter = 0, nLen = sText.length; nLetter < nLen; nLetter++) { oSpan = document.createElement("span"); oSpan.textContent = sText[nLetter]; oLetter = { "elem": oSpan, "parent": this }; aLetters.push(oLetter); oLetter.pos = Math.random() * 50; oLetter.elem.style.position = "relative"; this.appendChild(oSpan); } } var nMaxDist = 25, aLetters = [], sText = "Do you feel lucky, punk?", oRecompose = new Daemon(document.createElement("p"), perform, 33,...
...And 7 more matches
The Essentials of an Extension - Archive of obsolete content
e or what skin they are extending. There can be multiple skin and locale entries relating to different skins and locales. The most common case is having one skin entry for the global skin, classic/1.0, and multiple locale entries, one for each translation. Finally, the location is specified. There are some additional options that can be included in the entries of a chrome.manifest file. They are documented in the Chrome Registration page. Notably, we can have entries that are OS-specific. This is important because the appearance of the browser is very different for each operating system. If our extension needed to look differently on different systems, we could change the manifest file so that it looks like this: content xulschoolhello content/ skin xulschoolhello classic/...
...ox, but overlaying the main browser window is the most common case by far. Now let's look at the contents of our XUL file. We'll skip the first few lines because they relate to skin and locale, and we'll cover them later. <overlay id="xulschoolhello-browser-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> The root element in the file is an overlay. ...
... You may have noticed the naming we use on several places, such as the id xulschoolhello-browser-overlay. This is the namespacing standard that we use to avoid conflicts with Firefox and other extensions, as well as making some development tasks easier. ...
...And 7 more matches
A XUL Bestiary - Archive of obsolete content
ake an interface. Menus, toolbars, buttons, and scrollbars are widgets, and so are such general purpose pieces as boxes and 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 co...
...The W3C has standardized on a particular DOM and already has a candidate recommendation for an updated version. This is the DOM that is reflected in XUL and in the Mozilla browser. At the highest level in the tree of nodes that is the DOM sits the window object itself. ...
...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 exposed programmatically. The W3C has standardized on a particular DOM and already has a candidate recommendation for an updated version. This is the DOM that is reflected in XUL and in the Mozilla browser. At the highest level in the tree of nodes that is the DOM sits the window object itself. ...
...And 7 more matches
Using Remote XUL - Archive of obsolete content
lor pickers). XUL is often used by desktop applications like Mozilla but can also be loaded from a web server and rendered inside the content pane of a compatible browser. XUL loaded and rendered in this way is called remote XUL and can be used for basic functions like web site navigation as well as to build sophisticated web-based 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 s...
...ow it, to the .htaccess file in the directory from which the XUL file is served: AddType application/vnd.mozilla.xul+xml .xul Then restart your web server. With PHP you can send the mime-type with the header() function. ...
...l .xul Then restart your web server. With PHP you can send the mime-type with the header() function. <?php header('Content-type: application/vnd.mozilla.xul+xml'); ?> <!-- XUL markup starts here --> Note that you don't need a web server for this tutorial; you can load the document you create on your computer via a "file" URL or the "Open File" function of your browser. Step 1: a basic XUL document The first thing we need to do is create a basic XUL document. <?xml version="1.0"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" /> A XUL document requires only two entities to be valid, an XML processing instruction on the first line that identifies the file as XML, and a window element that defines a XUL application window (or in this case web page). The p...
...And 7 more matches
Reference - Archive of obsolete content
Inheritance and Private Variables The guide section links to an interesting document discussing how to create and use private variables in objects, which is great if you want to protect the various properties within an object from being poked at accidentally. I also just read a document on proper inheritance using apply(). Well if you combine the two, you can have inherited private variables: function MyClass(){ var property = 5; this.tellMe = function(){ return property; } } function MyOtherClass(){ MyClass.apply( this ); } var o = new MyOtherClass; alert( o.tellMe() ); //alerts 5 as you'd expect -- the preceding comment was added by Psygnisfive (talk - contribs) on 22:23, 4 December 2006 Terminology We need a terminology appendix. For example, "script" and "program" ...
...rticular 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 be revised? --Maian 23:43, 21 September 2005 (PDT) I think we need a new section in the reference that specifies the differences between versions, collecting this information into a single location r...
...s. 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. ...
...And 7 more matches
From object to iframe — other embedding technologies - Learn web development
th HTML) and the previous articles in this module. Objective: To learn how to embed items into web pages using <object>, <embed>, and <iframe>, like Flash movies and other webpages. A short history of embedding A long time ago on the Web, it was popular to use frames to create websites -- small parts of a website stored in individual HTML pages. These were embedded in a master document called a frameset, which allowed you to specify the area on the screen that each frame filled, rather like sizing the columns and rows of a table. These were considered the height of coolness in the mid to late 90s, and there was evidence that having a webpage split up into smaller chunks like this was better for download speeds -- especially noticeable with network connections being so slow back...
...ful at the time. They have since fallen out of fashion due to many problems, including accessibility, security, file size, and more; these days most mobile devices don't support such plugins anymore, and desktop support is on the way out. Finally, the <iframe> element appeared (along with other ways of embedding content, such as <canvas>, <video>, etc.) This provides a way to embed an entire web document inside another one, as if it were an <img> or other such element, and is used regularly today. With the history lesson out of the way, let's move on and see how to use some of these. Active learning: classic embedding uses In this article we are going to jump straight into an active learning section, to immediately give you a real idea of just what embedding technologies are useful for. The on...
...%;min-height: 100px;"> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); const output = document.querySelector('.output'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value;...
...And 7 more matches
Choosing the right approach - Learn web development
"callback hell"). Failure callbacks need to be called once for each level of nesting, whereas with promises you can just use a single .catch() block to handle the errors for the entire chain. A...
..."callback hell"). Failure callbacks need to be called once for each level of nesting, whereas with promises you can just use a single .catch() block to handle the errors for the entire chain. Async callbacks just aren't very graceful. Promise callbac...
... very graceful. Promise callbacks are always called in the strict order they are placed in the event queue; async callbacks 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 simult...
...And 7 more matches
Setting up your own test automation environment - Learn web development
Platforms Supported by Selenium for some useful links. Setting up Selenium in Node To start with, set up a new npm project, as discussed in Setting up Node and npm in the last chapter. Call it something different, like selenium-test. Next, we need to install a framework to allow us to work with Selenium from inside Node. We are going to choose selenium's official selenium-webdriver, as the documentation seems fairly up-to-date and it is well-maintained. If you want different options, webdriver.io and nightwatch.js are also good choices. To install selenium-webdriver, run the following command, making sure you are inside your project folder: npm install selenium-webdriver Note: It is still a good idea to follow these steps even if you previously installed selenium-webdriver and downlo...
...); } driver.quit(); }); }); In terminal, make sure you are inside your project folder, then enter the following command: node google_test You should see an instance of Firefox automatically open up! Google should automatically be loaded in a tab, "webdriver" should be entered in the search box, and the search button will be clicked. WebDriver will then wait for 2 seconds; the document title is then accessed, and if it is "webdriver - Google Search", we will return a message to claim the test is passed. WebDriver will then close down the Firefox instance and stop. Testing in multiple browsers at once There is also nothing to stop you running the test on multiple browsers simultaneously. Let's try this! Create another new file inside your project directory called google_tes...
... 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, until = webdriver.until; Next, you need to create a new instance of a dri...
...And 7 more matches
Application cache implementation overview
Channels having that flag set are searching for nsIApplicationCache object prior inspecting normal HTTP cache. nsIApplicationCacheService::ChooseApplicationCache is given the URL the channel is about to load. It synchronously returns an nsIApplicationCache object representing the most recent cache version from the most recent cache group containing the entry under the URL or a matching namespace. ...
...y has not been found, but the URL is falling under one of the NETWORK or FALLBACK namespaces. When matching FALLBACK namespace, the associated fallback entry for it is remembered. The load then continues from the network as a usual load, using HTTP cache. When load of the resource fails fallback steps are performed (see "falling back on a resource load failure" chapter). Associating the top level document with offline cache This happens between document load start and the first sub-resource download start and is not about associating nsIApplicationCache object with the channel, but with the document object the load is performed for. Until steps described further the document doesn't know anything about its appcache. The association happens in nsContentSink::ProcessOfflineManifest() called from the...
... document object the load is performed for. Until steps described further the document doesn't know anything about its appcache. The association happens in nsContentSink::ProcessOfflineManifest() called from the HTML parser every time <html> tag has been parsed. ProcessOfflineManifest is an effective implementation of "cache selection algorithm" as described by the HTML5 spec. For purpose of this documentation it's enough to describe the simplest case ; for complete documentation of the selection algorithm refer to the spec or to the code. ...
...And 7 more matches
Displaying Places information using views
ou may want to use the built-in Places views, which are generic and will save you a lot of time writing basic functionality so that you can focus on building your extension or application. Places provides the following built-in views: Tree Menu Toolbar Instantiating The three built-in views are simply standard XUL elements with a special type attribute whose value is "places". ...
...pt 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 = document.getElementById("mytree"); tree.place = uri; These two examples use the built-in tree view, but the point is to demonstrate the use of the place attribute and property. In this regard the built-in menu and toolbar views are no different. When a view's underlying data changes, the view will automatically update itself so that it displays the new data. This update is handled by logic between the v...
...ng the tree view So you've got a built-in tree view. How do you ask it about the data it displays? First, see nsIPlacesView. Like all Places views, the built-in tree view implements this interface, which provides broad methods such as getting the view's nsINavHistoryResult instance and examining the view's selection. Second, know this: when it comes to trees, "view" is an overloaded word. This document describes Places views. Places views are just XUL elements; the built-in Places tree view is just a tree element whose type attribute is equal to "places", as described above. But recall that all trees--Places view or not--display their data using another kind of view, nsITreeView. The built-in Places tree view therefore has a view of its own, the built-in Places tree view's view. This view is an...
...And 7 more matches
nsIFocusManager
void focusPlugin(in nsIContent aPlugin); Native code only! nsIDOMElement getFocusedElementForWindow(in nsIDOMWindow aWindow, in PRBool aDeep, out nsIDOMWindow aFocusedWindow); PRUint32 getLastFocusMethod(in nsIDOMWi...
... void focusPlugin(in nsIContent aPlugin); Native code only! nsIDOMElement getFocusedElementForWindow(in nsIDOMWindow aWindow, in PRBool aDeep, out nsIDOMWindow aFocusedWindow); PRUint32 getLastFocusMethod(in nsIDOMWindow windo...
... void focusPlugin(in nsIContent aPlugin); Native code only! ...
...And 7 more matches
Index
2 Account Provisioner The Account Provisioner is the dialog that first comes up when starting Thunderbird. ...
...ng and how Thunderbird has handled user requests. 6 Activity Manager interfaces thunderbird This page describes the programmatic interfaces behind the Activity Manager component. The functionality of the component is described on the Activity Manager page, and the Activity Manager examples page has code snippets. See nsIActivityManager.idl and nsIActivity.idl files for source documentation. 7 Address Book Interfaces MailNews, Mozilla, SeaMonkey, thunderbird This page contains a list of the interfaces that you'll will most likely hit when writing patches for the Address Book or writing extensions. The complete list of interfaces for the address book can be found here. Address Book examples show how to perform various tasks and provide code snippets. ...
...view of the related interfaces. See An overview of Thunderbird components for a general description of the Thunderbird user interface and related programmatic interfaces. 9 Address book sync client design by Richard H. Pizzarro <rhp@netscape.com> 10 Autoconfiguration in Thunderbird Administration, enterprise Author: Ben Bucksch Please do not change this document without consulting the author 11 Autoconfig file format No summary! 12 Autoconfig file format definition Please see https://wiki.mozilla.org/Thunderbird:Autoconfiguration:ConfigFileFormat. 13 Autoconfig: How to create a configuration file Autoconfiguration, thunderbird Authoritative definition 14 Autoconfiguration in Thun...
...And 7 more matches
MediaDevices.getUserMedia() - Web APIs
See Security for more information on this and other security issues related to using getUserMedia(). Syntax var promise = navigator.mediaDevices.getUserMedia(constraints); Parameters constraints A MediaStreamConstraints object specifying the types of media to request, along with any requ...
...onstraint property whose string value is the name of a constraint which was impossible to meet, and a message property containing a human-readable string explaining the problem. Because this error can occur even when the user has not yet granted permission to use the underlying device, it can potentially be used as a fingerprinting surface. SecurityError User media support is disabled on the Document on which getUserMedia() was called. The mechanism by which user media support is enabled and disabled is left up to the individual user agent. TypeError The list of constraints specified is empty, or has all constraints set to false. This can also happen if you try to call getUserMedia() in an insecure context, since navigator.mediaDevices is undefined in an insecure context. Privacy and secu...
... is a powerful feature which can only be used in secure contexts; in insecure contexts, navigator.mediaDevices is undefined, preventing access to getUserMedia(). A secure context is, in short, a page loaded using HTTPS or the file:/// URL scheme, or a page loaded from localhost. In addition, user permission is always required to access the user's audio and video inputs. Only a window's top-level document context for a valid origin can even request permission to use getUserMedia(), unless the top-level context expressly grants permission for a given <iframe> to do so using Feature Policy. Otherwise, the user will never even be asked for permission to use the input devices. For additional details on these requirements and rules, how they are reflected in the context in which your code is running, ...
...And 7 more matches
Node.insertBefore() - Web APIs
Web › API › Node › insertBefore
Note: The Node.cloneNode() can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode() will not be automatically kept in sync. ...
... Note: The Node.cloneNode() can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode() will not be automatically kept in sync. ...
...tomatically be removed from its existing parent before appending it to the specified new parent.) This means that a node cannot be in two locations of the document simultaneously. Note: The Node.cloneNode() can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode() will not be automatically kept in sync. If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node. Syntax let insertedNode = parentNode.insertBefore(newNode, referenceNode) insertedNode The node being inserted (the same as newNode) parentNode The parent of the newly inserted node. newNode The node to be inserted. referenceNode The node before which newNode is inserted. ...
...And 7 more matches
Page Visibility API - Web APIs
With tabbed browsing, there is a reasonable chance that any given webpage is in the background and thus not visible to the user. The Page Visibility API provides events you can watch for to know when a document becomes visible or hidden, as well as features to look at the current visibility state of the page. Notes: The Page Visibility API is especially useful for saving resources and improving performance by letting a page avoid performing unnecessary tasks when the document isn't visible. When the user minimizes the window or switches to another tab, the API sends a visibilitychange event to let listeners know the state of the page has changed. You can detect the event and perform some actions or behave differently. For example, if your web app is playing a video, it can pause the video whe...
...eb app is playing a video, it can pause the video when the user puts the tab into the background, and resume playback when the user returns to the tab. The user doesn't lose their place in the video, the video's soundtrack doesn't interfere with audio in the new foreground tab, and the user doesn't miss any of the video in the meantime. Visibility states of an <iframe> are the same as the parent document. Hiding an <iframe> using CSS properties (such as display: none;) doesn't trigger visibility events or change the state of the document contained within the frame. Use cases Let's consider a few use cases for the Page Visibility API. A site has an image carousel that shouldn't advance to the next slide unless the user is viewing the page An application showing a dashboard of information doe...
...y closed. IndexedDB processes are also left unthrottled in order to avoid timeouts. Example View live example (video with sound). ...
...And 7 more matches
Signaling and video calling - Web APIs
ussed elsewhere, in order for two devices on different networks to locate one another. This process is called signaling and involves both devices connecting to a third, mutually agreed-upon server. Through this third server, the two devices can locate one another, and exchange negotiation messages. In this article, we will further enhance the WebSocket chat first created as part of our WebSocket documentation (this article link is forthcoming; it isn't actually online yet) to support opening a two-way video call between users. You can try out this example on Glitch, and you can remix the example to experiment with it as well. You can also look at the full project on GitHub. Note: If you try out the example on Glitch, please note that any changes made to the code will immediately reset any conne...
... UI to start a call The code which handles the "userlist" message calls handleUserlistMsg(). Here we set up the handler for each connected user in the user list displayed to the left of the chat panel. This function receives a message object whose users property is an array of strings specifying the user names of every connected user. ...
...eft of the chat panel. This function receives a message object whose users property is an array of strings specifying the user names of every connected user. function handleUserlistMsg(msg) { var i; var listElem = document.querySelector(".userlistbox"); while (listElem.firstChild) { listElem.removeChild(listElem.firstChild); } msg.users.forEach(function(username) { var item = document.createElement("li"); item.appendChild(document.createTextNode(username)); item.addEventListener("click", invite, false); listElem.appendChild(item); }); } After getting a reference to the <ul> which contains the list of user names into the variable listElem, we empty the list by removing each of its child elements. Note: Obviously, it would be more efficient to update the list b...
...And 7 more matches
Using the Web Animations API - Web APIs
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. ...
... document.getElementById("alice").animate( aliceTumbling, aliceTiming ) And boom: the animation starts playing (see the finished version on Codepen). The animate() method can be called on any DOM element that could be animated with CSS. And it can be written in several ways. ...
...) translate3D(-50%, -50%, 0)', color: '#000' }, { color: '#431236', offset: 0.3}, { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' } ], { duration: 3000, iterations: Infinity } ); What's more, if we only wanted to specify the duration of the animation and not its iterations (by default, animations iterate once), we could pass in the milliseconds alone: document.getElementById("alice").animate( [ { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' }, { color: '#431236', offset: 0.3}, { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' } ], 3000); Controlling playback with play(), pause(), reverse(), and updatePlaybackRate() While we can write CSS Animations with the Web Animations API, where the API re...
...And 7 more matches
Using Web Workers - Web APIs
orker context is represented by a DedicatedWorkerGlobalScope object in the case of dedicated workers (standard workers that are utilized by a single script; shared workers use SharedWorkerGlobalScope). A dedicated worker is only accessible from the script that first spawned it, whereas shared workers can be accessed from multiple scripts. Note: See The Web Workers API landing page for reference documentation on workers and additional guides. You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the window object. But you can use a large number of items available under window, including WebSockets, and data storage mechanisms like IndexedDB. See Fun...
... the differences between dedicated and shared workers. Note that in this example we have two HTML pages, each with JavaScript applied that uses the same single worker file. Note: If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host, and port). Note: In Firefox, shared workers cannot be shared between documents loaded in private and non-private windows (bug 1177621). Spawning a shared worker Spawning a new shared worker is pretty much the same as with a dedicated worker, but with a different constructor name (see index.html and index2.html) -- each one has to spin up the worker using code like the following: var myWorker = new SharedWorker('worker.js'); One big difference is that with a shared wor...
...tion points with other threads, it's actually very hard to cause concurrency problems. There's no access to non-threadsafe components or the DOM. And you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code. Content security policy Workers are considered to have their own execution context, distinct from the document that created them. For this reason they are, in general, not governed by the content security policy of the document (or parent worker) that created them. So for example, suppose a document is served with the following header: Content-Security-Policy: script-src 'self' Among other things, this will prevent any scripts it includes from using eval(). However, if the script constructs a worker, co...
...And 7 more matches
CSS Grid Layout and Accessibility - CSS: Cascading Style Sheets
-up, often creating accessibility issues as it did so. In order to lay the design out in the table we often broke up the content in ways that made no sense at all when read out by a screen reader for example. In moving to CSS we often spoke about CSS for layout enabling a separation of content and markup and presentation. The ultimate aim being that we could create a semantic and well structured document, then apply CSS to create the layout we desired. Sites such as the CSS Zen Garden showcased this ability. The CSS Zen Garden challenged us to take identical markup and create a unique design using CSS. CSS Grid Layout does not have the same issues that tables did, our grid structure is defined in CSS rather than in the mark-up. If we need to add an element we can use something with no semantic m...
...ng line-based placement of grid template areas, without considering their location in the source. The specification includes a section that covers Reordering and Accessibility. In the introduction to that section are details of what the specification expects browsers to do when the content is visually reordered using Grid Layout. Grid layout gives authors great powers of rearrangement over the document. However, these are not a substitute for correct ordering of the document source. The order property and grid placement do not affect ordering in non-visual media (such as speech). Likewise, rearranging grid items visually does not affect the default traversal order of sequential navigation modes (such as cycling through links, see e.g. tabindex HTML5). If you reorder things visually using grid...
...rder things visually using grid layout, this will not change how the items are ordered if the content is being read out by a screen reader, or other text to speech user agent. In addition, the reordering will not change tab order. This means that someone navigating using the keyboard could be tabbing through links on your site and suddenly find themselves jumping from the top to the bottom of the document due to a reordered item being next in line. The specification warns authors (the CSSWG term for web developers) not to do this reordering. Authors must use order and the grid-placement properties only for visual, not logical, reordering of content. Style sheets that use these features to perform logical reordering are non-conforming. What does this mean for designing with grid layout in prac...
...And 7 more matches
Audio and Video Delivery - Developer guides
general workflow is usually something like this: Check what format the browser supports via feature detection (usually a choice of two, as stated above). If the browser doesn't support playback of any of the provided formats natively, either present a still image or use a fallback technology to present the video. Identify how you want to play/instantiate the media (e.g. a <video> element, or document.createElement('video') perhaps?) Deliver the media file to the player. HTML Audio <audio controls preload="auto"> <source src="audiofile.mp3" type="audio/mpeg"> <!-- fallback for browsers that don't support mp3 --> <source src="audiofile.ogg" type="audio/ogg"> <!-- fallback for browsers that don't support audio tag --> <a href="audiofile.mp3">download audio</a> </audio> The code ...
...pplication/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. ...
... 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. JavaScript Video var myVideo = document.createElement('video'); if (myVideo.canPlayType('video/mp4')) { myVideo.setAttribute('src','videofile.mp4'); } else if (myVideo.canPlayType('video/webm')) { myVideo.setAttribute('src','videofile.webm'); } myVideo.width = 480; myVideo.height = 320; We set the source of the video depending on the type of video file the browser supports we then set the width and height of the video. Web Audi...
...And 7 more matches
<input type="date"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › date
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-06-01 (June 1st, 2017). It then reads that value back in string and number formats. Additional attri...
... detect whether the browser supports <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 picker and show the fallback (<select>) instead. ...
...te 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 picker and show the fallback (<select>) instead. ...
...And 7 more matches
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
This can be done via XMLHttpRequest or XMLDocument.load(). ...
...ough the XSLTProcessor object. Once instantiated, an XSLTProcessor has an XSLTProcessor.importStylesheet() method that takes as an argument the XSLT stylesheet to be used in the transformation. The stylesheet has to be passed in as an XML document, which means that the .xsl file has to be loaded by the page before calling XSLTProcessor.importStylesheet(). This can be done via XMLHttpRequest or XMLDocument.load(). Figure 1 : Instantiating an XSLTProcessor var xsltProcessor = new XSLTProcessor(); // Load the xsl file using synchronous (third param is set to false) XMLHttpRequest var myXMLHTTPRequest = new XMLHttpRequest(); myXMLHTTPRequest.open("GET", "example.xsl", false); myXMLHTTPRequest.send(null); var xslRef = myXMLHTTPRequest.responseXML; // Finally import the .xsl xsltPro...
...Assuming that the DOM to be processed is contained by an element with the id example, that DOM can be "clone...
...And 7 more matches
window/utils - Archive of obsolete content
to take care not to store any user data derived from private browser windows. The exception is the windows() function which returns an array of currently opened windows. Private windows will not be included in this list if your add-on has not opted into private browsing. To learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module. Globals Functions getMostRecentBrowserWindow() Get the topmost browser window, as an nsIDOMWindow instance. Returns nsIDOMWindow: the topmost browser window. getInnerId(window) Returns the ID of the specified window's current inner window. This function wraps nsIDOMWindowUtils.currentInnerWindowID. Parameters window : nsIDOMWindow The window whose ...
...ow Returns nsIDOMWindow getWindowDocShell(window) Returns the nsIDocShell for the tabbrowser element. Parameters window : nsIDOMWindow Returns nsIDocShell getWindowLoadingContext(window) Returns the nsILoadContext. Parameters window : nsIDOMWindow Returns nsILoadContext open(uri, options) This function is used to open top level (application) windows. It takes the uri of the window document as its first argument and an optional hash of options as its second argument. var { open } = require('sdk/window/utils'); var window = open('data:text/html,Hello Window'); This function wraps nsIWindowWatcher.openWindow. Parameters uri : string URI of the document to be loaded into the window. Only chrome, resource, and data schemes are accepted. options : object Options for the function,...
...wing properties: Name Type parent nsIDOMWindow Parent for the new window. Optional, defaults to null. name string Name that is assigned to the window. Optional, defaults to null. features object Map of features to set for the window, defined like this: { width: 10, height: 15, chrome: true }. See the window.open features documentation for more details. Optional, defaults to an empty map: {}. var { open } = require('sdk/window/utils'); var window = open('data:text/html,Hello Window', { name: 'jetpack window', features: { width: 200, height: 50, popup: true } }); args object Extra argument(s) to be attached to the new window as the window.arguments property. Returns n...
...And 6 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
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. ...
...icient development Before you get to work developing your extension, you'll want to change some of your Firefox preferences. This isn't a requirement for extension development, but I recommend it as a way to work more efficiently. Preference Description Value nglayout.debug.disable_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. Refer to the "JavaScript debugging methods" sidebar. True javascript.options.showInCons...
...XPCOM functions (Figure 1). Extension/ chrome manifest Chrome/ #registered in the chrome content package #Run with privileges locale package skin package Figure 1: Chrome packages and chrome registration (FIXME: Not really explicit and not a Figure) Cross-package overlays The "overlay" technique introduced in Chapter 3 required the use of the xul-overlay instruction in the XUL document that is the overlay target. It is also possible to coerce an overlay without using the xul-overlay instruction in the XUL document--this is called a "cross-package overlay" (Figure 2). In fact, you need to use cross-package overlays to append buttons or menus to the Firefox browser window. Use the chrome manifest to invoke a cross-package overlay. Normal overlay: Adding the xul-overlay instructi...
...And 6 more matches
Custom XUL Elements with XBL - Archive of obsolete content
The element that the binding is attached to, called the bound element, acquires the new behavior specified by the binding. Taken from the XBL page. This somewhat cryptic explanation describes a very simple concept: with XBL you can create your own custom elements. XBL is heavily used in XUL, but in theory it could be applied to any XML language. ...
... you look at file bindingDialog.xul, you'll see that the CSS stylesheet is included, which means that the xshelloperson tag can now be used just like any XUL tag. In this case we're adding the "Persons" dynamically, so you'll have to look into the JS file to see how xshelloperson elements are created and added to the DOM just like any other. addPerson : function(aEvent) { // ... let person = document.createElement("xshelloperson"); // ... person.setAttribute("name", name); person.setAttribute("greeting", greeting); // ... personList.appendChild(person); // ... }, This is where the advantage of XBL is obvious: we only need to create a single node and set some attributes. We didn't need to create a whole XUL structure that would require around 7 nodes every time a "Person" is crea...
...unit. As a bonus, you should look into the usage of nsIFilePicker to open a "Open File" dialog in a way that looks native for all systems. Now let's look into the XBL file, person.xml. <bindings xmlns="http://www.mozilla.org/xbl" xmlns:xbl="http://www.mozilla.org/xbl" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> The bindings element is the root of the document, and it's a container for binding elements. Notice how the default namespace for the document is XBL, and the XUL namespace is defined as "xul". You'll need to keep this in mind when defining the content of the binding, because weird things can happen if you don't add "xul:" to your content nodes. <binding id="person"> In general, you should only have one binding per file. Bindings tend to ...
...And 6 more matches
Index of archived content - Archive of obsolete content
between privileged and non-privileged pages Jetpack Processes Legacy Add-ons Legacy extensions for Firefox for Android API Accounts.jsm BrowserApp addTab closeTab deck getBrowserForDocument getBrowserForWindow getTabForBrowser getTabForId getTabForWindow loadURI quit selectTab tabs HelperApps.jsm Home.jsm banner panels ...
...tion (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 Performance best practices in extensions ...
... Updating addons broken by private browsing changes Using Dependent Libraries In Extension Components Using the Stylesheet Service bookmarks.export() bookmarks.import() Adding preferences to an extension An Interview With Douglas Bowman of Wired News Archived Mozilla and build documentation ActiveX Control for Hosting Netscape Plug-ins in IE Archived SpiderMonkey docs File object open Merging TraceMonkey Repo SpiderMonkey coding conventions Autodial for Windows NT Automated testi...
...And 6 more matches
Mozilla Crypto FAQ - Archive of obsolete content
If you wish to develop and distribute cryptographic software, particularly for commercial sale or distribution, then you should consult an attorney with expertise in the particular laws and regulations that apply in your jurisdiction. I've updated this version of the Mozilla Crypto FAQ to discuss the situation now that the RSA public key algorithm is in the public domain and a full open source crypto implementation is being added to the Mozilla code base. ...
...directly for more information concerning their plans. See the Open Directory references for general PGP information, including contact information for companies and independent developers producing PGP implementations. ...
...format of the PSM key and certificate database, so that other software can reuse existing user keys and certificates managed by PSM? Yes, documentation of the database format is available; however we cannot guarantee that the format of the database will remain unchanged in the future. The initial release of SSL, S/MIME, and general PKI source code from iPlanet E-Commerce Solutions includes some documentation on the format of the key and certificate database. As with Mozilla documentation in general, mozilla.org will be glad to host any other documentation contributed to describe database formats, APIs, and other technical aspects of the released SSL, S/MIME, and PKI source code. However, as with APIs internal to Mozilla modules, mozilla.org cannot guarantee that the format of the key and certif...
...And 6 more matches
The Implementation of the Application Object Model - Archive of obsolete content
This section makes a technical argument both for having XUL in the first place and for using RDF as the underlying implementation of XUL's content model. ...
...This section makes a technical argument both for having XUL in the first place and for using RDF as the underlying implementation of XUL's content model. ...
..., transformed into something far worse than a demon. It became a markup language. XUL stands for "extensible user interface language". It is an XML-based language for describing the contents of windows and dialogs. XUL has language constructs for all of the typical dialog controls, as well as for widgets like toolbars, trees, progress bars, and menus. Where HTML describes the contents of a single document, XUL describes the contents of an entire window (which could itself contain multiple HTML documents). The HTML content tree structure for a single document is represented as a set of objects that can be accessed and manipulated. This is referred to as the DOM (document object model). In a similar fashion, XUL's content tree for a single window is represented as a set of objects that can be access...
...And 6 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
d JavaScript to include some of the most desired capability such as database access, remote web requests, and XML processing. We'll start by taking a look at querying a SQL database. This first example we'll demonstrate is querying a mySQL database for some employee contact information. It is assumed that you have already downloaded, extracted, and consumed the necessary documentation to get up and running with some basic Rhino scripts. If you don't already have it, you'll need to also download the JDBC driver for mySQL, extract the class files, and include the path in your CLASSPATH environment variable. The code in Listing 1 is a sample JavaScript script which incorporates Java classes to handle the database query. Listing 1 - Querying a mySQL d...
...is used to render the form and the out-logger will be used as a log display as each comment is added. The completed user interface is shown in Figure 1. Figure 1 - The user interface Server-Side DOM Processing Another powerful concept of Jaxer is the ability to access the DOM server-side with JavaScript. ...
...other powerful concept of Jaxer is the ability to access the DOM server-side with JavaScript. This gives you added control to interrogate and manage the document structure before it's pushed to the client. Listing 7 contains the code which demonstrates this concept. Listing 7 - Manipulating the DOM server-side <script runat="server"> window.onserverload = function() { document.getElementById( "out-logger" ).innerHTML = Jaxer.File.read( "dump.txt" ); } </script> The code in listing 7 is executed server-side and takes advantage of the onserverload event which ensures that we have a complete DOM before trying to access it. This code is simple in that it updates the innerHTML of the logging div with the contents of a text file. The contents of thi...
...And 6 more matches
The Business Benefits of Web Standards - Archive of obsolete content
Web Standards. This article discusses how adhering to web standards, and leaving behind proprietary markup and technologies, can contribute to a company's business goals. Site Wide Consistent Look and Feel By separating structure (or content) from presentation, web designers have a lot to gain. Specifically, presentation is defined using layout-oriented CSS language. Storing CSS in a separate document (aka style sheet) and applying it to a set of HTML documents permits a complete change of presentation for all these documents in a snap. Strict HTML (as opposed to the often-used transitional HTML markup), forces the designer not to use presentation tags in the HTML documents, naturally enforcing the separation of content from presentation. By locating all the style and design issues in one doc...
...savings in bandwidth are huge. Improve Search Engine Optimization Without Costs Being well-placed in search engines is one of the hardest challenges faced by webmasters. In this case, every bit helps. By using semantic markup we greatly assist the Search Engines in their indexing process. These things come naturally to Standards developers without additional effort, time or thought. All their documents are properly marked up at the outset. The number of sites which do not include proper titles and descriptions in the meta is surprising. A lot of other sites would greatly increase their SEO 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...
...Using CSS to render titles instead of graphics also helps in this regard. There are very significant differences in how search engines operate. ...
...And 6 more matches
HTML: A good basis for accessibility - Learn web development
times. This article looks in detail at how HTML can be used to ensure maximum accessibility. Prerequisites: Basic computer literacy, a basic understanding of HTML (see Introduction to HTML), and an understanding of what accessibility is. Objective: To gain familiarity with the features of HTML that have accessibility benefits and how to use them appropriately in your web documents. HTML and accessibility 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 us...
...elop with -- as mentioned above, you get some functionality for free, plus it is arguably easier to understand. Better on mobile -- semantic HTML is arguably lighter in file size than non-semantic spaghetti code, and easier to make responsive. Good for SEO -- search engines give more importance to keywords inside headings, links, etc. than keywords included in non-semantic <div>s, etc., so your documents will be more findable by customers. Let's get on and look at accessible HTML in more detail. Note: It is a good idea to have a screen reader set up on your local computer so that you can do some testing of the examples shown below. See our Screen readers guide for more details. Good semantics We've already talked about the importance of proper semantics, and why we should use the right HT...
...ol. The goal isn't "all or nothing." However, -- every improvement you can make will help the cause of accessibility. Text content One of the best accessibility aids a screen reader user can have is an excellent content structure with headings, paragraphs, lists, etc. An excellent semantic example might look something like the following: <h1>My heading</h1> <p>This is the first section of my document.</p> <p>I'll add another paragraph here too.</p> <ol> <li>Here is</li> <li>a list for</li> <li>you to read</li> </ol> <h2>My subheading</h2> <p>This is the first subsection of my document. I'd love people to be able to find this content!</p> <h2>My 2nd subheading</h2> <p>This is the second subsection of my content. I think is more interesting than the last one.</p> We've prepared a v...
...And 6 more matches
HTML: A good basis for accessibility - Learn web development
times. This article looks in detail at how HTML can be used to ensure maximum accessibility. Prerequisites: Basic computer literacy, a basic understanding of HTML (see Introduction to HTML), and an understanding of what accessibility is. Objective: To gain familiarity with the features of HTML that have accessibility benefits and how to use them appropriately in your web documents. HTML and accessibility 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 us...
...elop with -- as mentioned above, you get some functionality for free, plus it is arguably easier to understand. Better on mobile -- semantic HTML is arguably lighter in file size than non-semantic spaghetti code, and easier to make responsive. Good for SEO -- search engines give more importance to keywords inside headings, links, etc. than keywords included in non-semantic <div>s, etc., so your documents will be more findable by customers. Let's get on and look at accessible HTML in more detail. Note: It is a good idea to have a screen reader set up on your local computer so that you can do some testing of the examples shown below. See our Screen readers guide for more details. Good semantics We've already talked about the importance of proper semantics, and why we should use the right HT...
...ol. The goal isn't "all or nothing." However, -- every improvement you can make will help the cause of accessibility. Text content One of the best accessibility aids a screen reader user can have is an excellent content structure with headings, paragraphs, lists, etc. An excellent semantic example might look something like the following: <h1>My heading</h1> <p>This is the first section of my document.</p> <p>I'll add another paragraph here too.</p> <ol> <li>Here is</li> <li>a list for</li> <li>you to read</li> </ol> <h2>My subheading</h2> <p>This is the first subsection of my document. I'd love people to be able to find this content!</p> <h2>My 2nd subheading</h2> <p>This is the second subsection of my content. I think is more interesting than the last one.</p> We've prepared a v...
...And 6 more matches
Pseudo-classes and pseudo-elements - Learn web development
SS works (study CSS first steps.) Objective: To learn about the pseudo-class and pseudo-element selectors. What is a pseudo-class? A pseudo-class is a selector that selects elements that are in a specific state, e.g. they are the first element of their type, or they are being hovered over by the mouse pointer. They tend to act as if you had applied a class to some part of your document, often helping you cut down on excess classes in your markup, and giving you more flexible, maintainable code. Pseudo-classes are keywords that start with a colon: :pseudo-class-name Simple pseudo-class example Let's look at a simple example. If we wanted to make the first paragraph in an article larger and bold, we could add a class to that paragraph and then add CSS to that class, as shown ...
...e keywords that start with a colon: :pseudo-class-name Simple pseudo-class example Let's look at a simple example. If we wanted to make the first paragraph in an article larger and bold, we could add a class to that paragraph and then add CSS to that class, as shown in the first example below: However, this could be annoying to maintain -- what if a new paragraph got added to the top of the document? We'd need to move the class over to the new paragraph. Instead of adding the class, we could use the :first-child pseudo-class selector -- this will always target the first child element in the article, and we will no longer need to edit the HTML (this may not always be possible anyway, maybe due to it being generated by a CMS.) All pseudo-classes behave in this same kind of way. They target ...
...ve the class over to the new paragraph. Instead of adding the class, we could use the :first-child pseudo-class selector -- this will always target the first child element in the article, and we will no longer need to edit the HTML (this may not always be possible anyway, maybe due to it being generated by a CMS.) All pseudo-classes behave in this same kind of way. They target some bit of your document that is in a certain state, behaving as if you had added a class into your HTML. Take a look at some other examples on MDN: :last-child :only-child :invalid Note: It is valid to write pseudo-classes and elements without any element selector preceding them. In the example above, you could write :first-child and the rule would apply to any element that is the first child of an <article> ele...
...And 6 more matches
JavaScript basics - Learn web development
.js, and save it. In your index.html file, enter this code on a new line, just before the closing </body> tag: <script src="scripts/main.js"></script> This is doing the same job as the <link> element for CSS. It applies the JavaScript to the page, so it can have an effect on the HTML (along with the CSS, and anything else on the page). Add this code to the main.js file: const myHeading = document.querySelector('h1'); myHeading.textContent = 'Hello world!'; Make sure the HTML and JavaScript files are saved. Then load index.html in your browser. You should see something like this: Note: The reason the instructions (above) place the <script> element near the bottom of the HTML file is that the browser reads code in the order it appears in the file. If the JavaScript loads first and it...
...and then store it in a variable called myHeading. This is similar to what we did using CSS selectors. When you want to do something to an element, you need to select it first. Following that, the code set the value of the myHeading variable's textContent property (which represents the content of the heading) to Hello world!. Note: Both of the features you used in this exercise are parts of the Document Object Model (DOM) API, which has the capability to manipulate documents. Language basics crash course To give you a better understanding of how JavaScript works, let's explain some of the core features of the language. It's worth noting that these features are common to all programming languages. If you master these fundamentals, you have a head start on coding in other languages too! Impor...
...e; Array This is a structure that allows you to store multiple values in a single reference. let myVariable = [1,'Bob','Steve',10]; Refer to each member of the array like this: myVariable[0], myVariable[1], etc. Object This can be anything. Everything in JavaScript is an object, and can be stored in a variable. Keep this in mind as you learn. let myVariable = document.querySelector('h1'); All of the above examples too. So why do we need variables? Variables are necessary to do anything interesting in programming. If values couldn't change, then you couldn't do anything dynamic, like personalize a greeting message or change an image displayed in an image gallery. Comments Comments are snippets of text that can be added along with code. The browser ...
...And 6 more matches
Getting started with HTML - Learn web development
rea> <div class="controls"> <input id="reset" type="button" value="Reset" /> <input id="solution" type="button" value="Show solution" /> </div> html { font-family: 'Open Sans Light',Helvetica,Arial,sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; sol...
... Block-level elements are usually structural elements on the page. For example, a block-level element might represent headings, paragraphs, lists, navigation menus, or footers. A block-level element wouldn't be nested inside an inline element, but it might be nested inside another block-level element. Inline elements are contained within block-level elements, and surround only small parts of the document's content. (not entire paragraphs or groupings of content) An inline element will not cause a new line to appear in the document. It is typically used with text. For example, as an <a> element (hyperlink) or emphasis elements such as <em> or <strong>. Consider the following example: <em>first</em><em>second</em><em>third</em> <p>fourth</p><p>fifth</p><p>sixth</p> <em> is an inline element. ...
...HTML5 dropped these terms was to prevent this rather common confusion. Note: Find useful reference pages that include lists of block and inline elements. See Block-level elements and Inline elements. Empty elements Not all elements follow the pattern of an opening tag, content, and a closing tag. Some elements consist of a single tag, which is typically used to insert/embed something in the document. For example, the <img> element embeds an image file onto a page: <img src="https://udn.realityripple.com/samples/d5/2be21e0477.png"> This would output the following: Note: Empty elements are sometimes called void elements. Attributes Elements can also have attributes. Attributes look like this: Attributes contain extra information about the element that won't appear in the content. I...
...And 6 more matches
Making asynchronous programming easier with async and await - Learn web development
and look at a real example. ...
...sync/await Let's look back at a simple fetch example that we saw in the previous article: fetch('coffee.jpg') .then(response => { if (!response.ok) { throw new Error(`HTTP error! ...
...erstanding of promises and how they work, but let's convert this to use async/await to see how much simpler it makes things: async function myFetch() { let response = await fetch('coffee.jpg'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { let myBlob = await response.blob(); let objectURL = URL.createObjectURL(myBlob); let image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); } } myFetch() .catch(e => { console.log('There has been a problem with your fetch operation: ' + e.message); }); It makes code much simpler and easier to understand -- no more .then() blocks everywhere! Since an async keyword turns a function into a promise, you could refactor your code to use a hybrid a...
...And 6 more matches
Introduction to web APIs - Learn web development
developer's code. What can APIs do? There are a huge number of APIs available in modern browsers that allow you to do a wide variety of things in your code. You can see this by taking a look at the MDN APIs index page. Common browser APIs In particular, the most common categories of browser APIs you'll use (and which we'll cover in this module in greater detail) are: APIs for manipulating documents loaded into the browser. The most obvious example is the DOM (Document Object Model) API, which allows you to manipulate HTML and CSS -- creating, removing and changing HTML, dynamically applying new styles to your page, etc. Every time you see a popup window appear on a page or some new content displayed, for example, that's the DOM in action. Find out more about these types of API in Manipulat...
...aded into the browser. The most obvious example is the DOM (Document Object Model) API, which allows you to manipulate HTML and CSS -- creating, removing and changing HTML, dynamically applying new styles to your page, etc. Every time you see a popup window appear on a page or some new content displayed, for example, that's the DOM in action. Find out more about these types of API in Manipulating documents. APIs that fetch data from the server to update small sections of a webpage on their own are very commonly used. This seemingly small detail has had a huge impact on the performance and behaviour of sites -- if you just need to update a stock listing or list of available new stories, doing it instantly without having to reload the whole entire page from the server can make the site or app feel ...
...udioContext = window.AudioContext || window.webkitAudioContext; const audioCtx = new AudioContext(); Next, we create constants that store references to our <audio>, <button>, and <input> elements, and use the AudioContext.createMediaElementSource() method to create a MediaElementAudioSourceNode representing the source of our audio -- the <audio> element will be played from: const audioElement = document.querySelector('audio'); const playBtn = document.querySelector('button'); const volumeSlider = document.querySelector('.volume'); const audioSource = audioCtx.createMediaElementSource(audioElement); Next up we include a couple of event handlers that serve to toggle between play and pause when the button is pressed and reset the display back to the beginning when the song has finished playing: ...
...And 6 more matches
Creating reftest-based unit tests
now, automation currently only runs layout/reftests/reftest-sanity/reftest.list! If you try to run the full suite, you may experience stalls or other issues. Creating reftest-based unit tests Your first reftest It is a silly example, but this will step you through creating your first reftest. Step 1 For now you must check out and build the browser in order to run the tests. See the Build Documentation for details on doing that. Sorry about this, but the released builds and the nightly builds are built with the "--disable-tests" option and reftest will not work - see bug 369809. Step 2 Open a terminal window. Create a directory (inside Firefox's source code tree) and make that your current directory (i.e. move to that directory). Step 3 Create a file named foo.html with the following: ...
...ng chrome only pieces of UI. You can accomplish this by either: Rewrite them as Mochitests. The helper functions snapshotWindow and compareSnapshots are available in testing/mochitest/tests/SimpleTest/WindowSnapshot.js. Register them in the chrome package in layout/tools/reftest/jar.mn, and reference the chrome URIs in the manifest file (see an example). Testing invalidation Testing that a document displays correctly once it has loaded is only one part of testing rendering. Another part is testing invalidation - testing that when a document is changed after it has finished loading and displaying, that the browser correctly "invalidates" the parts of the screen that should change so that the screen displays the correct output the next time it is repainted. Invalidation tests check both that ...
...t has loaded is only one part of testing rendering. Another part is testing invalidation - testing that when a document is changed after it has finished loading and displaying, that the browser correctly "invalidates" the parts of the screen that should change so that the screen displays the correct output the next time it is repainted. Invalidation tests check both that the internal state of the document has been updated correctly, and that the browser then correctly invalidates and repaints the appropriate parts of the screen. ...
...And 6 more matches
Storage access policy: Block cookies from trackers
designed as an alternative to the older cookie policies, which have been available in Firefox for many years. This policy protects against cross-site tracking while minimizing the site breakage associated with traditional cookie blocking. This article explains how the policy works and how you can test it. Testing in Firefox This cookie policy has been available in Firefox since version 63. This documentation describes the policy that we intend to ship to Firefox Release users, but may not match what is implemented in the current Release version of Firefox. That's because we document new aspects of the policy as soon as they land in Firefox Nightly, our pre-release channel. Firefox Nightly may also contain experimental features that we don't yet plan to ship to Release users; experimental feature...
... We recommend sites test with Firefox Nightly, as this includes the newest version of our protections. ...
...ly may include additional protections that end up getting removed or changed before they reach our Release users. We'll keep this page updated with the newest information as we strengthen our protections. These protections are on by default in Nightly. The cookie policy can be enabled in other versions of Firefox through the Content Blocking settings (these steps will vary by version; the linked documentation includes a dropdown to select the appropriate Firefox version). Report Broken Sites If you find a website broken as a result of this change, file a bug under the Tracking Protection component within the Firefox product on Bugzilla. Alternatively you can report broken sites directly in Firefox by clicking "Report a Problem" in the Content Blocking section of the Control Center (this shortcu...
...And 6 more matches
MozScrolledAreaChanged
This event, introduced in Gecko 1.9.2, is fired whenever either or both of these values change. ...
...This event, introduced in Gecko 1.9.2, is fired whenever either or both of these values change. ...
...This event, introduced in Gecko 1.9.2, is fired whenever either or both of these values change. ...
...And 6 more matches
Introduction to Layout in Mozilla
Overview Basic data flow Key data structures Detailed walk-through Incrementalism Future tech-talks Wrap-up, Q&A Basic Data Flow Source document arrives via network APIs Incrementally "pumped" through the single-threaded layout engine Parse, compute style, render; repeat CSS used for rendering all content Content theoretically separate from "presentation" Key Data Structures Content node Elements, attributes, leaves DOM Frame Rectangular formatting primitive Geometric information [0..n] per content node 2nd thru nth are "continuations" Style context Non-geometric information May be shared by adjacent frames Reference counted, owned by frame View ...
... May not be directly manipulated Detailed Walk-Through Setting up Content model construction Frame construction Style ...
...y Frames own the style contexts, views, widgets Presentation has media type, dimensions, etc. May not be directly manipulated Detailed Walk-Through Setting up Content model construction Frame construction Style resolution Reflow Painting Setting Up Assume basic knowledge of embedding and network APIs (doc shell, streams) Content DLL auto-registers a Document Loader Factory (DLF) @mozilla.org/content-viewer-factory/view;1?type=text/html All MIME types mapped to the same class, nsContentDLF nsDocShell Receives inbound content via nsDSURIContentListener Invokes nsIDLF::CreateInstance, passes MIME type to DLF nsContentDLF Creates a nsHTMLDocument object, invokes StartDocumentLoad. ...
...And 6 more matches
CustomizableUI.jsm
ableUI assumes that each area it is told about is present in every browser window. CustomizableUI is aware of two types of areas: toolbars and the menu panel. Areas are registered using the registerArea method and unregistered using the unregisterArea method. When a customizable toolbar's XBL binding is constructed (generally, that is when a <toolbar customizable="true"/> node is appended to the document and isn't invisible), the binding will call into CustomizableUI and register the toolbar's node as being one of the concrete instances of its area. For each area, CustomizableUI keeps track of a list of the widgets they contain, generally refered to as 'placements'. This is analogous to the old currentset attribute. If consumers make a change to the placements in an area, CustomizableUI will upd...
... been added to either its default area or the area in which it was placed previously. If the widget has no default area and/or it has never been placed anywhere, aArea may be null. Only fired for API-based widgets. onWidgetDestroyed(aWidgetId) Fired when widgets are destroyed. aWidgetId is the widget that is being destroyed. Only fired for API-based widgets. onWidgetInstanceRemoved(aWidgetId, aDocument) Fired when a window is unloaded and a widget's instance is destroyed because of this. aWidgetId is the widget whose instance is being destroyed, aDocument the document in which this is happening. Only fired for API-based widgets. onWidgetDrag(aWidgetId, aArea) Fired both when and after customize mode drag handling system tries to determine the width and height of widget aWidgetId when dragged...
...rs should ensure that NO MATTER WHAT HAPPENS they call endBatchUpdate once for each call to beginBatchUpdate, even if there are exceptions in the code in the batch update. Otherwise, for the duration of the Firefox session, customization state is never saved. Typically, you would do this using a try...finally block wrapped around your insertion code. endBatchUpdate() End a batch update. See the documentation for beginBatchUpdate above. State is not saved if we believe it is identical to the last known saved state. State is only ever saved when all batch updates have finished (that is, there has been 1 endBatchUpdate call for each beginBatchUpdate call). If any of the endBatchUpdate calls pass aForceDirty=true, we will flush to the prefs file. Parameters aForceDirty force CustomizableUI t...
...And 6 more matches
Midas
Introduction Midas is the code name for Gecko's built-in rich text editor. Midas can be enabled via JavaScript on an HTML document. 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. ...
...xplorer. 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. Once Midas is invoked, a few more methods of the document object become available. You can try demo of this here. Properties document.designMode By setting this property to "on", the document becomes editable. Notes Since an entire document becomes editable, authors often load the editable document into an IFRAME and do the bulk of the scripting in the parent document. According to standards, The IFRAME element has the contentDocument property ...
...lable. You can try demo of this here. Properties document.designMode By setting this property to "on", the document becomes editable. Notes Since an entire document becomes editable, authors often load the editable document into an IFRAME and do the bulk of the scripting in the parent document. According to standards, The IFRAME element has the contentDocument property that refers to the document in the inline frame. It also has a property called contentWindow that refers to the window object inside the inline frame. This also avoids problems with bug 198155. In addition to the built-in commands, advanced editing can be done by manipulating the Selection and range objects. It is beneficial to be familiar with these objects when working with an editable document. Examples This example s...
...And 6 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. ...
... 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 functionality, design, and coding practices for SpiderMonkey. It can be read as something like an "ideal future state" for the engine. That means the code as it is today won't match this document, and that's OK. Whenever practical, new code and changes should move code closer to the ideal future. And of course, the idea of the future is always evolving in time as things chan...
... 8 Getting SpiderMonkey source code Guide, SpiderMonkey You can get the SpiderMonkey source code in gzipped form or directly from the Mercurial repository. 9 Hacking Tips SpiderMonkey This page list a few tips to help you investigate issues related to SpiderMonkey. All tips listed here are dealing with the JavaScript shell obtained at the end of the build documentation of SpiderMonkey. It is separated in 2 parts, one section related to debugging and another section related to drafting optimizations. Many of these tips only apply to debug builds of the JS shell; they will not function in a release build. 10 How to embed the JavaScript engine Embedding Mozilla, JavaScript, SpiderMonkey, Tutorial See also JSAPI User Guide. In particular, ...
...And 6 more matches
nsIAccessibleRole
entire on screen contents of containers advertising this role. Should be used for warning dialogs, etc. The role is used by xul:browsermessage, role="alert", xforms:message. ROLE_WINDOW 9 Represents the window frame, which contains child objects such as a title bar, client, and other objects contained in a window. The role is supported automatically by MS Windows. ROLE_INTERNAL_FRAME 10 A sub-document or iframe. ROLE_MENUPOPUP 11 Represents a menu, which presents a list of options from which the user can make a selection to perform an action. It is used for role="menu". ROLE_MENUITEM 12 Represents a menu item, which is an entry in a menu that a user can choose to carry out a command, select an option. It is used for xul:menuitem, role="menuitem". ROLE_TOOLTIP 13 Represents a ToolTip that...
...ole="menu". ROLE_MENUITEM 12 Represents a menu item, which is an entry in a menu that a user can choose to carry out a command, select an option. It is used for xul:menuitem, role="menuitem". ROLE_TOOLTIP 13 Represents a ToolTip that provides helpful hints. ROLE_APPLICATION 14 Represents a main window for an application. It is used for role="application". Also refer to ROLE_APP_ROOT. ROLE_DOCUMENT 15 Represents a document window. A document window is always contained within an application window. It is used for role="document". ROLE_PANE 16 Represents a pane within a frame or document window. Users can navigate between panes and within the contents of the current pane, but cannot navigate between items in different panes. Thus, panes represent a level of grouping lower than frame windows...
...It is used for the first child of a or iframe. ROLE_CHART 17 Represents a graphical image used to represent data. ROLE_DIALOG 18 Represents a dialog box or message box. It is used for xul:dialog, role="dialog". ROLE_BORDER 19 Represents a window border. ROLE_GROUPING 20 Logically groups other objects. ...
...And 6 more matches
nsIIOService
dingNode, in nsIPrincipal aLoadingPrincipal, in nsIPrincipal aTriggeringPrincipal, in uint32_t aSecurityFlags, in uint32_t aContentPolicyType, ); Parameters aSpec The spec for the desired uri. aOriginCharset The charset for the uri. May be null. aBaseURI The base URI for the spec. May be null. If aSpec is an absolute URL, this parameter is ignored. aLoadingNode The loadingDocument of the channel. This is the document/element that will get access to the result of this request. For example for an image load, it's the document in which the image will be loaded. And for a CSS stylesheet it's the document whose rendering will be affected by the stylesheet. If possible, pass in the element which is performing the load. But if the load is coming from a JS API (such as XMLHttpRequ...
.... For example for an image load, it's the document in which the image will be loaded. And for a CSS stylesheet it's the document whose rendering will be affected by the stylesheet. If possible, pass in the element which is performing the load. But if the load is coming from a JS API (such as XMLHttpRequest) or if the load might be coalesced across multiple elements (such as for ) then pass in the Document node instead. For loads that are not related to any document, such as loads coming from addons or internal browser features, use null here. aLoadingPrincipal The loadingPrincipal of the channel. The principal of the document where the result of this request will be used. This defaults to the principal of aLoadingNode, so when aLoadingNode is passed this can be left as null. However for loads wh...
...oaded. Most likely the triggeringPrincipal and the loadingPrincipal are identical, in which case the triggeringPrincipal can be left out. In some cases the loadingPrincipal and the triggeringPrincipal are different however, e.g. a stylesheet may import a subresource. In that case the principal of the stylesheet which contains the import command is the triggeringPrincipal, and the principal of the document whose rendering is affected is the loadingPrincipal. aSecurityFlags The securityFlags of the channel. Any of the securityflags defined in nsILoadInfo. aContentPolicyType The contentPolicyType of the channel. Any of the content types defined in nsIContentPolicyBase.idl. Return value Returns an nsIChannel based on aSpec and aBaseURI. newChannelFromURI() Obsolete since Gecko 48 Creates a c...
...And 6 more matches
nsIXSLTProcessor
content/xslt/public/nsIXSLTProcessor.idlScriptable XSLT Processor Inherits from: nsISupports Last changed in Gecko 1.7 Implemented by: @mozilla.org/document-transformer;1?type=xslt. ...
... content/xslt/public/nsIXSLTProcessor.idlScriptable XSLT Processor Inherits from: nsISupports Last changed in Gecko 1.7 Implemented by: @mozilla.org/document-transformer;1?type=xslt. ...
...This will make the processor use the default-value for all parameters as specified in the stylesheet. void clearParameters(); Parameters None. getParameter() Gets a parameter if...
...And 6 more matches
DOM Inspector FAQ - Firefox Developer Tools
How do I inspect a web site/window? ...
... Inspect a URL This just focuses the DOM Inspector's address bar, which allow you to inspect arbitrary documents which can be accessed via a URL. This causes the document to be loaded in the browser pane. ...
... Inspect a URL This just focuses the DOM Inspector's address bar, which allow you to inspect arbitrary documents which can be accessed via a URL. This causes the document to be loaded in the browser pane. ...
...And 6 more matches
Background Tasks API - Web APIs
operative Scheduling of Background Tasks API (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 in...
...imeout period has expired. The Window interface is also augmented by this API to offer 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 operatio...
...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 u...
...And 6 more matches
Drawing shapes with canvas - Web APIs
he canvas (relative to the origin) of the top-left corner of the rectangle. width and height provide the rectangle's size. Below is the draw() function from the previous page, but now it is making use of these three functions. Rectangular shape example <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> function draw() { var canvas = document.getElementById('canvas'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); ctx.fillRect(25, 25, 100, 100); ctx.clearRect(45, 45, 60, 60); ctx.strokeRect(50, 50, 50, 50); } } This example's output is shown below. ScreenshotLive sample The fillRect() function draws a large black square 100 pixels on each side. The clearRect() function then erases a 60x60 pixel squ...
.... Note: When you call fill(), any open shapes are closed automatically, so you don't have to call closePath(). This is not the case when you call stroke(). ...
... to place the starting point somewhere else. We could also use moveTo() to draw unconnected paths. Take a look at the smiley face below. To try this for yourself, you can use the code snippet below. Just paste it into the draw() function we saw earlier. ...
...And 6 more matches
Using channel messaging - Web APIs
In this article we'll explore the basics of using this technology. Note: This feature is available in Web Workers. ...
... In this article we'll explore the basics of using this technology. Note: This feature is available in Web Workers. ...
... In this article we'll explore the basics of using this technology. Note: This feature is available in Web Workers. ...
...And 6 more matches
ChildNode.before() - Web APIs
Web › API › ChildNode › before
e's parent, just before this ChildNode. DOMString objects are inserted as equivalent Text nodes. Syntax [Throws, Unscopable] void ChildNode.before((Node or DOMString)... nodes); Parameters nodes A set of Node or DOMString objects to insert. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...String objects are inserted as equivalent Text nodes. Syntax [Throws, Unscopable] void ChildNode.before((Node or DOMString)... nodes); Parameters nodes A set of Node or DOMString objects to insert. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...ows, Unscopable] void ChildNode.before((Node or DOMString)... nodes); Parameters nodes A set of Node or DOMString objects to insert. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...And 6 more matches
Element - Web APIs
Web › API › Element
It only has methods and properties common to all kinds of elements. More specific classes inherit from Element. For example, the HTMLElement interface is the base interface for HTML elements, while the SVGElement interface is the basis for all SVG elements. Most functionality is specified further down the class hierarchy. Languages outside the realm of the Web platform, like XUL through the XULElement interface, also implement Element. ...
...-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Element</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits properties from its parent interface, Node, and by extension that interface's parent, EventTarget. It implements the properties of ParentNode, ChildNode, NonDocumentTypeChildNode, and Animatable. Element.attributes Read only Returns a NamedNodeMap object containing the assigned attributes of the corresponding HTML element. Element.classList Read only Returns a DOMTokenList containing the list of class attributes. Element.className Is a DOMString representing the class of the element. Element.clientHeight Read only Returns a Number representing th...
... Element.localName Read only A DOMString representing the local part of the qualified name of the element. Element.namespaceURI Read only The namespace URI of the element, or null if it is no namespace. Note: In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the http://www.w3.org/1999/xhtml namespace in both HTML and XML trees. NonDocumentTypeChildNode.nextElementSibling Read only Is an Element, the element immediately following the given one in the tree, or null if there's no sibling node. Element.outerHTML Is a DOMString representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string. Element.part Represents the part identifier(s) of the eleme...
...And 6 more matches
Node.nodeName - Web APIs
Web › API › Node › nodeName
The nodeName read-only property returns the name of the current Node as a string. Syntax var str = node.nodeName; Value A DOMString. ...
... The nodeName read-only property returns the name of the current Node as a string. Syntax var str = node.nodeName; Value A DOMString. ...
... The nodeName read-only property returns the name of the current Node as a string. Syntax var str = node.nodeName; Value A DOMString. ...
...And 6 more matches
NodeIterator - Web APIs
NodeIterator.root Read only Returns a Node representing the root node as specified when the NodeIterator was created. ...
... NodeIterator.root Read only Returns a Node representing the root node as specified when the NodeIterator was created. ...
... NodeIterator.root Read only Returns a Node representing the root node as specified when the NodeIterator was created. ...
...And 6 more matches
ParentNode.querySelectorAll() - Web APIs
The ParentNode mixin defines the querySelectorAll() method as returning a NodeList representing a list of elements matching the specified group of selectors which are descendants of the object on which the method was called. If you need only a single result, consider the querySelector() method instead. Note: This method is implemented as Element.querySelectorAll(), Document.querySelectorAll(), and DocumentFragment.querySelectorAll() Syntax elementList = parentNode.querySelectorAll(selectors); Parameters selectors A DOMString containing one or more selectors to match 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 ...
... 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 always empty. Exceptions SyntaxError The syntax of the specified selectors string is not valid. Examples To obtain a NodeList of all of the <p> elements in the document: var matches = document.querySelectorAll("p"); This example returns a list of all <div> elements within the document with a class of either note or alert: var matches = document.querySelectorAll("div.note, div.alert"); Here, we get a list of <p> elements whose immediate parent element is a <div> with the class highlighted and which are located inside a container whose ID is test. var contai...
... matches = document.querySelectorAll("p"); This example returns a list of all <div> elements within the document with a class of either note or alert: var matches = document.querySelectorAll("div.note, div.alert"); Here, we get a list of <p> elements whose immediate parent element is a <div> with the class highlighted and which are located inside a container whose ID is test. ...
...And 6 more matches
TextRange - Web APIs
Web › API › TextRange
IE Only This property is IE specific. Although it is well supported by IE, most other browsers no longer support this property. This property should only be used as one of the solutions when you need to be compatible with lower versions of IE, rather than relying on it completely in cross browser scripts. A TextRange object represents a fragment of text in a document, similar to the standard defined Range interface. This object is used to represent a specific piece of text in the document. For example, when you hold down the mouse to select the content on the page, you create a typical TextRange. It is implemented in IE, then a TextRange object can be created by Element.createTextRange() or Document.selection.createRange(). Note that this interface is not supported in non IE browser...
...tangle bound to the TextRange object. TextRange.htmlText Gets or sets the HTML content within the TextRange. TextRange.text Gets or sets the plaintext content within the TextRange. Methods TextRange.collapse() Move the caret to the beginning or end of the current range. TextRange.duplicate() Returns a copy of TextRange. TextRange.execCommand() Executes a command on the current document, the current selection, or the given scope. TextRange.expand() Expand the range to include the full range of specified units. For example, expanding a "word" means that the words at both ends of the range will completely included in the range. xpand to wor may become expand to words, etc. TextRange.findText() Searches the specified text in the original range and adjusts the range to include t...
...ced in the corresponding position of the parent element instead of the child element. TextRange.pasteHTML() Paste the HTML content into the given range and replace any previous text and HTML elements in the range. TextRange.queryCommandEnabled() Returns a Boolean indicating whether the specified command can be executed successfully with the execCommand method in the current state of the given document. You can also see Document.queryCommandEnabled(). TextRange.queryCommandState() Returns the Boolean indicating the current state of the specified command. You can also see Document.queryCommandState(). TextRange.queryCommandValue() Returns the DOMString indicating the current value of the specified command. You can also see Document.queryCommandValue(). TextRange.scrollIntoView() Scroll the...
...And 6 more matches
Starting up and shutting down a WebXR session - Web APIs
u should know how to shut it down properly as well. You will learn how to do these things in this article. Accessing the WebXR API Your app's access to the WebXR API begins with the XRSystem object. This object represents the overall WebXR device suite available to you through the hardware and drivers available on the user's equipment. There is a global XRSystem object available for use by your document through the the Navigator property xr, which returns the XRSystem object if suitable XR hardware is available for your use given the hardware available and your document's environment. Thus the simplest code that fetches the XRSystem object is: const xr = navigator.xr; The value of xr will be null or undefined if WebXR isn't available. WebXR availability As a new and still in development API...
...irefox The source code for the extension is also available on GitHub. Emulator issues and notes While this isn't the place for a full article about the extension, there are some specific things worth mentioning. Version 0.4.0 of the extension was announced on March 26, 2020. It introduced support for augmented reality (AR) through the WebXR AR Module, which has is approaching a stable state. Documentation for AR is forthcoming shortly here on MDN. Other improvements include updating the emulator to rename 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 lo...
...This may also be the case if there simply is no compatible XR hardware available. ...
...And 6 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
We need t...
...We need to add a GainNode and connect that through our audio graph to actually apply amplitude variations to our sound. The gain node has one property: gain, which is of type AudioParam. This...
...ll change how the pulse modulates the first wave: <label for="hz">Hz</label> <input name="hz" id="hz" type="range" min="660" max="1320" value="880" step="1" /> <label for="lfo">LFO</label> <input name="lfo" id="lfo" type="range" min="20" max="40" value="30" step="1" /> As before, we'll vary the parameters when the range input values are changed by the user. ...
...And 6 more matches
Using the Web Speech API - Web APIs
put <div> and the HTML element (so we can output diagnostic messages and update the app background color later on), we implement an onclick handler so that when the screen is tapped/clicked, the speech recognition service will start. This is achieved by calling SpeechRecognition.start(). The forEach() method is used to output colored indicators showing what colors to try saying. ...
...tput diagnostic messages and update the app background color later on), we implement an onclick handler so that when the screen is tapped/clicked, the speech recognition service will start. This is achieved by calling SpeechRecognition.start(). The forEach() method is used to output colored indicators showing what colors to try saying. ...
...background color later on), we implement an onclick handler so that when the screen is tapped/clicked, the speech recognition service will start. This is achieved by calling SpeechRecognition.start(). The forEach() method is used to output colored indicators showing what colors to try saying. ...
...And 6 more matches
Window.pageYOffset - Web APIs
There is slightly better support for pageYOffset than for scrollY in older browsers, but if you're not concerned about browsers more than a handful of years old, you can use either one. The corresponding pageXOffset property, which returns the number of pixels scrolled along the horizontal axis (left and right), is an alias for scrollX. ...
... than for scrollY in older browsers, but if you're not concerned about browsers more than a handful of years old, you can use either one. The corresponding pageXOffset property, which returns the number of pixels scrolled along the horizontal axis (left and right), is an alias for scrollX. Syntax yOffset = window.pageYOffset; Value A floating-point number specifying the number of pixels the Document is scrolled vertically within its containing Window. This number is subpixel precise, so it may not be an integer. A value of 0.0 indicates that the window is not scrolled vertically, and that the top of the document is located at the top edge of the window's content area. Since this property is an alias for Window.scrollY, see that article for additional details on this value and its use. Exam...
...aliquam felis. Mauris efficitur tellus massa, id ullamcorper ipsum fermentum eu. Aenean mollis dignissim ultrices. Nunc gravida, sem sit amet lobortis iaculis, dolor ligula convallis nibh, id condimentum metus libero nec odio. Quisque nec ante pretium, viverra neque nec, facilisis risus. Duis condimentum sapien non felis cursus blandit. Integer euismod lectus a ipsum pellentesque lacinia.</p> `; document.getElementById("frame").contentDocument .body.innerHTML = contentHTML; In this example, an <iframe> is created and filled with content, then a specific element within the document is scrolled into view in the frame. Once 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 j...
...And 6 more matches
Window: popstate event - Web APIs
.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. These methods and their corresponding events can be used to add data to the history stack which can be used to reconstruct 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 popsta...
...rward() 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. ...
...ently 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 not. ...
...And 6 more matches
Visual formatting model - CSS: Cascading Style Sheets
External information (e.g., viewport size, intrinsic dimensions of images, etc.). ...
... External information (e.g., viewport size, intrinsic dimensions of images, etc.). ...
... External information (e.g., viewport size, intrinsic dimensions of images, etc.). ...
...And 6 more matches
position - CSS: Cascading Style Sheets
Web › CSS › position
The position CSS property sets how an element is positioned in a document. The top, right, bottom, and left properties determine the final location of positioned elements. 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 The position property is specified as a single keyword chosen from the list of values below. Values static The element is positioned according to the normal flow of the document. The top, right, bottom, left, and z-index properties have no effect. This is the default value. ...
...amples and send us a pull request. Syntax The position property is specified as a single keyword chosen from the list of values below. Values static The element is positioned according to the normal flow of the document. The top, right, bottom, left, and z-index properties have no effect. This is the default value. relative The element is positioned according to the normal flow of the document, and then offset relative to itself based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements; thus, the space given for the element in the page layout is the same as if position were static. This value creates a new stacking context when the value of z-index is not auto. Its effect on table-*-group, table-row, table-column, table-cell, an...
... The offset does not affect the position of any other elements; thus, the space given for the element in the page layout is the same as if position were static. This value creates a new stacking context when the value of z-index is not auto. Its effect on table-*-group, table-row, table-column, table-cell, and table-caption elements is undefined. absolute The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left. This value creates a new stacking context when the value of z-index is not auto. The margins of absolutely positione...
...And 6 more matches
<input type="month"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › month
ue is always formatted yyyy-MM. When the above value is submitted to the server, for example, it will look like bday-month=1978-06. ...
...cept as a valid input min The earliest year and month to accept as a valid input readonly A Boolean which, if present, indicates that the input's value can't be edited step A stepping interval to use when incrementing and decrementing the value of the input field list The values of the list attribute is the id of a <datalist> element located in the same document. The <datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. max The latest year and month, in the string format discussed in the Valu...
...s <input type="month">, we create a new <input> element, try setting its type to month, then immediately check what its type is set to. Browsers that don't support type month will return text, since that's What month falls back to when not supported. If <input type="month"> is not supported, we hide the native picker and show the fallback picker UI instead. ...
...And 6 more matches
Common MIME types - HTTP
Here is a list of MIME types, associated by type of documents, ordered by their common extensions. Two primary MIME types are important for the role of default types: text/plain is the default value for textual files. A textual file should be human-readable and must not contain binary data. application/octet-stream is the default value for all other cases. An unknown file type should use this type. Browsers pay a particular care when manipulating these files, attempting to safeguard the user to prevent dangerous behaviors. IANA is the official registry of MIME media types and maintains a list of all the official MIME types. ...
...he default value for all other cases. An unknown file type should use this type. Browsers pay a particular care when manipulating these files, attempting to safeguard the user to prevent dangerous behaviors. IANA is the official registry of MIME media types and maintains a list of all the official MIME types. ...
...ay a particular care when manipulating these files, attempting to safeguard the user to prevent dangerous behaviors. IANA is the official registry of MIME media types and maintains a list of all the official MIME types. ...
...And 6 more matches
HTTP headers - HTTP
Web › HTTP › Headers
te/time after which the response is considered stale. Pragma Implementation-specific header that may have various effects anywhere along the request-response chain. Used for backwards compatibility with HTTP/1.0 caches where the Cache-Control header is not yet present. Warning General warning information about possible problems. Client hints HTTP Client hints are a work in progress. Actual documentation can be found on the website of the HTTP working group. Accept-CH Servers can advertise support for Client Hints using the Accept-CH header field or an equivalent HTML <meta> element with http-equiv attribute ([HTML5]). Accept-CH-Lifetime Servers can ask the client to remember the set of Client Hints that the server supports for a specified period of time, to enable delivery of Clie...
...er the given date. This is used to transmit data only when the cache is out of date. If-Unmodified-Since Makes the request conditional, and expects the entity to be transmitted only if it has not been modified after the given date. This ensures the coherence of a new fragment of a specific range with previous ones, or to implement an optimistic concurrency control system when modifying existing documents. Vary Determines how to match request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server. Connection management Connection Controls whether the network connection stays open after the current transaction finishes. Keep-Alive Controls how long a persistent connection should stay open. Content negotiation Accept Informs...
... the Firefox user agent string reference. Response context Allow Lists the set of HTTP request methods supported by a resource. Server Contains information about the software used by the origin server to handle the request. Range requests Accept-Ranges Indicates if the server supports range requests, and if so in which unit the range can be expressed. Range Indicates the part of a document that the server should return. If-Range Creates a conditional range request that is only fulfilled if the given etag or date matches the remote resource. Used to prevent downloading two ranges from incompatible version of the resource. Content-Range Indicates where in a full body message a partial message belongs. Security Cross-Origin-Embedder-Policy (COEP) Allows a server to declare a...
...And 6 more matches
An overview of HTTP - HTTP
Web › HTTP › Overview
Clients and servers communicate by exchanging individual messages (as opposed to a stream of data). The messages sent by the client, usually a Web browser, are called requests and the messages sent by the server as an answer are called responses. ...
... Clients and servers communicate by exchanging individual messages (as opposed to a stream of data). The messages sent by the client, usually a Web browser, are called requests and the messages sent by the server as an answer are called responses. ...
... Clients and servers communicate by exchanging individual messages (as opposed to a stream of data). The messages sent by the client, usually a Web browser, are called requests and the messages sent by the server as an answer are called responses. ...
...And 6 more matches
Autoplay guide for media and Web Audio APIs - Web media technologies
volume is set to 0 The user has interacted with the site (by clicking, tapping, pressing keys, etc.) If the site has been whitelisted; this may happen either automatically if the browser determines that the user engages with media frequently, or manually through preferences or other user interface features If the autoplay feature policy is used to grant autoplay support to an <iframe> and its document. Otherwise, the playback will likely be blocked. The exact situations that result in blocking, and the specifics of how sites become whitelisted vary from browser to browser, but the above are good guidelines to go by. For details, see the auto-play policies for Google Chrome and WebKit. Note: Put another way, playback of any media that includes audio is generally blocked if the playback is ...
...et; vid.onplay = null; // Start whatever you need to do after playback has started } After getting a reference to the video element from the Event object's target, the element's onplay handler is set to null. This will prevent any future play events from being delivered to the handler. That could happen if the video is paused and resumed by the user or automatically by the browser when the document is in a background tab. At this point, your site or app can begin whatever it needs to do that relies upon the video having been started up. Note: This approach doesn't differentiate between autoplay and the user starting playback manually. The play() method The term "autoplay" also refers to scenarios in which a script tries to trigger the playback of media that includes audio, outside the...
... use the autoplay attribute whenever possible, because support for autoplay preferences are more widespread for the autoplay attribute than for other means of playing media automatically. It also lets the browser take responsibility for starting playback, letting it optimize the timing of that taking place. Example: Playing video This simple example plays the first <video> element found in the document. play() won't let the playback begin unless the document has permission to automatically play media. document.querySelector("video").play(); Example: Handling play() failures It's much easier to detect a failure to autoplay media when you use the play() method to start it. play() returns a Promise which is resolved once the media successfully begins to play, and is rejected when playback fails...
...And 6 more matches
Media - Progressive web apps (PWAs)
h a display. But you might also want to project it to a big screen for a large audience, or you might want to print it. These different media have different characteristics. CSS has the capacity to present content according to the media type. To specify rules that are specific to a type of media, use @media followed by the media type, followed by curly braces that enclose the rules. ...
...to a type of media, use @media followed by the media type, followed by curly braces that enclose the rules. Example A document on a website has a navigation area that contains the primary site menu. In the markup language, the navigation area's parent element has the id nav-area. (In HTML5, this can be marked up with the <nav> element instead of <div> with an id attribute.) When printing the document, the navigation area has no purpose. ...
... Example A document on a website has a navigation area that contains the primary site menu. In the markup language, the navigation area's parent element has the id nav-area. (In HTML5, this can be marked up with the <nav> element instead of <div> with an id attribute.) When printing the document, the navigation area has no purpose. This CSS (below) removes the navigation area when printing the document: @media print { #nav-area {display: none;} } Some common media types are: screen Color device display print Printed paged media projection Projected display all All media (the default) More details There are other ways to specify the media type for a set of rules. ...
...And 6 more matches
Web Components
ated 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 be scripted and styled without the fear of collision with other parts of the document. HTML templates: The <template> and <slot> elements enable you to write markup templates that are not displayed in the rendered page. These can then be reused multiple times as the basis of a cu...
...mplates and slots A guide showing how to define a reusable HTML structure using <template> and <slot> elements, and then use that structure inside your web components. Reference Custom elements CustomElementRegistry Contains functionality related to custom elements, most notably the CustomElementRegistry.define() method used to register new custom elements so they can then be used in your document. ...
... attributeChangedCallback: Invoked when one of the custom element's attributes is added, removed, or changed. ...
...And 6 more matches
page-worker - Archive of obsolete content
e module exports a constructor function Page, which constructs a new page worker. A page worker may be destroyed, after which its memory is freed, and you must create a new instance to load another page. You specify the page to load using the contentURL option to the Page() constructor. ...
...age({ contentScript: "console.log(document.body.innerHTML);", contentURL: "http://en.wikipedia.org/wiki/Internet" }); It can also point to an HTML file which you've packaged with your add-on. To do this, save the file in your add-on's data directory and create the URL using the data.url() method of the self module: pageWorker = require("sdk/page-worker").Page({ contentScript: "console.log(document.body.innerHTML);", contentURL: require("sdk/self").data.url("myFile.html") }); From Firefox 34, you can use "./myFile.html" as an alias for self.data.url("myFile.html"). ...
...he self module: pageWorker = require("sdk/page-worker").Page({ contentScript: "console.log(document.body.innerHTML);", contentURL: require("sdk/self").data.url("myFile.html") }); From Firefox 34, you can use "./myFile.html" as an alias for self.data.url("myFile.html"). So you can rewrite the above code like this: pageWorker = require("sdk/page-worker").Page({ contentScript: "console.log(document.body.innerHTML);", contentURL: "./myFile.html" }); You can load a new page by setting the page worker's contentURL property. ...
...And 5 more matches
Appendix: What you should know about open-source software licenses - Archive of obsolete content
Any discussion of open-source software deserves an explanation of licensing-related issues. In this chapter, I'll explain some of the basics: what open-source software (OSS) licenses are, what types of licenses exist, and when they're appropriate. ...
... copies of the source code; A user can obtain a program's source code; A user can modify the source code. Any OSS license will include these rights. The user is free to use (duplicate, distribute, and modify) the source code, following certain conditions. This means that the author is granting users the use of the work in the strong, authorial sense, and when I write "use" in the rest of this document it is generally in that sense. These conditions will vary from one license to the next, but the Open Source Definition stipulates the following minimum conditions: The integrity of the author's source code must be preserved; No discrimination may be made against individuals or organizations; No discrimination may be made based on field of endeavor; No additional licensing can be required w...
...ce and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 2. This software is provided "as is" and without warranty. Use at your own risk. 3. Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. Pros and cons The Modified BSD license w...
...And 5 more matches
Intercepting Page Loads - Archive of obsolete content
bs, without having to worry how many tabs are open. gBrowser exists in every browser window. We store the handler function in a private variable because later we want to remove it when we do not need it anymore. ...
...ow. We store the handler function in a private variable because later we want to remove it when we do not need it anymore. gBrowser.removeEventListener("load", this._loadHandler, true); Finally, the actual code for the handler, which is very simple: _onPageLoad : function(event) { // this is the content document of the loaded page. let doc = event.originalTarget; if (doc instanceof HTMLDocument) { // is this an inner frame? if (doc.defaultView.frameElement) { // Frame within a tab was loaded. // Find the root document: while (doc.defaultView.frameElement) { doc = doc.defaultView.frameElement.ownerDocument; } } } } The second if validation is necessary if you need to make a distinction for HTML documents being loaded in inner page frames. F...
... You can't, however, easily cancel the page load. You can close the tab, redirect the tab to about:blank or another page, or tell the browser to stop loading this page, but in general you don't want to do this because it will be visible to the user and it will look like a bug. ...
...And 5 more matches
New Skin Notes - Archive of obsolete content
E for some reason. I'll try again, but can't guarantee this will be fixed for the initial upgrades. --dria Took two days, but I finally got this sorted out. When the skin is updated on test/docs, editform textarea should be resizeable in all browsers. Yay! --dria WordPress skins need footer information. -- 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 (...
...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:16, 29 Aug 2005 (PDT) Imho the visited color looks horrible. We're a documentation site. There's no real reason for user to give him info that he already visited XML main page. It's hardly possible that he'll be interested in it. In all other dev centres there is no "visited link color" and we should remove IMHO. It looks odd when someone who uses Devmo on regular basis sees some violet links just because he already worked with this site yesterday.Also, the current color f...
...e he already worked with this site yesterday.Also, the current color for visited links makes them less visible. --Gandalf 00:45, 31 Aug 2005 (PDT) I don't like the current color too, but I strongly disagree that we don't need to give visited links different color. This is not what user expects (well, I don't expect sites to style visited and non-visited links the same), and it's false that other documentation sites do this (I just checked Apple's and Microsoft's sites). Your statement that "It looks odd when someone who uses Devmo on regular basis sees some violet links just because he already worked with this site yesterday" holds true for every single place on the web, yet visited links use different styling on most sites. --Nickolay 01:34, 31 Aug 2005 (PDT) Ok, so I'm asking just to change th...
...And 5 more matches
Building accessible custom components in XUL - Archive of obsolete content
eneric HTML elements are really acting as specific GUI controls (such as a treeitem within a treeview). Firefox 1.5 is the first browser to support DHTML Accessibility; it maps the declarations within the HTML page to the underlying accessibility architecture so that assistive technologies can "read" a web page and know how to present these complex controls to the end user. This has all been well-documented for some time. However, it is less well-known that the same DHTML Accessibility techniques can be applied to XUL, Mozilla's XML markup language for building user interfaces. (The Firefox interface itself is built in XUL, as well as the graphical interface presented by Firefox extensions.) XUL itself has a much richer set of built-in controls than HTML. There is generally no need to build your o...
...ibility goes. All you need to do is declare two namespaces and assign the appropriate role attributes, and Firefox handles exposing the elements properly to the underlying assistive technology. Further reading Table of supported roles and states in Firefox Focus Issues Download stage-3.zip install stage-3.xpi The next step on the road to an accessible spreadsheet is the focus problem. In HTML documents, you can make any element focusable with the tabindex attribute. In XUL, there is no tabindex attribute; to make a XUL element focusable, you need to use a Mozilla-specific CSS property, -moz-user-focus: normal. <code> grid.spreadsheet { border: thin solid; -moz-user-focus: normal; } </code> In HTML documents, Firefox draws a focus rectangle around the currently focused element. In XUL, we w...
...adsheet regains focus (by pressing SHIFT-TAB, or cycling all the way around the tab order and coming back into the spreadsheet), we need to programmatically reset the focus to the previously focused cell. This is handled in the spreadsheet_focus function, which is registered as a handler for the focus event. ...
...And 5 more matches
XBL Example - Archive of obsolete content
custom property, it will need to retrieve the value of the selectedIndex attribute of the deck, which holds the number of the currently displayed page. Similarly, when setting this property, it will need to change the selectedIndex attribute of the deck. In addition, the text widget will need to be updated to display which page is the current one. <property name="page" onget="return parseInt(document.getAnonymousNodes(this)[0].childNodes[0].getAttribute('selectedIndex'));" onset="return this.setPage(val);"/> The page property gets its value by looking at the first element of the anonymous array. This returns the vertical box, so to get the deck, we need to get the first child node of the box. The anonymous array isn't used as the deck is not anonymous from the box. Finally, the value of...
...all the onset handler to set the value. setPage method Now let's define the 'setPage' method. It will take one parameter, the page number to set the page to. It will need to make sure the page is not out of range and then modify the deck's selectedIndex attribute and the text widget's label attribute. ...
... deck's selectedIndex attribute and the text widget's label attribute. <method name="setPage"> <parameter name="newidx"/> <body> <![CDATA[ var thedeck=document.getAnonymousNodes(this)[0].childNodes[0]; var totalpages=this.childNodes.length; if (newidx<0) return 0; if (newidx>=totalpages) return totalpages; thedeck.setAttribute("selectedIndex",newidx); document.getAnonymousNodes(this)[0].childNodes[1].childNodes[1] .setAttribute("value",(newidx+1)+" of "+totalpages); return newidx; ]]> </body> </method> This function is called setPage and takes one parameter newidx. The body of the method has been enclosed inside <![CDATA[ and ]]>. This is the general mechanism in all XML files that can be used to escape all of the text insid...
...And 5 more matches
nsIContentPolicy - Archive of obsolete content
ware plugin (blocking ads or altering the look of content, for example), or if you want to stop or allow user-browsed URLs. Warning: Do not block the caller in your implementations of shouldLoad() or shouldProcess() (for example, by launching a dialog to prompt the user for something).") Note: In reality, much of this interface is defined in the nsIContentPolicyBase interface, but for now is documented here until someone has time to split things up. Method overview short shouldLoad(in unsigned long aContentType, in nsIURI aContentLocation, in nsIURI aRequestOrigin, in nsISupports aContext, in ACString aMimeTypeGuess, in nsISupports aExtra, in nsIPrincipal aRequestPrincipal); short shouldProcess(in unsigned long aContentType, in nsIURI aContentLocation, in nsIURI aRequestO...
...e 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). ...
...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). TYPE_SUBDOCUMENT 7 Indicates a document contained within another document (for example, <iframe> and <frame> elements). Note: Gecko uses TYPE_INTERNAL_FRAME and TYPE_INTERNAL_IFRAME in order to discern the difference internally. These types are mapped to TYPE_SUBDOCUMENT before being passed into the implement...
...And 5 more matches
Gecko FAQ - Gecko Redirect 1
e? Basically, a layout engine takes content (such as HTML, XML, image files, applets, and so on) and formatting information (such as Cascading Style Sheets, presentational HTML tags, etc.) and displays the formatted content on the screen. It paints the browser's content 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") a...
...For more information see XUL. How is a layout engine like Gecko different from a Web browser? Gecko provides the foundation needed to display content on the screen, including a layout engine and a complementary set of browser components. ...
...from among those that Gecko offers, and package these components alongside their own within their finished products. ...
...And 5 more matches
Positioning - Learn web development
This article explains the different position values, and how to use them. Prerequisites: HTML basics (study Introduction to HTML), and an idea of How CSS works (study Introduction to CSS.) Objective: To learn how CSS positioning works. ...
...of How CSS works (study Introduction to CSS.) Objective: To learn how CSS positioning works. We'd like you to follow along with the exercises on your local computer, if possible -- grab a copy of 0_basic-flow.html from our GitHub repo (source code here) and use that as a starting point. Introducing positioning The whole idea of positioning is to allow us to override the basic document flow behavior described above, to produce interesting effects. What if you want to slightly alter the position of some boxes inside a layout from their default layout flow position, to give a slightly quirky, distressed feel? Positioning is your tool. Or if you want to create a UI element that floats over the top of other parts of the page, and/or always sits in the same place inside the browser ...
...page is scrolled? Positioning makes such layout work possible. There are a number of different types of positioning that you can put into effect on HTML elements. To make a specific type of positioning active on an element, we use the position property. Static positioning Static positioning is the default that every element gets -- it just means "put the element into its normal position in the document layout flow -- nothing special to see here." To demonstrate this, and get your example set up for future sections, first add a class of positioned to the second <p> in the HTML: <p class="positioned"> ... </p> Now add the following rule to the bottom of your CSS: .positioned { position: static; background: yellow; } If you now save and refresh, you'll see no difference at all, except for...
...And 5 more matches
What is a URL? - Learn web development
ks on the Web. Summary With Hypertext and HTTP, URL is one of the key concepts of the Web. It is the mechanism used by browsers to retrieve any published resource on the web. URL stands for Uniform Resource Locator. A URL is nothing more than the address of a given unique resource on the Web. In theory, each valid URL points to a unique resource. Such resources can be an HTML page, a CSS document, an image, etc. In practice, there are some exceptions, the most common being a URL pointing to a resource that no longer exists or that has moved. As the resource represented by the URL and the URL itself are handled by the Web server, it is up to the owner of the web server to carefully manage that resource and its associated URL. Active Learning There is no active learning available yet. De...
...zilla.org/docs/Learn/ https://developer.mozilla.org/search?q=URL Any of those URLs can be typed into your browser's address bar to tell it to load the associated page (resource). A URL is composed of different parts, some mandatory and others optional. Let's see the most important parts using the following URL: http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument http is the protocol. The first part of the URL indicates which protocol the browser must use. A protocol is a set method for exchanging or transferring data around a computer network. Usually for websites it is the HTTP protocol or its secured version, HTTPS. The Web requires one of these two, but browsers also know how to handle other protocols such as mailto: (to open a mail client) or ft...
...xtra parameters provided to the Web server. Those parameters are a list of key/value pairs separated with the & symbol. The Web server can use those parameters to do extra stuff before returning the resource. Each Web server has its own rules regarding parameters, and the only reliable way to know if a specific Web server is handling parameters is by asking the Web server owner. #SomewhereInTheDocument is an anchor to another part of the resource itself. An anchor represents a sort of "bookmark" inside the resource, giving the browser the directions to show the content located at that "bookmarked" spot. On an HTML document, for example, the browser will scroll to the point where the anchor is defined; on a video or audio document, the browser will try to go to the time the anchor represents. It...
...And 5 more matches
Graceful asynchronous programming with Promises - Learn web development
ngle method on it and return the result, we'll need to wrap the function body in curly braces this time (otherwise it'll throw an error). Add the following to the end of your code: let promise3 = promise2.then(myBlob => { }) Now let's fill in the body of the executor function. Add the following lines inside the curly braces: let objectURL = URL.createObjectURL(myBlob); let image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); Here we are running the URL.createObjectURL() method, passing it as a parameter the Blob returned when the second promise fulfills. This will return a URL pointing to the object. Then we create an <img> element, set its src attribute to equal the object URL and append it to the DOM, so the image will display on the ...
...n together .then() blocks (and also .catch() blocks). The above code could also be written like this (see also simple-fetch-chained.html on GitHub): fetch('coffee.jpg') .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { return response.blob(); } }) .then(myBlob => { let objectURL = URL.createObjectURL(myBlob); let image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); }) .catch(e => { console.log('There has been a problem with your fetch operation: ' + e.message); }); Bear in mind that the value returned by a fulfilled promise becomes the parameter passed to the next .then() block's executor function. Note: .then()/.catch() blocks in promises are basically the async equival...
...ariables (creating object URLs from the blobs), then display the images and text on the page. ...
...And 5 more matches
A first splash into JavaScript - Learn web development
ess: </label><input type="text" id="guessField" class="guessField"> <input type="submit" value="Submit guess" class="guessSubmit"> </div> <div class="resultParas"> <p class="guesses"></p> <p class="lastResult"></p> <p class="lowOrHi"></p> </div> <script> // Your JavaScript goes here let randomNumber = Math.floor(Math.random() * 100) + 1; const guesses = document.querySelector('.guesses'); const lastResult = document.querySelector('.lastResult'); const lowOrHi = document.querySelector('.lowOrHi'); const guessSubmit = document.querySelector('.guessSubmit'); const guessField = document.querySelector('.guessField'); let guessCount = 1; let resetButton; function checkGuess() { let userGuess = Number(guessField.value); ...
...Hi.textContent = 'Last guess was too low!' ; } else if(userGuess > randomNumber) { lowOrHi.textContent = 'Last guess was too high!'; } } guessCount++; guessField.value = ''; } guessSubmit.addEventListener('click', checkGuess); function setGameOver() { guessField.disabled = true; guessSubmit.disabled = true; resetButton = document.createElement('button'); resetButton.textContent = 'Start new game'; document.body.append(resetButton); resetButton.addEventListener('click', resetGame); } function resetGame() { guessCount = 1; const resetParas = document.querySelectorAll('.resultParas p'); for(let i = 0 ; i < resetParas.length ; i++) { resetParas[i].textContent = ''; } ...
..., but the form won't currently do anything. The place where we'll be adding all our code is inside the <script> element at the bottom of the HTML: <script> // Your JavaScript goes here </script> Adding variables to store our data Let's get started. ...
...And 5 more matches
Implementing feature detection - Learn web development
ferred to by the second <link> element, but let's instead implement some JavaScript to automatically swap them as needed. First, remove the contents of the second <link> element's href attribute. We will fill this in dynamically later on. Next, add a <script></script> element at the bottom of your body (just before the closing </body> tag). ...
... implement some JavaScript to automatically swap them as needed. First, remove the contents of the second <link> element's href attribute. We will fill this in dynamically later on. Next, add a <script></script> element at the bottom of your body (just before the closing </body> tag). Give it the following contents: const conditional = document.querySelector('.conditional'); const testElem = document.createElement('div'); if (testElem.style.flex !== undefined && testElem.style.flexFlow !== undefined) { conditional.setAttribute('href', 'flex-layout.css'); } else { conditional.setAttribute('href', 'float-layout.css'); } Here we are grabbing a reference to the second <link> element, and creating a <div> element as part of our test. In our conditional statement, we test that the flex and ...
...all the logic in a single CSS file, cutting down on HTTP requests. the problem here is browser support -- @supports is not supported at all in IE, and only supported in very recent versions of Safari/iOS WebKit (9+/9.2+), whereas the JavaScript version should work in much older browsers (probably back to IE8 or 9, although older versions of IE will have additional problems, such as not supporting Document.querySelector, and having a messed up box model). JavaScript We already saw an example of a JavaScript feature detection test earlier on. Generally, such tests are done via one of the following common patterns: Summary of JavaScript feature detection techniques Feature detection type Explanation Example If member in object Check whether a certain method or prope...
...And 5 more matches
Cross Process Object Wrappers
Note that from Firefox 47 onwards, unsafe CPOW usage is no longer permitted in browser code. If browser code tries an unsafe CPOW operation, the browser will throw an exception and you'll see an "unsafe CPOW usage forbidden" error in the Browser Console. Add-on code is still allowed to use CPOWs "unsafely". However, if an add-on passes a CPOW into a platform API, and that platform API then attempts an unsafe operation on it, this will throw an exception. So as a general rule, add-ons should avoid passing CPOWs into non-addon code. In multiprocess Firefox, chrome code runs in a different process from web content. ...
...ifferent process from web content. So chrome code can't directly interact with web content: instead, it must factor out the code that interacts with web content into separate scripts that are called frame scripts. Chrome code can load frame scripts into the content process using the message manager, and can then communicate with them using a message-passing API. To learn more about this, see the documentation on using the message manager. Chrome to content messaging must be asynchronous. This is because the chrome process runs the Firefox UI, so if it were blocked by the content process, then a slow content process could cause Firefox to become unresponsive to users. Converting synchronous code to be asynchronous can be difficult and time-consuming. As a migration aid, the messaging framework...
...); wrapper.innerHTML = "<h2>Modified by chrome!</h2>" wrapper.setAttribute("align", "center"); } Auto-generated CPOWs Add-ons that have not declared themselves multiprocess compatible are set up with a number of compatibility shims. One of these shims provides the following behavior: whenever chrome code tries to access content directly (for example, through window.content or browser.contentDocument), it is given back a CPOW that wraps the content object. This means that examples like this will actually work, even in multiprocess Firefox: gBrowser.selectedBrowser.contentDocument.body.innerHTML = "replaced by chrome code"; It's still important to keep in mind, though, that this is access through a CPOW and not direct access to content. Bidirectional CPOWs A common pattern is for chrome co...
...And 5 more matches
JavaScript-DOM Prototypes in Mozilla
ly that special. All the methods that are supposed to show up on this JSObject are actually not properties of the object itself, but rather properties of the prototype of the JSObject for the wrapper (unless the C++ object's class info has the flag nsIXPCScriptable::DONT_SHARE_PROTOTYPE set, but lets assume that's not the case here). As an example 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 prot...
...sIDOMHTMLImageElement, others are nsIDOMNSHTMLImageElement (Netscape extensions to the standard interface), nsIDOMEventTarget, nsIDOMEventListener, nsIDOM3Node, and so on. The prototype object that XPConnect creates for the classes that have class info are shared within a scope (window). Because of this, the following holds true (assuming img1 and img2 are two different image objects in the same document): img1.__proto__ === img2.__proto__ If img1 would come from one document and img2 from another document, then the above would not be true. Both prototypes would look identical, but they would be two different JSObject's. This sharing of prototypes lets users do cool things like modify how all instances of a given class works by modifying the prototype of one instance. As an example: function...
...a foo() method). ...
...And 5 more matches
Index
calization You're likely here because you're localizing a .properties file and it had a link to this page. This page is to help explain how to localize these strings so that the correct plural form is shown to the user. For example, "1 page" vs "2 pages". 9 Localization content best practices Apps, Extensions, Internationalization, Localization, Mozilla, l10n, l12y This document provides best practices for developers to create localizable code, and describes how to avoid some localizability (l12y) common mistakes. 10 Localization notes Guide, Internationalization, Localization, Mozilla Localizers usually work on the localizable files without the context of the source files including the localized strings; it is important to add comments to the local...
...ion notes Guide, Internationalization, Localization, Mozilla Localizers usually work on the localizable files without the context of the source files including the localized strings; it is important to add comments to the localizable files themselves, too. These comments are generally referred to as localization notes. There is an established format for those, which is described in this document. 11 Localization prerequisites Internationalization, Localization, delete To work on localization, you need a subset of the Mozilla Build Prerequisites. On Mac and Linux, you should be just fine, and on Windows, MozillaBuild should get you everything you need. 12 Localization quick start guide Guide, Translation This guide is filled with all of the basic,...
...guide provides details on what a localization technical review is, what criteria are used for the technical reviews, and the process for requesting one and following its progress. 19 Localization: Frequently asked questions FAQ, Guide, Internationalization, Localization, Mozilla This page lists tweaks and tips that may not require a complete page on its own. For more detailed documentation about localization in general, see our Localization page. 20 Localizing XLIFF files for iOS OASIS, Translate, XLIFF, XML, iOS Firefox for iOS uses the XLIFF XML-based file format to hold and transfer localization data. XLIFF (eXtensible Localisation Interchange File Format) is a localization standard governed by the OASIS standards body. The goal of the standard is to ha...
...And 5 more matches
DMD
OZ_CRASHREPORTER_UPLOAD_FULL_SYMBOLS=1 Launch On a local build, use mach run --dmd; use --mode to choose the mode. On a build done by the try server, follow these instructions instead. Trigger Follow the Trigger instructions for Linux. Fennec In order to use DMD on Fennec you will need root access on the Android device. Instructions on how to root your device is outside the scope of this document. Build Build with these options: ac_add_options --enable-dmd Prep In order to prepare your device for running Fennec with DMD enabled, you will need to do a few things. First, you will need to push the libdmd.so library to the device so that it can by dynamically loaded by Fennec. You can do this by running: adb push $OBJDIR/dist/bin/libdmd.so /sdcard/ Second, you will need to make an ex...
...D.cpp:1286) #02: malloc (/home/njn/moz/mi5/go64dmd/memory/build/../../../memory/build/replace_malloc.c:153) #03: moz_xmalloc (/home/njn/moz/mi5/memory/mozalloc/mozalloc.cpp:84) #04: nsCycleCollectingAutoRefCnt::incr(void*, nsCycleCollectionParticipant*) (/home/njn/moz/mi5/go64dmd/dom/xul/../../dist/include/nsISupportsImpl.h:250) #05: nsXULElement::Create(nsXULPrototypeElement*, nsIDocument*, bool, bool,mozilla::dom::Element**) (/home/njn/moz/mi5/dom/xul/nsXULElement.cpp:287) #06: nsXBLContentSink::CreateElement(char16_t const**, unsigned int, mozilla::dom::NodeInfo*, unsigned int, nsIContent**, bool*, mozilla::dom::FromParser) (/home/njn/moz/mi5/dom/xbl/nsXBLContentSink.cpp:874) #07: nsCOMPtr<nsIContent>::StartAssignment() (/home/njn/moz/mi5/go64dmd/dom/xml/../../dist/inclu...
... "Live" mode output For "live" mode, dmd.py's output d...
...And 5 more matches
NSPR Contributor Guide
These guidelines should help the contributor in crafting his contribution, increasing its likelihood for acceptance. ...
...These guidelines should help the contributor in crafting his contribution, increasing its likelihood for acceptance. ...
... releases. This means that the behavior of an existing public API item in NSPR cannot change. Should you need to have a similar API, with some slightly different behavior or different function prototype, then suggest a new API with a different name. C Language API The NSPR API is a C Language API. Please do not contribute Java, C or other language wrappers. Coding Style NSPR does not have a documented coding style guide. Look at the extant code. Make yours look like that. Some guidelines concerning naming conventions can be found in NSPR Naming Conventions in the NSPR Reference. See also: XXX Ownership of your contribution When you contribute something to NSPR, you must have intellectual property rights to that contribution. This means that you cannot give us something you snatched from s...
...And 5 more matches
NSS API Guidelines
These rules are here to help us all immediately achieve more consistent and usable code, but some existing code won't follow all these rules. ...
...These rules are here to help us all immediately achieve more consistent and usable code, but some existing code won't follow all these rules. NSS API Structure This section explains the structure and relationships of the NSS libraries. ...
...is organized, the libraries that get built from the NSS sources, and guidelines for writing NSS code. These guidelines will familiarize you with some of the ways things can be done in the NSS code. This will help you understand existing NSS code. It should also help you understand how to write new code, and where to place it. Some of the guidelines in this document, are more forward-looking than documentary. These rules are here to help us all immediately achieve more consistent and usable code, but some existing code won't follow all these rules. NSS API Structure This section explains the structure and relationships of the NSS libraries. The Layering section explains how the NSS code is layered, and how higher-level functions wrap low-level functions. The Libraries section descibes the NS...
...And 5 more matches
Python binding for NSS
es, particularly in the areas of networking and process management. Python also provides an abstraction of common operating system services but because NSS and NSPR are tightly bound python-nss exposes elements of NSPR. For information on NSS and NSPR, see the following: Network Security Services (NSS). NSS project page. Netscape Portable Runtime. NSPR project page. NSPR Reference. NSPR API documentation. Design Goals NSS and NSPR are C language API's which python-nss "wraps" and exposes to Python programs. The design of python-nss follows these basic guiding principles: Be a thin layer with almost a one-to-one mapping of NSS/NSPR calls to python methods and functions. Programmers already familiar with NSS/NSPR will be quite comfortable with python-nss. Be "Pythonic". The term Pythoni...
...nd upper case letters, a upper case letter is used to separate words. Acronyms always appear as a contiguous string of upper case letters. Method, function and property names are always lower case with words seperated by underscores. Constants are all upper case with words seperated by underscores, they match the NSS/NSPR C API. Every module, class, function, and method has associated documentation and is exposed via the standard Python methodology. This documentation is available via the numerous Python documentation extraction tools. Also see the generated HTML documentation provided with each release. NSS/NSPR structs are exposed as Python objects. NSS/NSPR functions which operate on a NSS/NSPR object (i.e. struct) become methods of that object. NSS/NSPR objects which are collect...
...k of formatted text but if you need more control, such as when building GUI elments you can access a list of "lines", each line is paired with an indentation level value. The (indent, text) pairs allow you to insert the item into a GUI tree structure or simply change the indentation formatting. Deprecated elements of the python-nss API are marked with Python deprecation warnings as well as being documented in the nss module documentation. As of Python 2.7 deprecation warnings are no longer reported by default. It is suggested Python developers using python-nss periodically run their code with deprecation warnings enabled. Depercated elements will persist for a least two releases before being removed from the API entirely. Project History Red Hat utilizes both NSS and Python in many of it's pro...
...And 5 more matches
Gecko Roles
echnologies typically respond to the role by reading the entire onscreen contents of containers advertising this role. Should be used for warning dialogs, etc. ROLE_WINDOW Represents the window frame, which contains child objects such as a title bar, client, and other objects contained in a window. The role is supported automatically by Microsoft Windows. ROLE_INTERNAL_FRAME A sub-document. ROLE_MENUPOPUP Represents a menu, which presents a list of options from which the user can make a selection to perform an action. ROLE_MENUITEM Represents a menu item, which is an entry in a menu that a user can choose to carry out a command, select an option. ROLE_TOOLTIP Represents a tooltip that provides helpful hints; this is generally displayed at the mouse cursor po...
... the user can make a selection to perform an action. ROLE_MENUITEM Represents a menu item, which is an entry in a menu that a user can choose to carry out a command, select an option. ROLE_TOOLTIP Represents a tooltip that provides helpful hints; this is generally displayed at the mouse cursor position. ROLE_APPLICATION Represents a main window for an application. ROLE_DOCUMENT Represents a document window. A document window is always contained within an application window. ROLE_PANE Represents a pane within a frame or document window. Users can navigate between panes and within the contents of the current pane, but cannot navigate between items in different panes. Thus, panes represent a level of grouping lower than frame windows or documents, but above ind...
... A font chooser. A font chooser is a component that lets the user pick various attributes for fonts. ROLE_CHROME_WINDOW Frame role. A top level window with a title bar, border, menu bar, etc. It is often used as the primary window for an application. ROLE_GLASS_PANE A glass pane. A pane that is guaranteed to be painted on top of all panes beneath it. ROLE_HTML_CONTAINER A document container for HTML, whose children represent the document content. ROLE_ICON A small fixed size picture, typically used to decorate components. ROLE_LABEL Presents an icon or short string in an interface. ROLE_LAYERED_PANE A layered pane. A specialized pane that allows its children to be drawn in layers, providing a form of stacking order. This is usually the pane that hol...
...And 5 more matches
XML Extras
The module is structured as a drop-in component 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. Feature Status Feature Status XMLSerializer Available XMLHttpRequest Available DOMParser (string and stream input source) Available Web Services with SOAP and WSDL No longer available from Gecko 1.9/Firefox 3. ...
... XMLSerializer Available XMLHttpRequest Available DOMParser (string and stream input source) Available Web Services with SOAP and WSDL No longer available from Gecko 1.9/Firefox 3. XML Persistence FIXptr and XPointer Available since 1.4alpha in the core Mozilla. Moved to XML Extras during 1.4beta. See also: XML in Mozilla document.load() A few examples dealing with XML from MozillaZine Knowledge Base. QA and Testing There are some online tests for mainly exercising the HTTP GET method via XMLHttpRequest. Other test cases for each of the implemented components listed above exist in extensions/xmlextras/tests/. More exhaustive test suites need to be created, however. If you'd like to help out with QA, you can do one of ...
... the tests associated with their component, act as QA contact for related bugs and help with regression testing. Contribute a test suite or individual tests that use the implemented components. File bugs for new test you have, and/or check them into extensions/xmlextras/tests/. File bugs against the implemented components. Bugs should be filed against the XML component in the Browser product. Documentation Probably the best way to learn how to use these technologies is through examples. There are some in extensions/xmlextras/tests/. If you follow that link to look at the examples you will need to look at page source for the HTML documents. For XMLHttpRequest object you can mostly rely on the Microsoft XMLHttpRequest documentation, with some caveats: all functions and property names begin wit...
...And 5 more matches
nsISHEntry
Inherits from: nsIHistoryEntry Last changed in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) Implemented by: @mozilla.org/browser/session-history-entry;1. ...
... Inherits from: nsIHistoryEntry Last changed in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) Implemented by: @mozilla.org/browser/session-history-entry;1. ...
...crollPosition(in long x, in long y); void setTitle(in AString aTitle); void setUniqueDocIdentifier(); void setURI(in nsIURI aURI); void setViewerBounds(in nsIntRect bounds); Native code only! void syncPresentationState(); Attributes Attribute Type Description cacheKey nsISupports Set and get the cache key for the entry. contentType ACString Indicates the content-type of the document that this is a session history entry for. contentViewer nsIContentViewer Content viewer, for fast restoration of presentation. docIdentifier unsigned long long An integer that should be the same for two entries attached to the same docshell if and only if the two entries are entries for the same document. In practice, two entries A and B will have the same docIdentifier if we arrived at B by...
...And 5 more matches
nsISelectionController
the method returns. SCROLL_FIRST_ANCESTOR_ONLY 1<<2 If set, only the first ancestor will be scrolled into view. SCROLL_CENTER_VERTICALLY 1<<4 If set, the specified location will be scrolled to the center of the view. Methods Native code only!characterExtendForBackspace Will extend the selection one character cell backward in the document. This method is used internally for handling backspace key only when we're after UTF-16 surrogates. void characterExtendForBackspace(); Parameters None. Native code only!characterExtendForDelete Will extend the selection one character cell forward in the document. This method is used internally for handling delete key. void characterExtendForDelete(); Parameters None. characterMove() Will move...
...ce key only when we're after UTF-16 surrogates. void characterExtendForBackspace(); Parameters None. Native code only!characterExtendForDelete Will extend the selection one character cell forward in the document. This method is used internally for handling delete key. void characterExtendForDelete(); Parameters None. characterMove() Will move the selection one character forward/backward in the document. This will also have the effect of collapsing the selection if the extend = PR_FALSE the "point" of selection that is extended is considered the "focus" point, or the last point adjusted by the selection. void characterMove( in boolean forward, in boolean extend ); Parameters forward Forward or backward if PR_FALSE. extend Should it collapse the selection or exte...
...olean checkVisibility( in nsIDOMNode node, in short startOffset, in short endOffset ); Parameters node nsIDOMNode to test. startOffset Offset in DOM to first char of textnode to test. endOffset Offset in DOM to last char of textnode to test. Return value true if visible, false if not. completeMove() Will move page view to the top or bottom of the document this will also have the effect of collapsing the selection if the extend = PR_FALSE the "point" of selection that is extended is considered the "focus" point, or the last point adjusted by the selection. void completeMove( in boolean forward, in boolean extend ); Parameters forward Forward or backward if PR_FALSE. extend Should it collapse the selection or extend...
...And 5 more matches
Working with Multiple Versions of Interfaces
The Problem In this short note we illustrate how one can update an XPCOM module in order for it to work in both Firefox 2 and Firefox 3, even if the interfaces have changed in the interim. In the extension that prompted this note, I needed to obtain the HWND of the document (yes its on Windows) in order to identify each particular extension instance. To do this I used the accessibility framework: HWND getHwnd(nsIDOMNode *node){ HWND self = NULL; nsresult rv; nsCOMPtr<nsIAccessibleRetrieval> refp; refp = do_CreateInstance( "@mozilla.org/accessibleRetrieval;1", &rv); if (NS_FAILED(rv)){ return self; } //line 6. nsCOMPtr<nsIAccessible> accnode; rv = refp->GetAccessibleFor(node, getter_AddRefs(accnode)); if(NS_FAILED(rv)){ return self; } void *wh = NULL; nsCOMPtr<nsIAcce...
...D getHwnd(nsIDOMNode *node){ HWND self = NULL; nsresult rv; nsCOMPtr<nsIAccessibleRetrieval> refp; refp = do_CreateInstance( "@mozilla.org/accessibleRetrieval;1", &rv); if (NS_FAILED(rv)){ return self; } //line 6. nsCOMPtr<nsIAccessible> accnode; rv = refp->GetAccessibleFor(node, getter_AddRefs(accnode)); if(NS_FAILED(rv)){ return self; } void *wh = NULL; nsCOMPtr<nsIAccessibleDocument> accdocnode; accdocnode = do_QueryInterface(accnode, &rv); if(NS_FAILED(rv)){ return self; } rv = accdocnode->GetWindowHandle(&wh); if(NS_SUCCEEDED(rv)){ self = static_cast<HWND>(wh); } return self; } This approach worked, as is, for versions as early as Firefox 1.5. The problem arises when one tries to run an extension built with the latest SDK in an older version of Firefox, say Fire...
...First the good news. Plan B inside Firefox 2 happily runs to completion. All the XPCOM calls succeed, or at least think they suc...
...And 5 more matches
Add to iPhoto
an write the core of the extension itself. This is done in the iPhoto object in the extension's code. Hooking up to the context menu On startup, we find the content area's context menu and add an event listener to it that will be called when the context menu is displayed. We'll use our handler for this event to add the "Add Image to iPhoto" option if the user has right-clicked on an image. ...
... in the iPhoto object in the extension's code. Hooking up to the context menu On startup, we find the content area's context menu and add an event listener to it that will be called when the context menu is displayed. We'll use our handler for this event to add the "Add Image to iPhoto" option if the user has right-clicked on an image. ...
...ion if the user has right-clicked on an image. if (document.getElementById("contentAreaContextMenu")) { document.getElementById("contentAreaContextMenu").addEventListener("popupshowing", iPhoto.onPopup, false); } Responding when the context menu is clicked When the user right-clicks an image, our handler gets called: onPopup: function() { var node = iPhoto.getCurrentNode(); var item = document.getElementById("add-to-iphoto_menuitem"); if (item) { item.hidden = (node == null); // Hide it if we're not on an image } } This code finds the image node the user right-clicked in by calling our getCurrentNode() method, then sets the hidden state of the "Add Image to iPhoto" menu item based on whether or not an image node was found. The code to identify the node looks like this: get...
...And 5 more matches
DOM Inspector internals - Firefox Developer Tools
ctor and DOM Inspector sidebar used in SeaMonkey). Initially, we will begin by focusing on inspector.xul and its entry point, and then expand our focus later to explain how these other inspectors differ. DOM Inspector from a high-level perspective The DOM inspector primary UI consists of some toolbars and a panelset. The panelset contains two panels. One panel reacts to changes to the inspected document, and the other panel reacts to changes to the selection in the first panel. These are the document panel and the object panel, respectively. (Internally, a panel may be loosely referred to as a "pane", but a panelset is always referred to as a "panelset".) A panel's purpose is to manage available viewers. At the top of each panel is a toolbar which contains a menu button allowing you to choose w...
...specific commands. Viewers are dynamically loaded; when the panel is made to switch from one viewer to another, the old viewer is destroyed, and the new viewer is loaded in its place. In this way, the panelset and panels function like a frameset and frames. This comparison turns out to be quite apt, since each panel actually contains an anonymous browser, and individual viewers exist in separate documents loaded in the browser. This separation allows for viewers to be self-contained, with a viewer's XUL defined in its own document and loaded in its own scope, without fear of collisions in the XUL, CSS, or JS. Another convenient consequence of this is that if you use a properly set up development profile, then for the most part, the effects of development changes can be seen by simply switching aw...
...ector.xul. These are pulled in from a series of overlays, so that the XUL defining DOM Inspector's UI can be organized into discrete units. inspector.xul itself is only a skeleton describing the basic structure and layout of the primary DOM Inspector window, leaving most of its contents to be added by the overlays. Using modular overlays also allows for common XUL to be shared across the various documents that make up the DOM Inspector's UI, although not all overlays are shared by multiple consumers. Single-consumer overlays exist solely for organization. In some cases overlays are overlaid by other overlays. If we imagine a tree structure obtained by connecting overlays as children to the files they overlay, while ignoring any overlays used for host integration, we can visualize the host-agno...
...And 5 more matches
The JavaScript input interpreter - Firefox Developer Tools
rl+S on Mac) to search forward in the list of matches. You can also use the ? and ? icons in the expression search bar. When you find the expression you want, press Enter (Return) to execute the statement. ...
...the expression you want, press Enter (Return) to execute the statement. Working with iframes If a page contains embedded iframes, you can use the cd() function to change the console's scope to a specific iframe, and then you can execute functions defined in the document hosted by that iframe. ...
...nsole's scope to a specific iframe, and then you can execute functions defined in the document hosted by that iframe. ...
...And 5 more matches
CSSStyleSheet - Web APIs
turns a live CSSRuleList which maintains an up-to-date list of the CSSRule objects that comprise the stylesheet. This is normally used to access individual rules like this: styleSheet.cssRules[i] // where i = 0..cssRules.length-1 To add or remove items in cssRules, use the CSSStyleSheet's insertRule() and deleteRule() methods. ownerRule Read only If this stylesheet is imported into the document using an @import rule, the ownerRule property returns the corresponding CSSImportRule; otherwise, this property's value is null. Methods Inherits methods from its parent, StyleSheet. deleteRule() Deletes the rule at the specified index into the stylesheet's rule list. insertRule() Inserts a new rule at the specified position in the stylesheet, given the textual representation of the rule...
...om insertRule(), which simply takes the textual representation of the entire rule as a single string. removeRule() Functionally identical to deleteRule(); removes the rule at the specified index from the stylesheet's rule list. Notes In some browsers, if a stylesheet is loaded from a different domain, accessing cssRules results in SecurityError. ...
... string. removeRule() Functionally identical to deleteRule(); removes the rule at the specified index from the stylesheet's rule list. Notes In some browsers, if a stylesheet is loaded from a different domain, accessing cssRules results in SecurityError. A stylesheet is associated with at most one Document, which it applies to (unless disabled). A list of CSSStyleSheet objects for a given document can be obtained using the document.styleSheets property. A specific style sheet can also be accessed from its owner object (Node or CSSImportRule), if any. A CSSStyleSheet object is created and inserted into the document's Document.styleSheets list automatically by the browser, when a stylesheet is loaded for a document. As the stylesheet list cannot be modified directly, there's no useful way t...
...And 5 more matches
Element: fullscreenchange event - Web APIs
vent Event handler property onfullscreenchange This event is sent to the Element which is transitioning into or out of full-screen mode. Examples In this example, a handler for the fullscreenchange event is added to the element whose ID is fullscreen-div. If the user clicks on the "Toggle Fullscreen Mode" button, the click handler will toggle full-screen mode for the div. ...
...If the user clicks on the "Toggle Fullscreen Mode" button, the click handler will toggle full-screen mode for the div. If document.fullscreenElement has a value it will exit full-screen mode. If not, the div will be placed into full-screen mode. Remember that by the time the fullscreenchange event is handled, the status of the element has already changed. So if the change is to full-screen mode, document.fullscreenElement will point to the element that is now in full-screen mode. On the other hand, if document.fullscreenElement is null, full-screen mode has been canceled. ...
... if the change is to full-screen mode, document.fullscreenElement will point to the element that is now in full-screen mode. On the other hand, if document.fullscreenElement is null, full-screen mode has been canceled. What that means to the example code 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. ...
...And 5 more matches
Element.querySelectorAll() - Web APIs
d list is always empty. Exceptions SyntaxError The syntax of the specified selectors string is not valid. ...
... Examples dataset selector & attribute selectors <section class="box" id="sect1"> <div class="funnel-chart-percent1">10.900%</div> <div class="funnel-chart-percent2">3700.00%</div> <div class="funnel-chart-percent3">0.00%</div> </section> // dataset selectors const refs = [...document.querySelectorAll(`[data-name*="funnel-chart-percent"]`)]; // attribute selectors // const refs = [...document.querySelectorAll(`[class*="funnel-chart-percent"]`)]; // const refs = [...document.querySelectorAll(`[class^="funnel-chart-percent"]`)]; // const refs = [...document.querySelectorAll(`[class$="funnel-chart-percent"]`)]; // const refs = [...document.querySelectorAll(`[class~="funnel-chart-percent"]`)]; Obtaining a list of matches To obtain a NodeList of all of the <p> elements contained within ...
...ll(`[class~="funnel-chart-percent"]`)]; Obtaining a list of matches To obtain a NodeList of all of the <p> elements contained within the element "myBox": var matches = myBox.querySelectorAll("p"); This example returns a list of all <div> elements within "myBox" with a class of either "note" or "alert": var matches = myBox.querySelectorAll("div.note, div.alert"); Here, we get a list of the document's <p> elements whose immediate parent element is a div with the class "highlighted" and which are located inside a container whose ID is "test". var container = document.querySelector("#test"); var matches = container.querySelectorAll("div.highlighted > p"); This example uses an attribute selector to return a list of the iframe elements in the document that contain an attribute named "data-src"...
...And 5 more matches
HTMLFormElement - Web APIs
onformdata property. reset The reset event fires when a form is reset. Also available via the onreset property. submit The submit event fires when a form is submitted. Also available via the onsubmit property. ...
...set event fires when a form is reset. Also available via the onreset property. submit The submit event fires when a form is submitted. Also available via the onsubmit property. Usage notes Obtaining a form element object To obtain an HTMLFormElement object, you can use a CSS selector with querySelector(), or you can get a list of all of the forms in the document using its forms property. Document.forms returns an array of HTMLFormElement objects listing each of the forms on the page. You can then use any of the following syntaxes to get an individual form: document.forms[index] Returns the form at the specified index into the array of forms. document.forms[id] Returns the form whose ID is id. document.forms[name] Returns the form whose name attribute's value is name. Accessing t...
...set> <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 elements, which makes it an excellent way to get at the elements most important when processing forms. ...
...And 5 more matches
HTMLScriptElement - Web APIs
ies Inherits properties from its parent, HTMLElement. HTMLScriptElement.type Is a DOMString representing the MIME type of the script. It reflects the type attribute. HTMLScriptElement.src Is a DOMString representing the URL of an external script. It reflects the src attribute. HTMLScriptElement.event Is a DOMString; an obsolete way of registering event handlers on elements in an HTML document. HTMLScriptElement.charset Is a DOMString representing the character encoding of an external script. It reflects the charset attribute. HTMLScriptElement.async HTMLScriptElement.defer The async and defer attributes are Boolean attributes that control how the script should be executed. The defer and async attributes must not be specified if the src attribute is absent. There are three...
...he defer behavior instead of the default blocking behavior. Note: The exact processing details for these attributes are complex, involving many different aspects of HTML, and therefore are scattered throughout the specification. These algorithms describe the core ideas, but they rely on the parsing rules for <script> start and end tags in HTML, in foreign content, and in XML; the rules for the document.write() method; the handling of scripting; and so on. HTMLScriptElement.crossOrigin Is a DOMString reflecting the CORS setting for the script element. For scripts from other origins, this controls if error information will be exposed. HTMLScriptElement.text Is a DOMString that joins and returns the contents of all Text nodes inside the <script> element (ignoring other nodes like commen...
... CORS setting for the script element. For scripts from other origins, this controls if error information will be exposed. HTMLScriptElement.text Is a DOMString that joins and returns the contents of all Text nodes inside the <script> element (ignoring other nodes like comments) in tree order. On setting, it acts the same way as the textContent 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 ...
...And 5 more matches
HTMLSelectElement.add() - Web APIs
the collection, or an index of type long, representing the item item should be inserted before. If this parameter is null (or the index does not exist), the new element is appended to the end of the collection. Exceptions A DOMError of the type HierarchyRequestError if the item passed to the method is an ancestor of the HTMLSelectElement. ...
...resenting the item item should be inserted before. If this parameter is null (or the index does not exist), the new element is appended to the end of the collection. Exceptions A DOMError of the type HierarchyRequestError if the item passed to the method is an ancestor of the HTMLSelectElement. ...
...fore. If this parameter is null (or the index does not exist), the new element is appended to the end of the collection. Exceptions A DOMError of the type HierarchyRequestError if the item passed to the method is an ancestor of the HTMLSelectElement. Examples Creating Elements from Scratch var sel = document.createElement("select"); var opt1 = document.createElement("option"); var opt2 = document.createElement("option"); opt1.value = "1"; opt1.text = "Option: Value 1"; opt2.value = "2"; opt2.text = "Option: Value 2"; sel.add(opt1, null); sel.add(opt2, null); /* Produces the following, conceptually: <select> <option value="1">Option: Value 1</option> <option value="2">Option: Value 2</option> </select> */ The before parameter is optional. So the following is accepted. ...
...And 5 more matches
Using the MediaStream Recording API - Web APIs
qual to 100% of the parent height, minus the heights and padding of the other two: .sound-clips { box-shadow: inset 0 3px 4px rgba(0,0,0,0.7); background-color: rgba(0,0,0,0.1); height: calc(100% - 240px - 0.7rem); overflow: scroll; } Note: calc() has good support across modern browsers too, even going back to Internet Explorer 9. Checkbox hack for showing/hiding This is fairly well documented already, but we thought we'd give a mention to the checkbox hack, which abuses the fact that you can click on the <label> of a checkbox to toggle it checked/unchecked. In Web Dictaphone this powers the Information screen, which is shown/hidden by clicking the question mark icon in the top right hand corner. First of all, we style the <label> how we want it, making sure that it has enough z-inde...
...X(0); } Basic app setup To grab the media stream we want to capture, we use getUserMedia(). We then use the MediaRecorder API to record the stream, and output each recorded snippet into the source of a generated <audio> element so it can be played back. ...
...am we want to capture, we use getUserMedia(). We then use the MediaRecorder API to record the stream, and output each recorded snippet into the source of a generated <audio> element so it can be played back. ...
...And 5 more matches
Node.nodeType - Web APIs
Web › API › Node › nodeType
stants. Constants Node type constants Constant Value Description Node.ELEMENT_NODE 1 An Element node like <p> or <div>. Node.TEXT_NODE 3 The actual Text inside an Element or Attr. Node.CDATA_SECTION_NODE 4 A CDATASection, such as <!CDATA[[ ... ]]>. Node.PROCESSING_INSTRUCTION_NODE 7 A ProcessingInstruction of an XML document, such as <?xml-stylesheet ... ?>. Node.COMMENT_NODE 8 A Comment node, such as <!-- ... -->. Node.DOCUMENT_NODE 9 A Document node. Node.DOCUMENT_TYPE_NODE 10 A DocumentType node, such as <!DOCTYPE html>. Node.DOCUMENT_FRAGMENT_NODE 11 A DocumentFragment node. Deprecated node type constants The following constants have been depr...
...An Attribute of an Element. Attributes no longer implement the Node interface as of DOM4. Node.ENTITY_REFERENCE_NODE 5 An XML Entity Reference node, such as &foo;. Removed in DOM4. Node.ENTITY_NODE 6 An XML <!ENTITY ...> node. Removed in DOM4. Node.NOTATION_NODE 12 An XML <!NOTATION ...> node. Removed in DOM4. ...
... Attributes no longer implement the Node interface as of DOM4. Node.ENTITY_REFERENCE_NODE 5 An XML Entity Reference node, such as &foo;. Removed in DOM4. Node.ENTITY_NODE 6 An XML <!ENTITY ...> node. Removed in DOM4. Node.NOTATION_NODE 12 An XML <!NOTATION ...> node. Removed in DOM4. ...
...And 5 more matches
PerformanceTiming - Web APIs
ents; others describe the time at which internal browser operations of interest took place. Each time is provided as an unsigned long long representing the moment, in milliseconds since the UNIX epoch These properties are listed in the order in which they occur during the navigation process. ...
...ions of interest took place. Each time is provided as an unsigned long long representing the moment, in milliseconds since the UNIX epoch These properties are listed in the order in which they occur during the navigation process. PerformanceTiming.navigationStart Read only When the prompt for unload terminates on the previous document in the same browsing context. If there is no previous document, this value will be the same as PerformanceTiming.fetchStart. PerformanceTiming.unloadEventStart Read only When the unload event has been thrown, indicating the time at which the previous document in the window began to unload. If there is no previous document, or if the previous document or one of the needed redirects is not of the same origin, the value returned is 0. PerformanceTiming...
... PerformanceTiming.redirectStart Read only When the first HTTP redirect starts. ...
...And 5 more matches
Pointer events - Web APIs
nse input from an input device such as a pen, stylus, or finger. Some sensing devices can detect the close proximity of the input device, and the state is expressed as a hover following the mouse. hit test The process the browser uses to determine a target element for a pointer event. Typically, this is determined by considering the pointer's location and also the visual layout of elements in a document on screen media. pointer A hardware-agnostic representation of input devices that can target a specific coordinate (or set of coordinates) on a screen. Examples of pointer input devices are mouse, pen/stylus, and touch contacts. pointer capture Pointer capture allows the events for a pointer to be retargeted to a particular element other than the normal hit test result of the pointer's locati...
...ndler(event) { } function enter_handler(event) { } function down_handler(event) { } function move_handler(event) { } function up_handler(event) { } function cancel_handler(event) { } function out_handler(event) { } function leave_handler(event) { } function gotcapture_handler(event) { } function lostcapture_handler(event) { } function init() { var el=document.getElementById("target"); // Register pointer event handlers el.onpointerover = over_handler; el.onpointerenter = enter_handler; el.onpointerdown = down_handler; el.onpointermove = move_handler; el.onpointerup = up_handler; el.onpointercancel = cancel_handler; el.onpointerout = out_handler; el.onpointerleave = leave_handler; el.gotpointe...
...</div> </body> </html> Determining the Primary Pointer In some scenarios there may be multiple pointers (for example a device with both a touchscreen and a mouse) or a pointer supports multiple contact points (fo...
...And 5 more matches
Range.extractContents() - Web APIs
The Range.extractContents() method moves contents of the Range from the document tree into a DocumentFragment. Event listeners added using DOM Events are not retained during extraction. HTML attribute events are retained or duplicated as they are for the Node.cloneNode() method. HTML id attributes are also cloned, which can lead to an invalid document if a partially-selected node is extracted and appended to the document. Partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid. ...
...nts are not retained during extraction. HTML attribute events are retained or duplicated as they are for the Node.cloneNode() method. HTML id attributes are also cloned, which can lead to an invalid document if a partially-selected node is extracted and appended to the document. Partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid. Syntax documentFragment = range.extractContents(); Example Basic example var range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); var documentFragment = range.extractContents(); document.body.appendChild(documentFragment); Moving items between containers This example lets you move items between two containers. Select one or more item, and then click "swap" to mov...
...ers. Select one or more item, and then click "swap" to move them to the opposite container. ...
...And 5 more matches
Selection - Web APIs
Web › API › Selection
The anchor is where the user began the selection and the focus is where the user ends the selection. ...
...The anchor is where the user began the selection and the focus is where the user ends the selection. ...
... focus is placed where you released the mouse button. Anchor and focus should not be confused with the start and end positions of a selection. The anchor can be placed before the focus or vice-versa, depending on the direction you made your selection. Properties Selection.anchorNodeRead only Returns the Node in which the selection begins. Can return null if selection never existed in the document (e.g., an iframe that was never clicked on). Selection.anchorOffsetRead only Returns a number representing the offset of the selection's anchor within the anchorNode. If anchorNode is a text node, this is the number of characters within anchorNode preceding the anchor. If anchorNode is an element, this is the number of child nodes of the anchorNode preceding the anchor. Selection.focusNodeRea...
...And 5 more matches
SpeechSynthesis - Web APIs
voice they want. Inside the inputForm.onsubmit handler, we stop the form submitting with preventDefault(), create a new SpeechSynthesisUtterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the SpeechSynthesis.speak() method. ...
...t handler, we stop the form submitting with preventDefault(), create a new SpeechSynthesisUtterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the SpeechSynthesis.speak() method. ...
...tDefault(), create a new SpeechSynthesisUtterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the SpeechSynthesis.speak() method. ...
...And 5 more matches
SubtleCrypto.exportKey() - Web APIs
aw export This example exports an AES key as an ArrayBuffer containing the bytes for the key. See the complete code on GitHub. /* Export the given key and write it into the "exported-key" space. ...
...The exported key is then PEM-encoded. See the complete code on GitHub. ...
... and write it into the "exported-key" space. */ async function exportCryptoKey(key) { const exported = await window.crypto.subtle.exportKey( "pkcs8", key ); const exportedAsString = ab2str(exported); const exportedAsBase64 = window.btoa(exportedAsString); const pemExported = `-----BEGIN PRIVATE KEY-----\n${exportedAsBase64}\n-----END PRIVATE KEY-----`; const exportKeyOutput = document.querySelector(".exported-key"); exportKeyOutput.textContent = pemExported; } /* Generate a sign/verify key pair, then set up an event listener on the "Export" button. */ window.crypto.subtle.generateKey( { name: "RSA-PSS", // Consider using a 4096-bit key for systems that require long-term security modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA...
...And 5 more matches
SubtleCrypto.verify() - Web APIs
e verify() method supports the same algorithms as the sign() method. Examples Note: You can try the working examples out on GitHub. RSASSA-PKCS1-v1_5 This code uses a public key to verify a signature. See the complete code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. ...
...x = document.querySelector(".rsassa-pkcs1 #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } /* Fetch the encoded message-to-sign and verify it against the stored signature. * If it checks out, set the "valid" class on the signature. * Otherwise set the "invalid" class. */ async function verifyMessage(publicKey) { const signatureValue = document.querySelector(".rsassa-pkcs1 .signature-value"); signatureValue.classList.remove("valid", "invalid"); let encoded = getMessageEncoding(); let result = await window.crypto.subtle.verify( "RSASSA-PKCS1-v1_5", publicKey, signature, encoded ); signatureValue.classList.add(result ? "valid" : "invalid"); } RSA-PSS This code uses a public key to verify a signature. See the ...
....verify( "RSASSA-PKCS1-v1_5", publicKey, signature, encoded ); signatureValue.classList.add(result ? "valid" : "invalid"); } RSA-PSS This code uses a public key to verify a signature. See the complete code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. ...
...And 5 more matches
Touch events - Web APIs
e, also be a stylus or other contact method. Create a canvas <canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> Your browser does not support canvas element. </canvas> <br> Log: <pre id="log" style="border: 1px solid #ccc;"></pre> Setting up the event handlers When the page loads, the startup() function shown below will be called. ...
... Tracking new touches We'll keep track of the touches in-progress. ...
...rs for our <canvas> element so we can handle the touch events as they occur. Tracking new touches We'll keep track of the touches in-progress. var ongoingTouches = []; When a touchstart event occurs, indicating that a new touch on the surface has occurred, the handleStart() function below is called. ...
...And 5 more matches
TreeWalker - Web APIs
A TreeWalker can be created using the Document.createTreeWalker() method. Properties This interface doesn't inherit any property. TreeWalker.root Read only Returns a Node representing the root node as specified when the TreeWalker was created. TreeWalker.whatToShow Read only Returns an unsigned long being a bitmask made of constants describing the types of Node that must be presented. Non-matching nodes are skipped, but their children may be included, if relevant. ...
...gned long) Shows all nodes. NodeFilter.SHOW_ATTRIBUTE 2 Shows attribute Attr nodes. This is meaningful only when creating a TreeWalker with an Attr node as its root. In this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree. NodeFilter.SHOW_CDATA_SECTION 8 Shows CDATASection nodes. NodeFilter.SHOW_COMMENT 128 Shows Comment nodes. NodeFilter.SHOW_DOCUMENT 256 Shows Document nodes. NodeFilter.SHOW_DOCUMENT_FRAGMENT 1024 Shows DocumentFragment nodes. NodeFilter.SHOW_DOCUMENT_TYPE 512 Shows DocumentType nodes. ...
...CUMENT_TYPE 512 Shows DocumentType nodes. NodeFilter.SHOW_ELEMENT 1 Shows Element nodes. NodeFilter.SHOW_ENTITY 32 Shows Entity nodes. This is meaningful only when creating a TreeWalker with an Entity node as its root; in this case, it means that the Entity node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree. NodeFilter.SHOW_ENTITY_REFERENCE 16 Shows EntityReference nodes. NodeFilter.SHOW_NOTATION 2048 Shows Notation nodes. This is meaningful only when creating a TreeWalker with a Notation node as its root; in this case, it means that the Notation node will appear in the first position of the t...
...And 5 more matches
ARIA Test Cases - Accessibility
plement ARIA, and the noted test files could be used as an "ARIA test file". New Tests for Internet Explorer 8 RC1 On this MSDN page the ARIA state/role mapping in IE8 to MSAA Roles can be directly checked. Also, as a clever feature for AT testing, the firing of events (like EVENT_OBJECT_STATECHANGE) can be invoked from the examples. Finally, a list of currently non-mapped ARIA roles is given. Documenting and Filing Bugs Review the information on how to file a bug on an ARIA implementation. When documenting an issue, please also list it in the relevant compatibility table below. When possible provide a link to the bug in the database so that its status can be reviewed. Widget Test Cases Alert Simple alert Complex Alert Real alert example with aria-required and aria-invalid -- type in a ...
...reader supports this in other lists as well. As focus moves within the list, the screen reader should announce the relevant list items. ...
... Safari JAWS 9 - - n/a n/a JAWS 10 - - - - VoiceOver (Leopard) n/a n/a - fail Window-Eyes - - - - NVDA - n/a - - Zoom (Leopard) pass n/a pass pass ZoomText - - - - Orca - - - - Tree dojo nightly build Simple tree -- uses document structure to create hierarchy Tree - Subtrees are encapsulated in treeitems MS IE8 Tree example We need an example that uses aria-level, aria-setsize and aria-posinset to create the hierarchy We also need one that uses aria-owns to create the hierarchy / structure We need one that uses the document to create structure, but uses nested ULs with links inside, and role="presentation" Expected...
...And 5 more matches
ARIA annotations - Accessibility
Below we'll introduce the new features associated with ARIA annotations, and have a look at some code examples that show them in action. Note: You can find all the examples discussed in this article in a demo file at aria-annotations. ...
... Below we'll introduce the new features associated with ARIA annotations, and have a look at some code examples that show them in action. Note: You can find all the examples discussed in this article in a demo file at aria-annotations. ...
... Below we'll introduce the new features associated with ARIA annotations, and have a look at some code examples that show them in action. Note: You can find all the examples discussed in this article in a demo file at aria-annotations. ...
...And 5 more matches
Cubic Bezier Generator - CSS: Cascading Style Sheets
ut onchange="updateCanvas();return true;" type="text" maxlength=6 id="x2" value="0.14" class='field'> <label for="y2">y2 = </label><input onchange="updateCanvas();return true;" type="text" maxlength=6 id="y2" value="0.53" class='field'> <br> <output id="output">Log</output> </form> </html> .field { width: 40px; } function updateCanvas() { var x1 = document.getElementById('x1').value; var y1 = document.getElementById('y1').value; var x2 = document.getElementById('x2').value; var y2 = document.getElementById('y2').value; drawBezierCurve(x1, y1, x2, y2); } const radius = 4; // Place needed to draw the rulers const rulers = 30.5; const margin = 10.5; const basic_scale_size = 5; // Size of 0.1 tick on the rulers var scaling; //LIMITATI...
...aw the rulers const rulers = 30.5; const margin = 10.5; const basic_scale_size = 5; // Size of 0.1 tick on the rulers var scaling; //LIMITATION: scaling is computed once: if canvas.height/canvas.width change it won't be recalculated var dragSM = 0; // Drag state machine: 0 = nodrag, others = object being dragged function initCanvas() { // get the canvas element using the DOM var canvas = document.getElementById('bezier'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); scaling = Math.min(canvas.height - rulers - margin, canvas.width - rulers - margin); canvas.onmousedown = mouseDown; canvas.onmouseup = mouseUp; } else ...
...on cY(y) { return (1 - y) * scaling + margin; } function reverseY(y) { return (margin - y) / scaling + 1; } function lY(y) { // Used when drawing horizontal lines to prevent subpixel blur var result = cY(y); return Math.round(result) == result ? ...
...And 5 more matches
<color> - CSS: Cascading Style Sheets
widely supported by browsers. The keywords in the following list are defined by the CSS Color Module Level 4 specification. Note that these keywords are case insensitive, but are listed here with mixed case for readability. ...
...wing list are defined by the CSS Color Module Level 4 specification. Note that these keywords are case insensitive, but are listed here with mixed case for readability. ...
... VisitedText Text of visited links Deprecated system color keywords The following keywords were defined in earlier versions of the CSS Color Module. They are now deprecated. for use on public web pages. ActiveBorder Active window border. ActiveCaption Active window caption. Should be used with CaptionText as foreground color. AppWorkspace Background color of multiple document interface. Background Desktop background. ButtonHighlight The color of the border facing the light source for 3-D elements that appear 3-D due to that layer of surrounding border. ButtonShadow The color of the border away from the light source for 3-D elements that appear 3-D due to that layer of surrounding border. CaptionText Text in caption, size box, and scrollbar arro...
...And 5 more matches
Adding captions and subtitles to HTML5 video - Developer guides
n video controls, this button is hidden, and we need to define our own. Browsers do vary as to what they support, so we will be attempting to bring a more unified UI to each browser where possible. There's more on browser compatibility issues later on. Initial setup As with all the other buttons, one of the first things we need to do is store a handle to the subtitles' button: var subtitles = document.getElementById('subtitles'); We also initially turn off all subtitles, in case the browser turns any of them on by default: for (var i = 0; i < video.textTracks.length; i++) { video.textTracks[i].mode = 'hidden'; } The video.textTracks property contains an array of all the text tracks attached to the video. We loop through each one and set its mode to hidden. Note: The WebVTT API gives us ...
...before we make it do anything, we need to build the menu that goes with it. This menu is built dynamically, so that languages can be added or removed later by simply editing the <track> elements within the video's markup. ...
...it do anything, we need to build the menu that goes with it. This menu is built dynamically, so that languages can be added or removed later by simply editing the <track> elements within the video's markup. ...
...And 5 more matches
<input type="week"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › week
ing 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. ...
...e browser supports <input type="week">, we create a new <input> element, try setting its type to week, then immediately check what its type is set to. Non-supporting browsers will return text, because the week type falls back to type text. If <input type="week"> is not supported, we hide the native picker and show the fallback picker UI (<select>s) instead. ...
...ement, try setting its type to week, then immediately check what its type is set to. Non-supporting browsers will return text, because the week type falls back to type text. If <input type="week"> is not supported, we hide the native picker and show the fallback picker UI (<select>s) instead. ...
...And 5 more matches
<link>: The External Resource Link element - HTML: Hypertext Markup Language
Web › HTML › Element › link
This element is most commonly used to link to stylesheets, but is also used to establish site icons (both "favicon" style icons and icons for the home screen and apps on mobile devices) among other things. 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. ...
...lude a <link> element inside your <head> like this: <link href="main.css" rel="stylesheet"> This simple example provides the path to the stylesheet inside an href attribute, and a rel attribute with a value of stylesheet. The rel stands for "relationship", and is probably one of the key features of the <link> element -- the value denotes how the item being linked to is related to the containing document. As you'll see from our Link types reference, there are many different kinds of relationship. There are a number of other common types you'll come across. For example, a link to the site's favicon: <link rel="icon" href="favicon.ico"> There are a number of other icon rel values, mainly used to indicate special icon types for use on various mobile platforms, e.g.: <link rel="apple-touch-icon-p...
... not loading, verify that the Content-Security-Policy header's img-src directive is not preventing access to it. The HTML and XHTML specifications define event handlers for the <link> element, but it is unclear how they would be used. Under XHTML 1.0, empty elements such as <link> require a trailing slash: <link />. WebTV supports the use of the value next for rel to preload the next page in a document series. Attributes This element includes the global attributes. as This attribute is only used when rel="preload" or rel="prefetch" has been set on the <link> element. It specifies the type of content being loaded by the <link>, which is necessary for request matching, application of correct content security policy, and setting of correct Accept request header. Furthermore, rel="preload" u...
...And 5 more matches
Index - XPath
Web › XPath › Index
Found 57 pages: # Page Tags and summary 1 XPath CSS Selectors, DOM, JXON, Landing, Path, XML, XPath, XSLT XPath stands for XML Path Language. It uses a non-XML syntax to provide a flexible way of addressing (pointing to) different parts of an XML document. It can also be used to test addressed nodes within a document to determine whether they match a pattern or not. 2 Axes Transforming_XML_with_XSLT, XPath, XPath_Reference, XSLT, XSLT_Reference For further information on using XPath expressions, please see the For Further Reading section at the end of Transforming XML with XSLT document. Also see the 'axes' section in the xpath spec. 3 ancestor Axe, XPath No summary! 4 ancestor-or-self Axe, XPath ...
...ldren of their parents. 9 following Axe, XPath The following axis indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes. 10 following-sibling Axe, XPath The following-sibling axis indicates all the nodes that have the same parent as the context node and appear after the context node in the source document. ...
... 15 self Axe, XPath The self axis indicates the context node itself. ...
...And 5 more matches
context-menu - Archive of obsolete content
ner function for this event and it returns true, the menu item associated with the listener's content script is shown in the menu. For example, this item appears whenever the context menu is invoked on a page that contains at least one image: require("sdk/context-menu").Item({ label: "This Page Has Images", contentScript: 'self.on("context", function (node) {' + ' return !!document.querySelector("img");' + '});' }); Note that the listener function has a parameter called node. This is the node in the page that the user context-clicked to invoke the menu. You can use it to determine whether your item should be shown. You can both specify declarative contexts and listen for contexts in a content script. Your context listener is called even if any declarative...
..."sdk/selection"); and within the contentScript, reference the selected text as selection.text Private windows If your add-on has not opted into private browsing, then any menus or menu items that you add will not appear in context menus belonging to private browser windows. To learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module. More examples For conciseness, these examples create their content scripts as strings and use the contentScript property. In your own add-on, you will probably want to create your content scripts in separate files and pass their URLs using the contentScriptFile property. See Working with Content Scripts for more information. Warning: Unless your content s...
...keep the script in a separate file and load it using contentScriptFile. This makes your code easier to maintain, secure, debug and review. ...
...And 4 more matches
On page load - Archive of obsolete content
This article is for XUL/JavaScript developers who want to have custom code executed each time a new page is loaded in browser/mail. 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. ...
...r 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. ...
...tach a script to your overlay (see "Attaching a Script to an Overlay") that adds a load event listener to appcontent element (browsers) or messagepane (mail): window.addEventListener("load", function load(event){ window.removeEventListener("load", load, false); //remove listener, no longer needed myExtension.init(); },false); var myExtension = { init: function() { var appcontent = document.getElementById("appcontent"); // browser if(appcontent){ appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true); } var messagepane = document.getElementById("messagepane"); // mail if(messagepane){ messagepane.addEventListener("load", function(event) { myExtension.onPageLoad(event); }, true); } }, onPageLoad: function(aEvent) { var...
...And 4 more matches
QuerySelector - Archive of obsolete content
Along the lines of other frameworks such as jQuery or Prototype, shortening the "querySelector" name can be convenient: function $ (selector, el) { if (!el) {el = document;} return el.querySelector(selector); } function $$ (selector, el) { if (!el) {el = document;} return el.querySelectorAll(selector); // Note: the returned object is a NodeList. // If you'd like to convert it to a Array for convenience, use this instead: // return Array.prototype.slice.call(el.querySelectorAll(selector)); } alert($('#myID').id); (Note that while using the Firefox Web Console, the above functions are available automatically.) Both XUL and even XML can be easily made supportable (an alternative approach to the following would be to add ChromeWindow.prototype or Window.prototype, ...
...r convenience, use this instead: // return Array.prototype.slice.call(el.querySelectorAll(selector)); } alert($('#myID').id); (Note that while using the Firefox Web Console, the above functions are available automatically.) Both XUL and even XML can be easily made supportable (an alternative approach to the following would be to add ChromeWindow.prototype or Window.prototype, accessing this.document.querySelector, or following the jQuery style of chaining by returning 'this' within each prototype method of $()): HTMLDocument.prototype.$ = function (selector) { // Only for HTML return this.querySelector(selector); }; Example: <h1>Test!</h1> <script> HTMLDocument.prototype.$ = function (selector) { return this.querySelector(selector); }; alert(document.$('h1')); // [object HTMLHeadin...
...wing the jQuery style of chaining by returning 'this' within each prototype method of $()): HTMLDocument.prototype.$ = function (selector) { // Only for HTML 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 f...
...And 4 more matches
Sidebar - Archive of obsolete content
this bookmark in sidebar" checked in the properties open in the "viewWebPanelsSidebar". A web page can use window.sidebar to create bookmark with that property. To open a page in the "viewWebPanelsSidebar" from chrome code (browser/addon/extension) such as from menuitem, it can call: openWebPanel(aTitle, aURI); Accessing the sidebar from a browser.xul script The sidebar content is always in a document separate from the main browser document (the sidebar is actually implemented as a XUL browser element). This means you can't directly access the sidebar content from a script referenced from a browser.xul overlay. To access your sidebar's window or document objects, you need to use the contentWindow or contentDocument properties of document.getElementById("sidebar") respectively. For example the...
...UL browser element). This means you can't directly access the sidebar content from a script referenced from a browser.xul overlay. To access your sidebar's window or document objects, you need to use the contentWindow or contentDocument properties of document.getElementById("sidebar") respectively. ...
...barWindow.yourNotificationFunction(anyArguments); } Testing which sidebar is open The sidebar content may contain different panels (bookmarks, history, webpanel, etc.) and sometimes one wants to only act on the sidebar when it contains a specific panel. ...
...And 4 more matches
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
and was originally published in Japanese for the Firefox Developers Conference Summer 2007. Shimoda-san is a co-author of Firefox 3 Hacks (O'Reilly Japan, 2008). Before we dive into a thorough explanation, we'll quickly introduce the technologies used to develop Firefox extensions. We will also look at the minimum knowledge you'll need to have in order to develop for Firefox. Technologies used to develop Firefox extensions Firefox and its extensions are both based on and developed with technologies widely used on the web. ...
...d in one another as a means to extend the language. All elements can carry a "namespace URI" identifier, which is unique for each language. For example, even though XHTML and SVG have elements with the same name, these can be distinguished. The namespace URI for XHTML is "http://www.w3.org/1999/xhtml" ; for SVG is it "http://www.w3.org/2000/svg". CSS: A style language to alter the display of XML documents Like XML, Cascading Style Sheets (CSS) is a technical specification established by the W3C; it is a style-description language defining the display of data marked up in XML and HTML. As shown in Listing 1, it has an extremely simple syntax. By separating the structure of the data, expressed through HTML or XML, and the display style, indicated by CSS, data can be reused better than it is when s...
...xtensions to the specification standardized in ECMAScript 3rd Edition, and can use JavaScript 1.7 and JavaScript 1.8. ...
...And 4 more matches
XPCOM Objects - Archive of obsolete content
n previous examples. this.obsService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService); The Cc object (Components.classes) is an index to static objects and class definitions available through XPCOM. The string between the brackets is just an identifier, in this case corresponding to the Observer service. You'll usually know what string to use by reading examples and documentation. There is no comprehensive list of these (that we know of), and that's understandable since it would be a very long list, and it can be extended by add-ons. If you want to see the list in your current Firefox installation, just run the following code in the Error Console: var str = ""; for (var i in Components.classes) { str += i + "\n" }; str A run on Firefox 3.6.2 with a few extensio...
...espaced. We would use something like @xulschool.com/ to make our own components. Components are either services (static objects) or instances of classes, just like the objects we handle in JS. The method you call on Cc["some-string"] should either be getService or createInstance, depending on what you're asking for. In most cases it is very clear which one to call, but in case of doubt, look for documentation on it. Those two methods always receive the interface identifier as an argument. Similarly to Cc, Ci (Components.interfaces) is an index of available interfaces. A modified version of the last code snippet produces an even longer list of available interfaces. Just like in component identifiers, the nsI prefix is just a way of keeping things in order. The NS stands for Netscape, Mozilla's pr...
...e NS stands for Netscape, Mozilla's predecessor. The "I" stands for interface. Our interfaces should begin with something like xsIHello. An interface is just a definition of a set of attributes and methods that an object implementing it should have. XPCOM components can implement multiple interfaces, and they often do. Let's look at the Preference service as an example of this. We'll look at its documentation in a very old XUL site called XUL Planet. All of its documentation was planned to be migrated to MDC, but it looks like it was never finished and XUL Planet was discontinued. Their XPCOM documentation is better in terms of seeing the relationships between components and interfaces, so we'll use that. Another useful resource is this XPCOM reference. This is generated from source, and it's ke...
...And 4 more matches
Creating reusable content with CSS and XBL - Archive of obsolete content
ed using the file:/// scheme, or from add-on code. You apply this technique in a simple demonstration. Information: XBL bindings The structure provided by markup languages and CSS is not ideal for complex applications where parts need to be self-contained and reusable. You can place stylesheets in separate files, and you can place scripts in separate files. But you must link those files from the document as a whole. Another structural limitation concerns content. You can use CSS to provide content for selected elements, but the content is limited to text and images, and its positioning is limited to before or after the selected element. Mozilla provides a mechanism that overcomes these limitations: XBL (XML Bindings Language). You can use XBL to link selected elements to their own: Stylesheets ...
...t for selected elements, but the content is limited to text and images, and its positioning is limited to before or after the selected element. Mozilla provides a mechanism that overcomes these limitations: XBL (XML Bindings Language). You can use XBL to link selected elements to their own: Stylesheets Content Properties and methods Event handlers Because you avoid linking everything at the document level, you can make self-contained parts that are easy to maintain and reuse. More details For more information about XBL bindings, see the XBL page in this wiki. Action: An XBL demonstration Make a new HTML document, doc6.html. Copy and paste the content from here: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <HTML> <HEAD> <TITLE>Mozilla CSS Getting Started - XBL demon...
...ument, doc6.html. Copy and paste the content from here: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <HTML> <HEAD> <TITLE>Mozilla CSS Getting Started - XBL demonstration</TITLE> <LINK rel="stylesheet" type="text/css" href="style6.css"> </HEAD> <BODY> <H1>XBL demonstration</H1> <DIV id="square">Click Me</DIV> </BODY> </HTML> Make a new CSS file, style6.css. This stylesheet contains the document style. Copy and paste the content from here: /*** XBL demonstration ***/ #square { -moz-binding: url("square.xbl#square"); } Make a new text file, square.xbl. This file contains the XBL binding. Copy and paste the content from here: <?xml version="1.0"?> <!DOCTYPE bindings> <bindings xmlns="http://www.mozilla.org/xbl" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/ther...
...And 4 more matches
XML data - Archive of obsolete content
This page contains an example of how you can use CSS with XML data. You create a sample XML document, and a stylesheet that you can use to display it in your browser. This is the 3rd section of Part II of the CSS tutorial. Previous section: SVG Next section: XBL binding Information: XML data XML (eXtensible Markup Language) is a general-purpose language for any kind of structured data. By default, your Mozilla browser displays XML in a format very similar to the original data in the XML file. You see the actual tags that define the data's structure. By linking a CSS stylesheet with the XML document, you can define other ways to display it. ...
...kup Language) is a general-purpose language for any kind of structured data. By default, your Mozilla browser displays XML in a format very similar to the original data in the XML file. You see the actual tags that define the data's structure. By linking a CSS stylesheet with the XML document, you can define other ways to display it. To do this, your stylesheet uses rules that map tags in the XML document to the display types used by HTML. Example Data in an XML document uses <INFO> tags. ...
...ML in a format very similar to the original data in the XML file. You see the actual tags that define the data's structure. By linking a CSS stylesheet with the XML document, you can define other ways to display it. To do this, your stylesheet uses rules that map tags in the XML document to the display types used by HTML. Example Data in an XML document uses <INFO> tags. You want the document's INFO elements to be displayed like HTML paragraphs. ...
...And 4 more matches
XUL user interfaces - Archive of obsolete content
rowsers. 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-stylesheet type="text/css" href="style7.css"?> <!DOCTYPE window> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" title="CSS Getting Started - XUL demonstration" onload="init();"> <script type="application/javascript...
...0%; border: 1px inset -moz-dialog; margin: 4px; padding: 0px 4px; } #status { padding: 4px; } #status[warning] { color: red; } Make a new text file, script7.js. ...
...px; padding: 0px 4px; } #status { padding: 4px; } #status[warning] { color: red; } Make a new text file, script7.js. ...
...And 4 more matches
Images, Tables, and Mysterious Gaps - Archive of obsolete content
unexpectedly opening up. It's enough to drive a designer mad. How About a Fix? There is one obvious fix-- stop creating designs that are dependent on tables and sliced up or single-pixel images-- but it's not terribly practical for many designers, and it sure doesn't help fix old designs that are suddenly blowing apart in recent browsers. There's another obvious fix, which is to make sure your document doesn't trigger the "standards"rendering mode. You can do this by using a DOCTYPE that will trigger either "quirks" mode or "almost standards" mode, or not having a DOCTYPE appear in your document at all. The lack of a DOCTYPE will prevent validation, and so is not recommended. For authors who are working with legacy documents, a "quirks" mode DOCTYPE is the best choice. In cases where an author...
...he "standards"rendering mode. You can do this by using a DOCTYPE that will trigger either "quirks" mode or "almost standards" mode, or not having a DOCTYPE appear in your document at all. The lack of a DOCTYPE will prevent validation, and so is not recommended. For authors who are working with legacy documents, a "quirks" mode DOCTYPE is the best choice. In cases where an author is writing a new document or trying to migrate a design to be as standards-based as possible, then "almost standards" mode is probably a better choice. ...
...a DOCTYPE appear in your document at all. The lack of a DOCTYPE will prevent validation, and so is not recommended. For authors who are working with legacy documents, a "quirks" mode DOCTYPE is the best choice. In cases where an author is writing a new document or trying to migrate a design to be as standards-based as possible, then "almost standards" mode is probably a better choice. ...
...And 4 more matches
Source code directories overview - Archive of obsolete content
See also similar information in Mozilla Source Code Directory Structure, and also see the more detailed overview of how the parts of Gecko fit together. Introduction: Common Subdirectories A common naming scheme is used throughout the Mozilla source trees. ...
... See also similar information in Mozilla Source Code Directory Structure, and also see the more detailed overview of how the parts of Gecko fit together. Introduction: Common Subdirectories A common naming scheme is used throughout the Mozilla source trees. ...
...ment is a guide for developers to the directory structure of the Mozilla source code tree. It gives a bird's eye view of the source code so a developer can get a good idea what is in Mozilla and where to find things. It is a good document for a new Mozilla developer to start learning about the Mozilla code base. This document contains material for SeaMonkey, Firefox, and Toolkit. It is a living document which is (supposed to be) updated monthly according to changes in the Mozilla source tree. See also similar information in Mozilla Source Code Directory Structure, and also see the more detailed overview of how the parts of Gecko fit together. Introduction: Common Subdirectories A common naming scheme is used throughout the Mozilla source trees. At the top level is the name of the product (e.g...
...And 4 more matches
Creating a Help Content Pack - Archive of obsolete content
Original doc: http://www.mozilla.org/projects/help.../content_packs I hesitate to call it "original", tho, because I've basically rewritten the entire thing so that it's easier and faster to use to create Help content. The previous document had a lot of places where ideas were simply introduced without explanation, and I've tried to go through things a bit more slowly with better descriptions. This is still very much a work in progress, tho, and I need to complete the rest of it soon (where "complete" means "use what's there that's good, build on the stuff that's not as good, and add other useful information as necessary". This document describes how to integrate HTML help documentation into your application using the Mozilla Help Viewer. Documentation contained in the Help Viewer can be ...
... other useful information as necessary". This document describes how to integrate HTML help documentation into your application using the Mozilla Help Viewer. Documentation contained in the Help Viewer can be accessed using any XUL application or program that embeds Mozilla. What is a Content Pack? ...
...The content pack descriptor file outlines the framework of the contents of the pack by pointing to the files describing the table of contents, index, and glossary RDF files. The table of contents and index files are simple tree-based outlines written in RDF. ...
...And 4 more matches
Frequently Asked Questions - Archive of obsolete content
Why does Mozilla show source code/gibberish instead of SVG? There are two possible reasons for this: a simple mistake in the SVG file, or a misconfigured server. If there's a grey area at the top of the source with the text "This XML file does not appear to have any style information associated with it" then the problem is with the SVG file. ...
...it's not a bug. Failing to respect the MIME types servers send is incorrect and has been a source of security holes in other browsers. Mozilla will not be changing this behaviour. For more information on server configuration for SVG see this link. Why does Mozilla show an "XML Parsing Error" message instead of SVG? This is an XML debugging message to help XML authors correct errors in their XML documents. Mozilla will show this message when there's an XML well formedness error in the file it tried to load. (It doesn't mean there's an error in Mozilla.) There are many different XML errors, but the most common one in SVG files is "XML Parsing Error: prefix not bound to a namespace". This is (almost certainly) because the 'xmlns:xlink' attribute has been used in the file without including the follo...
...website is misconfigured. For information on configuring servers for SVG see this link. Why am I asked to install a plug-in to view SVG files? This is probably because there is an <embed> or <object> tag in the HTML page and its 'type' attribute is set to the wrong MIME type. The SVG MIME type is image/svg+xml (not image/svg-xml or anything else for that matter). Correct this mistake or ask the document maintainer to correct it. How should I report bugs in Mozilla SVG? If you discover any problems with our SVG implementation that you think we should know about then we'd like to hear from you. To help us make the best use of our time, please first search in the SVG component of our bug database to check that the issue hasn't already been reported. If you can't find a matching bug please file a ...
...And 4 more matches
The life of an HTML HTTP request - Archive of obsolete content
Warning: The content of this article may be out of date. It was last updated in 1999. (1) The loading of the url is started in nsWebShell::DoLoadURL (called from some LoadURL or LoadURI variant in the webshell). The webshell then tells its DocumentLoader to load (command "view") the specified url. [note: Passes nsWebShell.mObserver as nsIStreamObserver and the webshell as nsIContentViewerContainer to the DocLoader.] (2) The Document Loader calls NS_OpenURI with the url to begin transfering the requested file. Necko (the network library) checks the url scheme (the first part of the url, http: in this case) and locates the correct nsIProtocolHandler (in this case nsHTTPHandler) and asks it for a nsIChannel (nsHTTPChannel). The channel represents the connection to the server, and is...
...) and locates the correct nsIProtocolHandler (in this case nsHTTPHandler) and asks it for a nsIChannel (nsHTTPChannel). The channel represents the connection to the server, and is the source of the html data stream. (3) When data is starting to come from the webserver the nsIChannel calls the OnStartRequest in the DocumenLoader. Now the channel knows the content type of the incoming data, so the DocumentLoader can find an nsIDocumentLoaderFactory for the "text/html" content type (in this case an nsLayoutDLF). This factory is then told to create a nsIContentViewer. The factory creates a ContentViewer. In most cases (including this) it also creates a nsIDocument (nsHTMLDocument) and binds it to the ContentViewer. The ContentViewer is then Embed():ed into the ContentViewerContainer (the WebShell). ...
...an find an nsIDocumentLoaderFactory for the "text/html" content type (in this case an nsLayoutDLF). This factory is then told to create a nsIContentViewer. The factory creates a ContentViewer. In most cases (including this) it also creates a nsIDocument (nsHTMLDocument) and binds it to the ContentViewer. The ContentViewer is then Embed():ed into the ContentViewerContainer (the WebShell). (4) The document then creates a nsIParser for parsing the input stream. For HTML document this is an nsParser, which also implements nsIStreamListener. This StreamListener is returned to the DocumentLoader and connected to the nsIChannel of the request. (5) The Document (nsHTMLDocument) also creates a nsIContentSink (nsHTMLContentSink) and connects it to the parser and the document. The parser then parses the st...
...And 4 more matches
Anonymous Content - Archive of obsolete content
For example, the HTML file upload control appears in most browsers as a composite widget consisting of a text field and a button. ...
... For example, the HTML file upload control appears in most browsers as a composite widget consisting of a text field and a button. ...
...binding's content element are cloned. Elements and attributes in the XBL namespace are never cloned. For content generated underneath the bound element, the topmost nodes' parentNode pointers are set to the bound element. When anonymous content elements are built above the bound element, the topmost elements' parentNode pointers are set to the bound element's parentNode. All anonymous nodes' ownerDocument pointers are set to the bound document at the time of generation. In effect the anonymous content exists in its own insulated pocket within the document. Using parentNode, anonymous content nodes can refer to their explicit parents, but explicit parents have no knowledge of their anonymous children. The anonymous content is not accessible via the childNodes list for the bound element, nor is it ...
...And 4 more matches
DOM Interfaces - Archive of obsolete content
Parameters elt - The element to retrieve anonymous children for. ...
... The nsIDOMDocumentXBL Interface The nsIDOMDocumentXBL interface contains methods for manipulating XBL bindings. The interface is implemented by all DOM documents. IDL Definition interface nsIDOMDocumentXBL { NodeList getAnonymousNodes(in Element elt); Element getAnonymousElementByAttribute(in Element elt, in DOMString attrName, in DOMString attrValue); Element getBindingParent(in Node node); void loadBindingDocument(in DOMString documentURL); }; Methods getAnonymousNodes The getAnonymousNodes method retrieves the anonymous children of the specified element. Parameters elt - The element to retrieve anonymous children for. Return Value NodeList - The return value of getAnonymousNo...
...getAnonymousElementByAttribute is an anonymous descendant of the given element with matching attribute name and value. getBindingParent The getBindingParent method is used to obtain the bound element with the binding attached that is responsible for the generation of the specified anonymous node. This method enables an author to determine the scope of any content node. When content at the document-level scope is passed in as an argument, the property's value is null. Parameters node - The node for which the bound element responsible for generation is desired. Return Value Element - The return value of getBindingParent is the element responsible for the given anonymous node. loadBindingDocument The loadBindingDocument method can be used to synchronously obtain ...
...And 4 more matches
ContextMenus - Archive of obsolete content
so fire when the label is right-clicked for instance, so the event handler should check to make sure that the target of the contextmenu event is what is desired. To cancel a context menu event, you can use the preventDefault method of the event object. function checkContextMenu(event) { if (event.target.localName == "textbox") event.preventDefault(); } function init() { var container = document.getElementById("container"); container.addEventListener("contextmenu", checkContextMenu, true); } The 'checkContextMenu' function checks to see if the textbox was the target of the context menu and, if so, cancels the event using the preventDefault method. This has the effect of disabling the context menu. The event listener is attached using the addEventListener method within the 'init' func...
...e event listener is attached using the addEventListener method within the 'init' function. This might be called while initializing a window during a load event for example. Attaching Context Menus A context menu may be attached to an element using the context attribute, which may be applied to any XUL element. The value of the context attribute should be the id of a context menu within the same document. In the example, a context menu is attached to a grid. <window id="main-window"> <popupset> <menupopup id="ins-del-menu"> <menuitem label="Insert"/> <menuitem label="Delete"/> </menupopup> </popupset> </window> <grid context="ins-del-menu"> <columns> <column/> <column flex="1"/> </columns> <rows id="rows"> <row align="center"> <label value="Nam...
...s-del-menu"> <columns> <column/> <column flex="1"/> </columns> <rows id="rows"> <row align="center"> <label value="Name:"/> <textbox/> </row> </rows> </grid> The same context menu can be attached to multiple elements. Just set the context attribute on those elements you want the context menu to apply to. One technique is to attach a context menu to an entire document area. For instance, the Firefox browser applies a single context menu to the browser area which displays web pages. For example, the following will attach a context menu with the id 'contentAreaContextMenu' to a browser element: <browser context="contentAreaContextMenu"> Indicating the Default Item On some platforms, one of the items in a context menu is marked as being a default operation. T...
...And 4 more matches
Box Objects - Archive of obsolete content
line of a paragraph has a separate layout object. Conversely, some content nodes have no layout objects at all. For instance, the key element doesn't have any layout objects since it isn't displayed in any way. Similarly, any element that has been hidden will not have a layout object either. The DOM is generally used only to get and modify information pertaining to the content or structure of the document. It's relatively simple to determine what kind of content tree node will be created for a given element. A XUL element, for example, will have a XULElement type of content node. The layout objects that will be created are determined in a more complex manner. Various pieces of information are used such as the tag name, the attributes on an element, various CSS properties, the elements and layout o...
...f the elements in the box as displayed, instead of their order as they are stored in the DOM. Retrieving Position and Size The box object provides six read only properties, x, y, screenX, screenY, width and height, for determining the currently displayed position and size of an element. All values returned are in pixels. ...
...ining the currently displayed position and size of an element. All values returned are in pixels. x, y The x and y coordinates are referenced from the top left corner of the document in the window (that portion which excludes the window border and title bar) and refer to the top left corner of the element, including CSS padding. CSS margins and borders* are excluded. The top left corner of the document is that which is obtained from screen.mozInnerScreenX, screen.mozInnerScreenY screenX, screenY The screenX and screenY coordinates are referenced from the absolute top left corner of the screen (screen.top,screen.left) and refer to the top left corner of the element, including CSS padding and borders. CSS margins are excluded. width, height The width and height properties are also measured in pi...
...And 4 more matches
XUL accessibility guidelines - Archive of obsolete content
Center. mozilla.support.accessibility. Mozilla accessibility newsgroup. #accessibility. Accessibility channel on Mozilla's IRC server. Guidelines Keyboard access Keyboard access is important to users who can't use a mouse. Many screen reader users and those with physical disabilities rely on the keyboard as their primary input tool. These users require easy, predictable, and well-documented keyboard control. Tab order Provide a logical tab order and ensure that users can navigate all content using a keyboard. By default, the tab order is determined by the order of the elements in the underlying code. It can also be set programmatically with the tabindex attribute if needed, but this should be done sparingly and thoroughly tested whenever it is used. The navigation order should b...
...er-focus: normal. (Firefox's "Print Preview" window uses this fallback technique.) This should only be used as a last resort, and it should be consistent throughout a window (that is either all toolbar buttons are tabbable or none of them are). Keyboard shortcuts Keyboard shortcuts are very useful to users needing keyboard access. There are many ways to provide keyboard shortcuts. They are well documented in the XUL Tutorial:Keyboard Shortcuts. Careful attention should be taken when setting keyboard shortcuts. When creating an extension (for Firefox or another XUL application), make sure the keyboard shortcuts you assign do not interfere with those already defined by the base application. Refer to the following resources when setting keyboard shortcuts. Learn More Keyboard Shortcuts...
... 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 in the US is with phone number form fields. US phone numbers are often displayed on the web in two main formats XXX-XXX-XXXX or (XXX) XXX-XXXX. To enforce this ...
...And 4 more matches
SAX - Archive of obsolete content
are user-defined objects implementing SAX handler interfaces, depending on what kind of information they need to get from the parser. After the parsing process is started, handlers receive a series of callbacks for the content of XML being parsed. The following handlers are available: Interface Purpose nsISAXContentHandler Receive notification of the logical content of a document (e.g. elements, attributes, whitespace, and processing instructions). nsISAXDTDHandler Receive notification of basic DTD-related events. nsISAXErrorHandler Receive notification of errors in the input stream. nsISAXLexicalHandler SAX2 extension handler for lexical events (e.g. comment and CDATA nodes, DTD declarations, and entities). An example implementa...
... nsISAXErrorHandler Receive notification of errors in the input stream. nsISAXLexicalHandler SAX2 extension handler for lexical events (e.g. comment and CDATA nodes, DTD declarations, and entities). ...
...tification of errors in the input stream. nsISAXLexicalHandler SAX2 extension handler for lexical events (e.g. comment and CDATA nodes, DTD declarations, and entities). ...
...And 4 more matches
Correctly Using Titles With External Stylesheets - Archive of obsolete content
External stylesheets are often associated with HTML documents using the <link rel="stylesheeet"> element, but it is important to use the element's title attribute properly. This is because the title attribute on a <link rel="stylesheeet"> element makes it either preferred or an alternative style sheet. This can lead to a stylesheet being ignored, which is typically not what an author intends to do. Why Titles Matter The title attribute affects how your external stylesheet is applied to a document. In fact, the use of the title attribute is so significant that HTML 4.01 categorizes stylesheets according to the presence or absence of a title. ...
... which is typically not what an author intends to do. Why Titles Matter The title attribute affects how your external stylesheet is applied to a document. In fact, the use of the title attribute is so significant that HTML 4.01 categorizes stylesheets according to the presence or absence of a title. By including a title attribute, you can control whether a particular stylesheet always affects a document, or if it is only used under certain circumstances. There are three kinds of stylesheets that are possible: persistent, preferred, and alternate stylesheets. Authors will be most familiar with persistent stylesheets, of which any number may be applied to a document at once. A persistent stylesheet is one which has no title attribute and a value of stylesheet supplied for the rel attribute. A do...
... A preferred stylesheet, on the other hand, is one that has a value of stylesheet supplied for the rel attribute, and any value at all for the title attribute. ...
...And 4 more matches
What is CSS? - Learn web development
what CSS is, with a simple syntax example, and also covers some key terms about the language. Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, and HTML basics (study Introduction to HTML.) Objective: To learn what CSS is. In the Introduction to HTML module we covered what HTML is, and how it is used to mark up documents. These documents will be readable in a web browser. Headings will look larger than regular text, paragraphs break onto a new line and have space between them. Links are colored and underlined to distinguish them from the rest of the text. What you are seeing is the browser's default styles -- very basic styles that the browser applies to HTML to make sure it will be basically readable even if no...
...s specified by the author of the page. However, the web would be a boring place if all websites looked like that. Using CSS you can control exactly how HTML elements look in the browser, presenting your markup using whatever design you like. For more on browser/default styles, check out the following video: What is CSS for? As we have mentioned before, CSS is a language for specifying how documents are presented to users -- how they are styled, laid out, etc. A document is usually a text file structured using a markup language -- HTML is the most common markup language, but you may also come across other markup languages such as SVG or XML. Presenting a document to a user means converting it into a form usable by your audience. Browsers, like Firefox, Chrome, or Edge , are designed to pr...
... Note: A browser is sometimes called a user agent, which basically means a computer program that represents a person inside a computer system. Browsers are the main type of user agent we think of when talking about CSS, however, it is not the only one. ...
...And 4 more matches
Sending forms through JavaScript - Learn web development
HTML forms can send an HTTP request declaratively. But forms can also prepare an HTTP request to send via JavaScript, for example via XMLHttpRequest. 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. Avoiding a full page load can provide a smoother experience by avoiding network lag, and possible visual issues like flickering. Many...
...sing 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( data[name] ) ); } ...
...the data within a form element to manage how it's sent. Note that FormData objects are "write only", which means you can change them, but not retrieve their contents. Using this object is detailed in Using FormData Objects, but here are two examples: Using a standalone FormData object <button>Click Me!</button> You should be familiar with that HTML sample. ...
...And 4 more matches
Advanced text formatting - Learn web development
g. ...
..."playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); const output = document.querySelector('.output'); const code = textarea.value; const userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution...
...ositive Thinking.)</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); const output = document.querySelector('.output'); const code = textarea.value; const userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.va...
...And 4 more matches
Creating hyperlinks - Learn web development
with HTML. HTML text formatting, as covered in HTML text fundamentals. Objective: To learn how to implement a hyperlink effectively, and link multiple files together. What is a hyperlink? Hyperlinks are one of the most exciting innovations the Web has to offer. They've been a feature of the Web since the beginning, and are what makes the Web a web. Hyperlinks allow us to link documents to other documents or resources, link to specific parts of documents, or make apps available at a web address. Almost any web content can be converted to a link so that when clicked or otherwise activated the web browser goes to another web address (URL). Note: A URL can point to HTML files, text files, images, text documents, video and audio files, or anything else that lives on the Web. If t...
...hich means that people relying on keyboard controls or touchscreens to navigate web pages will have difficulty accessing title information. If a title's information is truly important to the usability of page, then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text. Active learning: creating your own example link Create an HTML document using your local code editor and our getting started template. Inside the HTML body, add one or more paragraphs or other types of content you already know about. Change some of the content into links. Include title attributes. Block level links As mentioned before, almost any content can be made into a link, even block-level elements. If you have an image you want to make into a link, use...
...'d have to go up a directory level, then back down into the pdf directory. To go up a directory, use two dots -- .. -- so the URL you would use is ../pdfs/project-brief.pdf: <p>A link to my <a href="../pdfs/project-brief.pdf">project brief</a>.</p> Note: You can combine multiple instances of these features into complex URLs, if needed, for example: ../../../complex/path/to/my/file.html. Document fragments It's possible to link to a specific part of an HTML document, known as a document fragment, rather than just to the top of the document. To do this you first have to assign an id attribute to the element you want to link to. It normally makes sense to link to a specific heading, so this would look something like the following: <h2 id="Mailing_address">Mailing address</h2> Then to lin...
...And 4 more matches
Introducing asynchronous JavaScript - Learn web development
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 we have looked at in previous learning area modules is synchronous -- you run some code, and the result is returned as soon as the browser can do so. Let's look at a simple example (see it live here, and see the source): const btn = document.querySelector('button'); btn.addEventListener('click', () => { alert('You clicked me!'); let pElem = document.createElement('p'); pElem.textContent = 'This is a newly-added paragraph.'; document.body.appendChild(pElem); }); In this block, the lines are executed one after the other: We grab a reference to a <button> element that is already available in the DOM. We add a click event ...
...Elem); }); In this block, the lines are executed one after the other: We grab a reference to a <button> element that is already available in the DOM. We add 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 ...
...s done, or to let you know that something of interest has happened. Using callbacks is slightly old-fashioned now, but you'll still see them in use in a number of older-but-still-commonly-used APIs. An example of an async callback is the second parameter of the addEventListener() method (as we saw in action above): btn.addEventListener('click', () => { alert('You clicked me!'); let pElem = document.createElement('p'); pElem.textContent = 'This is a newly-added paragraph.'; document.body.appendChild(pElem); }); The first parameter is the type of event to be listened for, and the second parameter is a callback function that is invoked when the event is fired. When we pass a callback function as an argument to another function, we are only passing the function's reference as an argument,...
...And 4 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
function creates a new Date() object, extracts a time string out of it using toLocaleTimeString(), and then displays it in the UI. It then runs the function once per second using setInterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source): function displayTime() { let date = new Date(); let time = date.toLocaleTimeString(); document.getElementById('demo').textContent = time; } const createClock = setInterval(displayTime, 1000); Just like setTimeout(), setInterval() returns an identifying value you can use later when you need to clear the interval. Clearing intervals setInterval() keeps running a task forever, unless you do something about it. You'll probably want a way to stop such tasks, otherwise you may end up getting...
...aScript inside your <script> element. Here, you're storing a reference to the <div> inside a constant, setting a rotateCount variable to 0, setting an uninitialized variable that will later be used to contain a reference to the requestAnimationFrame() call, and setting a startTime variable to null, which will later be used to store the start time of the requestAnimationFrame(). const spinner = document.querySelector('div'); let rotateCount = 0; let startTime = null; let rAF; Below the previous code, insert a draw() function that will be used to contain our animation code, which includes the timestamp parameter: function draw(timestamp) { } Inside draw(), add the following lines. They will define the start time if it is not defined already (this will only happen on the first loo...
...e rAF: cancelAnimationFrame(rAF); Active learning: Starting and stopping our spinner In this exercise, we'd like you to test out the cancelAnimationFrame() method by taking our previous example and updating it, adding an event listener to start and stop the spinner when the mouse is clicked anywhere on the page. Some hints: A click event handler can be added to most elements, including the document <body>. It makes more sense to put it on the <body> element if you want to maximize the clickable area -- the event bubbles up to its child elements. You'll want to add a tracking variable to check whether the spinner is spinning or not, clearing the animation frame if it is, and calling it again if it isn't. Note: Try this yourself first; if you get really stuck, check out of our live exampl...
...And 4 more matches
Build your own function - Learn web development
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 function goes inside the curly braces. ...
...ing 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 function goes inside the curly braces. ...
...t 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 function goes inside the curly braces. Finally, add the following code inside the curly braces: const html = document.querySelector('html'); const panel = document.createElement('div'); panel.setAttribute('class', 'msgBox'); html.appendChild(panel); const msg = document.createElement('p'); msg.textContent = 'This is a message box'; panel.appendChild(msg); const closeBtn = document.createElement('button'); closeBtn.textContent = 'x'; panel.appendChild(closeBtn); closeBtn.onclick = function() { panel.parentNode.removeChild(panel); } This is quite a lot of code to go through, so we'll walk you through it bit by bit. The first line uses a DOM API function c...
...And 4 more matches
Video and Audio APIs - Learn web development
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. ...
...formation -- one box is not obscuring another. Implementing the JavaScript We've got a fairly complete HTML and CSS interface already; now we just need to wire up all the buttons to get the controls working. Create a new JavaScript file in the same directory level as your index.html file. Call it custom-player.js. ...
...mplementing the JavaScript We've got a fairly complete HTML and CSS interface already; now we just need to wire up all the buttons to get the controls working. Create a new JavaScript file in the same directory level as your index.html file. Call it custom-player.js. ...
...And 4 more matches
Working with JSON - Learn web development
files. The latter contains some simple CSS to style our page, while the former contains some very simple body HTML: <header> </header> <section> </section> Plus a <script> element to contain the JavaScript code we will be writing in this exercise. At the moment it only contains two lines, which grab references to the <header> and <section> elements and store them in variables: const header = document.querySelector('header'); const section = document.querySelector('section'); We have made our JSON data available on our GitHub, at https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json. We are going to load it into our page, and use some nifty DOM manipulation to display it, like this: Obtaining the JSON To obtain the JSON, we use an API called XMLHttpRequest (often call...
...hat request.response will definitely be available when we come to try to do something with it. Populating the header Now that we've retrieved the JSON data and converted it into a JavaScript object, let's make use of it by writing the two functions we referenced above. First of all, add the following function definition below the previous code: function populateHeader(jsonObj) { const myH1 = document.createElement('h1'); myH1.textContent = jsonObj['squadName']; header.appendChild(myH1); const myPara = document.createElement('p'); myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed']; header.appendChild(myPara); } We named the parameter jsonObj, to remind ourselves that this JavaScript object originated from JSON. Here we first create an <h1> ...
...ce is that its text is set to a concatenated string containing both the homeTown and formed properties of the object. ...
...And 4 more matches
Properly configuring server MIME types - Learn web development
rs 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 the web server or application reports an incorrect MIME type for content, a web browser has no way, according to the HTTP specification, of knowin...
...dministrators from their own errors, since Internet Explorer will continue to process content as expected even though the web server is misconfigured, e.g. displays an image which is reported to be plain text. ...
...figured, e.g. displays an image which is reported to be plain text. Serving content using the correct MIME type can also be important for security reasons; it's possible for malicious content to affect the user's computer by pretending to be a safe type of document when it is in fact not. Note: Historically, Firefox has loaded CSS files even if they had the wrong MIME type, as long as the HTML document that requested them was being processed in quirks mode. For security reasons, Gecko 2.0 will no longer do this for stylesheets loaded from a different origin than the requesting document. If your stylesheet comes from a different origin than the document, you must serve it with the correct MIME type (text/css). Gecko 1.9.1.11 (Firefox 3.5.11) and Gecko 1.9.2.5 (Firefox 3.6.5) also implement this...
...And 4 more matches
Overview of Mozilla embedding APIs
e information. nsString There are a collection of string classes which support both unicode and ASCII strings. These classes provide a variety of string operations as well as dealing with the memory management issues of storing the underlying data. See the String Guide for more details. nsWeakPtr This is an nsCOMPtr which encapsulates XPCOM weak reference support. See the nsIWeakReference document for more information. Public Return Codes NS_SUCCEEDED NS_ERROR_FAILURE NS_ERROR_NOT_IMPLEMENTED Public Functions The following functions are available from the XPCOM DLL. NS_InitEmbedding This function initializes the Gecko embedding support. This must be the first function call made into Gecko. NS_TermEmbedding This function shuts down Gecko and cleans up any remaining resources...
...NALHELPERAPPSERVICE_CONTRACTID Implemented Interfaces: nsIExternalHelperAppService Preferences Service The Preferences service provides access to persistent data stored within a user's profile directory. Contract-id: NS_PREF_CONTRACTID Implemented Interfaces: nsIPrefService nsIPrefBranch Related Interfaces: nsIPrefListener Profile Manager Service Contract-id: Implemented Interfaces: Document Loader Service (WebProgress) Eventually, this service will be replaced by theWebProgress service... Contract-id: NS_DOCUMENT_LOADER_SERVICE_CONTRACTID Implemented Interfaces: nsIWebProgress nsIDocumentLoader Related Interfaces: nsIWebProgressListener Public Components nsWebBrowser The nsWebBrowser is the main embedding component which Gecko exposes. Conceptually, each nsWebBrowser insta...
... be replaced by theWebProgress service... Contract-id: NS_DOCUMENT_LOADER_SERVICE_CONTRACTID Implemented Interfaces: nsIWebProgress nsIDocumentLoader Related Interfaces: nsIWebProgressListener Public Components nsWebBrowser The nsWebBrowser is the main embedding component which Gecko exposes. Conceptually, each nsWebBrowser instance represents a HTML content area. Conceptually, for each document being rendered, Gecko creates a container called a DOMWindow. Each WebBrowser exposes a tree of DOMWindows - representing the frame hierarchy for the current document. As such, access to individual document frames is done via the DOMWindow interfaces. Manipulation of the entire document structure is done via the various WebBrowser interfaces. Contract-id: NS_WEBBROWSER_CONTRACTID Implemented Inte...
...And 4 more matches
Following the Android Toasts Tutorial from a JNI Perspective
This article is a work in progress and is based on GitHubGIST :: _ff-addon-tutorial-jniAndroidToast.js This article will follow the Android Developers :: API Guides - Toasts tutorial. It will use the JNI.jsm module that is available in Firefox for Android since version 17. This article teaches developers how to port Java code to JNI by reading the Java and Android documentation. Toast description A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message, and the current activity remains visible and interactive. For example, navigating away from an email before you send it triggers a "Draft saved" toast to let you know that you can continue editing later. Toasts automatically disappear after a timeout. Toasts do not have ...
...equired for the message, and the current activity remains visible and interactive. For example, navigating away from an email before you send it triggers a "Draft saved" toast to let you know that you can continue editing later. Toasts automatically disappear after a timeout. Toasts do not have to be created with JNI; they are exposed by the NativeWindow feature on Firefox for Android, see toast documentation. Java code Let's start with 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 ch...
...h/foo/bar$subclass;. When declaring methods, the signatures of the types go right next to each other without any spacing. The arguments are within the parenthesis, and the return type is immediately following. More on this later. So let us now declare the types for our toast example. We see we have three classes and two basic types (int and void). The class signature is looked up on the Android documentation. For instance, we go to Android Reference :: Context and we see: We see that the signature in dot notation is android.content.Context. So this will be written as Landroid/content/Context;. For convenience, let's make an object called SIG and populate it with our types. let SIG = { Context: 'Landroid/content/Context;', CharSequence; 'Ljava/lang/CharSequence;', int: 'I', To...
...And 4 more matches
NSS_3.12_release_notes.html
NSS 3.12 Release Notes 17 June 2008 Newsgroup: mozilla.dev.tech.crypto Contents Introduction Distribution Information New in NSS 3.12 Bugs Fixed Documentation Compatibility Feedback Introduction Network Security Services (NSS) 3.12 is a minor release with the following new features: SQLite-Based Shareable Certificate and Key Databases libpkix: an RFC 3280 Compliant Certificate Path Validation Library Camellia cipher support TLS session ticket extension (RFC 5077) NSS 3.12 is tri-licensed under the MPL 1.1/GPL 2.0/LGPL 2.1. Note: Firefox 3 uses NSS 3.12, but not the new SQLite-based shareable certificate and key databases. We missed the deadline to enable that feature in Firefox 3. Distribution Information The CVS tag for the NSS 3.12 release is NSS...
...ipher support TLS session ticket extension (RFC 5077) NSS 3.12 is tri-licensed under the MPL 1.1/GPL 2.0/LGPL 2.1. Note: Firefox 3 uses NSS 3.12, but not the new SQLite-based shareable certificate and key databases. We missed the deadline to enable that feature in Firefox 3. Distribution Information The CVS tag for the NSS 3.12 release is NSS_3_12_RTM. NSS 3.12 requires NSPR 4.7.1. See the Documentation section for the build instructions. NSS 3.12 source and binary distributions are also available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_12_RTM/src/. Binary distributions: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_12_RTM/. Both debug and optimized builds are provided. G...
...Bug 330721: Remove OS/2 VACPP compiler support from NSS Bug 408260: certutil usage doesn't give enough information about trust arguments Bug 410226: leak in create_objects_from_handles Bug 415007: PK11_FindCertFromDERSubjectAndNickname is dead cod...
...And 4 more matches
NSS Tools
NSS Security Tools Newsgroup: mozilla.dev.tech.crypto Overview The NSS Security Tools allow developers to test, debug, and manage applications that use NSS. The Tools Information table below describes both the tools that are currently working and those that are still under development. The links for each tool take you to the source code, documentation, plans, and related links for each tool. The links will become active when information is available. Currently, you must download the NSS 3.1 source and build it to create binary files for the NSS tools. For information about downloading the NSS source, see https://developer.mozilla.org/NSS/Building. If you have feedback or questions, please feel free to post to mozilla.dev.tech.crypto. This newsgroup is the preferred forum for all ques...
...inate redundant functionality in tools. Many tools implement private versions of PKCS11Init(), OpenCertDB(), etc. Eliminate use of getopt() and replace with NSPR calls to get command options (to eliminate platform dependencies with getopt()). Tools Information Tool Description Links certutil 2.0 Manage certificate and key databases (cert7.db and key3.db). ...
...place with NSPR calls to get command options (to eliminate platform dependencies with getopt()). Tools Information Tool Description Links certutil 2.0 Manage certificate and key databases (cert7.db and key3.db). Source, Documentation, Tasks/Plans cmsutil 1.0 Performs basic CMS operations such as encrypting, decrypting, and signing messages. Source, Documentation crlutil Manage certificate revocation lists (CRLs). Source, Documentation, dbck 1.0 Analyze and repair certificate databases (not working in NSS 3.2) Source, Tasks/Plans modutil 1.1 Manage the database of PKCS11 modules (secmod.db). Add modules and modify the properties of existing modules (such as whether a module is the default provider of some ...
...And 4 more matches
nsICookieService
iption cookieIconIsVisible boolean This attribute really doesn't belong on this interface. CVS blame will tell you why it is here. It remains until we can find a better home for it. Methods getCookieString() Get the complete cookie string associated with the URI. string getCookieString( in nsIURI aURI, in nsIChannel aChannel ); Parameters aURI The URI of the document for which cookies are being queried. aChannel The channel used to load the document. this parameter may be null, but it is strongly recommended that a non-null value be provided to ensure that the cookie privacy preferences are honored. Return value Returns the resulting cookie string. getCookieStringFromHttp() Get the complete cookie string associated with the URI. Note: This function is...
...but it is strongly recommended that a non-null value be provided to ensure that the cookie privacy preferences are honored. Return value Returns the resulting cookie string. getCookieStringFromHttp() Get the complete cookie string associated with the URI. Note: This function is redundant and will most likely be removed in a future revision of this interface. getCookieString() will query the documentURI property off of nsIHttpChannelInternal if supported, so getCookieString() can be used in place of this method. string getCookieStringFromHttp( in nsIURI aURI, in nsIURI aFirstURI, in nsIChannel aChannel ); Parameters aURI The URI of the document for which cookies are being queried. aFirstURI The URI that the user originally typed in or clicked on to initiate the load of the...
...RI property off of nsIHttpChannelInternal if supported, so getCookieString() can be used in place of this method. string getCookieStringFromHttp( in nsIURI aURI, in nsIURI aFirstURI, in nsIChannel aChannel ); Parameters aURI The URI of the document for which cookies are being queried. aFirstURI The URI that the user originally typed in or clicked on to initiate the load of the document referenced by aURI. aChannel The channel used to load the document. this parameter may be null, but it is strongly recommended that a non-null value be provided to ensure that the cookie privacy preferences are honored. Return value Returns the resulting cookie string. setCookieString() Set the cookie string associated with the URI. Note: Should be able to allow null aPrompt, since nsIPro...
...And 4 more matches
nsIDOMParser
Note: If you're a web developer, please refer to the DOMParser documentation instead. Creating a DOMParser To create a DOMParser object from a web page or a chrome script running in a window, simply use new DOMParser(). When you create a DOMParser from a privileged script, you can pass parameters to the constructor, more on that below. To create a DOMParser when the constructor is not available (e.g., from a JS XPCOM component, a JS module, or an xpcshell test), use: var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"] .createInstance(Components.interfaces.nsIDOMParser); // optionally, call parser.init(principal, documentURI, baseURI); Principals, document and base URI Note: This section covers changes introduced to DOMParser in Gecko 1.9. (This section is on...
...se: var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"] .createInstance(Components.interfaces.nsIDOMParser); // optionally, call parser.init(principal, documentURI, baseURI); Principals, document and base URI Note: This section covers changes introduced to DOMParser in Gecko 1.9. (This section is only relevant to Firefox extensions--not to Web content.) To create a document, the parser needs to specify a principal (see Security check basics), a base URI (see document.baseURIObject), and a documentURI. These values are automatically determined as defined below, but if you work with DOMParser from privileged code, you can override the defaults by providing arguments to the DOMParser constructor or calling parser.init(). Usually you don't need to do that. If you come a...
...If the caller has UniversalXPConnect privileges, it can pass parameters to new DOMParser(). ...
...And 4 more matches
nsIDOMXPathResult
Read only. invalidIteratorState boolean true if the iterator state has become invalid. For example, modifying a node invalidates the iterator. Read only. ...
...e most appropriate type. NUMBER_TYPE 1 Type is a single number. STRING_TYPE 2 Type is a single string. BOOLEAN_TYPE 3 Type is a single boolean value. UNORDERED_NODE_ITERATOR_TYPE 4 Type is a reference to all the nodes matching the expression used in the evaluator. The nodes may not necessarily be in the same order that they appear in the document. ORDERED_NODE_ITERATOR_TYPE 5 Type is a reference to all the nodes matching the expression used in the evaluator. The nodes in the result set are in the same order that they appear in the document. UNORDERED_NODE_SNAPSHOT_TYPE 6 Type is a node-set containing snapshots of all the nodes matching the expression used in the evaluator. The nodes may not necessarily be in ...
... 5 Type is a reference to all the nodes matching the expression used in the evaluator. The nodes in the result set are in the same order that they appear in the document. UNORDERED_NODE_SNAPSHOT_TYPE 6 Type is a node-set containing snapshots of all the nodes matching the expression used in the evaluator. The nodes may not necessarily be in the same order that they appear in the document. ORDERED_NODE_SNAPSHOT_TYPE 7 Type is a node-set containing snapshots of all the nodes matching the expression used in the evaluator. The nodes in the result set are in the same order that they appear in the document. ...
...And 4 more matches
Browser Console - Firefox Developer Tools
see we can not only access the Browser Console but also Web Console. ...
...t document of the Browser Console this can be done with the HUDService. This example here makes it so that when you mouse over the "Clear" button it will clear the Browser Console: Components.utils.import("resource://devtools/shared/Loader.jsm"); var HUDService = devtools.require("devtools/client/webconsole/hudservice"); var hud = HUDService.getBrowserConsole(); var clearBtn = hud.chromeWindow.document.querySelector('.webconsole-clear-console-button'); clearBtn.addEventListener('mouseover', function() { hud.jsterm.clearOutput(true); }, false); Bonus Features Available For Add-on SDK add-ons, the console API is available automatically. Here's an example add-on that just logs an error when the user clicks a widget: widget = require("sdk/widget").Widget({ id: "an-error-happened", label: "...
...browser object, through the gBrowser global, and that enables you to control the browser through the command line. Try running this code in the Browser Console's command line (remember that to send multiple lines to the Browser Console, use Shift+Enter): var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab); newTabBrowser.addEventListener("load", function() { newTabBrowser.contentDocument.body.innerHTML = "<h1>this page has been eaten</h1>"; }, true); newTabBrowser.contentDocument.location.href = "https://mozilla.org/"; It adds a listener to the currently selected tab's load event that will eat the new page, then loads a new page. Note: You can restart the browser with the command Ctrl + Alt + R (Windows, Linux) or Cmd + Alt + R (Mac) This command restarts the browser with the ...
...And 4 more matches
Manipulating video using canvas - Web APIs
By combining the capabilities of the video element with a canvas, you can manipulate video data in real time to incorporate a variety of visual effects to the video being displayed. This tutorial demonstrates how to perform chroma-keying (also known as the "green screen effect") using JavaScript code. The document content The HTML document used to render this content is shown below. <!DOCTYPE html> <html> <head> <style> body { background: black; color:#CCCCCC; } #c2 { background-image: url(media/foo.png); background-repeat: no-repeat; } div { float: left; border :1px solid #444444; padding:10px; margin: 10px; background:#3B3B3B; } </style> </head> <body> <div> ...
... 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 ...
...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. ...
...And 4 more matches
Compositing example - Web APIs
This sample program demonstrates a number of compositing operations. The output looks like this: Compositing example This code sets up the global values used by the rest of the program. ...
... This sample program demonstrates a number of compositing operations. The output looks like this: Compositing example This code sets up the global values used by the rest of the program. ...
....33, b: 0.33 }; // resize canvas canvas1.width = width; canvas1.height = height; canvas2.width = width; canvas2.height = height; lightMix() colorSphere(); runComposite(); return; }; And this code, runComposite(), handles the bulk of the work, relying on a number of utility functions to do the hard parts. ...
...And 4 more matches
Element.outerHTML - Web APIs
Web › API › Element › outerHTML
of the element and its descendants. Setting the value of outerHTML replaces the element and all of its descendants with a new DOM tree constructed by parsing the specified htmlString. 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. Examples Getting the value of an element's outerHTML property: HTML <div id="d"> <p>Content</p> <p>Further Elaborated</p> </div> Javascript var d = document.getElementById("d"); console.log(d.outerHTML); // The string '<div id="d"><p>Content</p><p>Further Elaborated</p></div>' // is written to the console window Replacing a node by setting the oute...
... Notes If the element has no parent element, setting its o...
...d</p> </div> Javascript var d = document.getElementById("d"); console.log(d.outerHTML); // The string '<div id="d"><p>Content</p><p>Further Elaborated</p></div>' // is written to the console window Replacing a node by setting the outerHTML property: HTML <div id="container"> <div id="d">This is a div.</div> </div> Javascript var container = document.getElementById("container"); var d = document.getElementById("d"); console.log(container.firstChild.nodeName); // logs "DIV" d.outerHTML = "<p>This paragraph replaced the original div.</p>"; console.log(container.firstChild.nodeName); // logs "P" // The #d div is no longer part of the document tree, // the new paragraph replaced it. Notes If the element has no parent element, setting its outerHTML property will not change it or its de...
...And 4 more matches
Using the Gamepad API - Web APIs
ome variables: The gamepadInfo paragraph that the connection info is written into, the ball that we want to move, the start variable that acts as the ID for requestAnimation Frame, the a and b variables that act as position modifiers for moving the ball, and the shorthand variables that will be used for the requestAnimationFrame() and cancelAnimationFrame() cross browser forks. var gamepadInfo = document.getElementById("gamepad-info"); var ball = document.getElementById("ball"); var start; var a = 0; var b = 0; Next we use the gamepadconnected event to check for a gamepad being connected. When one is connected, we grab the gamepad using Navigator.getGamepads()[0], print information about the gamepad into our gamepad info div, and fire the gameLoop() function that starts the whole ball movement ...
...epadconnected and gamepaddisconnected events in order to display the state of all gamepads connected to the system. You can find a working demo and look at the full source code on Github. ...
...cted to the system. You can find a working demo and look at the full source code on Github. ...
...And 4 more matches
HTMLCanvasElement.toBlob() - Web APIs
s not origin clean; at least some of its contents come from secure Examples Getting a file representing the canvas Once you have drawn content into a canvas, you can convert it into a file of any supported image format. ...
...etting a file representing the canvas Once you have drawn content into a canvas, you can convert it into a file of any supported image format. The code snippet below, for example, takes the image in the <canvas> element whose ID is "canvas", obtains a copy of it as a PNG image, then appends a new <img> element to the document, whose source image is the one created using the canvas. ...
...you can convert it into a file of any supported image format. The code snippet below, for example, takes the image in the <canvas> element whose ID is "canvas", obtains a copy of it as a PNG image, then appends a new <img> element to the document, whose source image is the one created using the canvas. var canvas = document.getElementById('canvas'); canvas.toBlob(function(blob) { var newImg = document.createElement('img'), url = URL.createObjectURL(blob); newImg.onload = function() { // no longer need to read the blob so it's revoked URL.revokeObjectURL(url); }; newImg.src = url; document.body.appendChild(newImg); }); Note that here we're creating a PNG image; if you add a second parameter to the toBlob() call, you can specify the image type. For example, to get the i...
...And 4 more matches
HTMLImageElement.loading - Web APIs
The HTMLImageElement property loading is a string whose value provides a hint to the user agent that tells the browser how to handle loading images which are currently outside the window's visual viewport. This helps to optimize the loading of the document's contents by postponing loading the image until it's expected to be needed, rather than immediately during the initial page load. Syntax let imageLoadScheduling = htmlImageElement.loading; htmlImageElement.loading = eagerOrLazy; Value A DOMString providing a hint to the user agent as to how to best schedule the loading of the image to optimize page performance. The possible values are: eager The default behavior, eager tells the browser to load the image as soon as the <img> element is processed. lazy Tells the user agent to hold of...
... as to how to best schedule the loading of the image to optimize page performance. The possible values are: eager The default behavior, eager tells the browser to load the image as soon as the <img> element is processed. lazy Tells the user agent to hold off on loading the image until the browser estimates that it will be needed imminently. For instance, if the user is scrolling through the document, a value of lazy will cause the image to only be loaded shortly before it will appear in the window's visual viewport. Usage notes Timing of the load event The load event is fired when the document has been fully processed. When images are loaded eagerly (which is the default), every image in the document must be fetched before the load event can fire. By specifying the value lazy for loadin...
...n load fires, it's possible that any lazy-loaded images located in the visual viewport may not yet be visible. ...
...And 4 more matches
Basic concepts - Web APIs
web applications with rich query abilities regardless of network availability, these applications can work both online and offline. IndexedDB is useful for applications that store a large amount of data (for example, a catalog of DVDs in a lending library) and applications that don't need persistent internet connectivity to work (for example, mail clients, to-do lists, and notepads). About this document This introduction discusses essential concepts and terminology in IndexedDB. It gives you the big picture and explains key concepts. You'll find the following useful: For an overview of the design and structure of IndexedDB, see Big Concepts. To learn more about IndexedDB terms, see the Definitions section. For a detailed tutorial on how to use the API, see Using IndexedDB. For the refere...
...is introduction discusses essential concepts and terminology in IndexedDB. It gives you the big picture and explains key concepts. You'll find the following useful: For an overview of the design and structure of IndexedDB, see Big Concepts. To learn more about IndexedDB terms, see the Definitions section. For a detailed tutorial on how to use the API, see Using IndexedDB. For the reference documentation on the IndexedDB API, refer back to the main IndexedDB API article and its subpages, which document the types of objects used by IndexedDB. For more information on how the browser handles storing your data in the background, read Browser storage limits and eviction criteria. Overview of IndexedDB IndexedDB lets you store and retrieve objects that are indexed with a "key." All changes tha...
...a 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 result set. If you are not familiar with NoSQL systems, read the Wikipedia article on NoSQL. IndexedDB adheres to a same-origin policy. An origin is the domain, application layer protocol, and port of a URL of the document where the script is being executed. Each origin has its own associated set of databases. Every database has a name that identifies it within an origin. The security boundary imposed on IndexedDB prevents applications from accessing data with a different origin. For example, while an app or a page in http://www.example.com/app/ can retrieve data from http://www.example.com/dir/, because they ha...
...And 4 more matches
Key Values - Web APIs
s 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 Description Virtual Keycode Windows Mac Linux Android "Unidentified" The user agent wasn't able to map the event's virtual keycode ...
...mer programming button. KEYCODE_TV_TIMER_PROGRAMMING (258) [1] Firefox added proper support for the "TV" key in Firefox 37; before that, this key generated the key code "Live". [2] These keys were "Unidentified" until Firefox 37. Media controller keys Because modern remote controls for media devices often include buttons beyond the basic controls covered elsewhere in this document, key values are defined for a broad array of these additional buttons. The values below are derived in part form a number of consumer electronics technical specifications: DTV Application Software Environment (part of the ATSC specification) Open Cable Application Platform 1.1.3 ANSI/CEA-2014-B: Web-based Protocol and Framework for Remote User Interface on UPnP(TM) Networks and the Internet...
...rt of the ATSC specification) Open Cable Application Platform 1.1.3 ANSI/CEA-2014-B: Web-based Protocol and Framework for Remote User Interface on UPnP(TM) Networks and the Internet Android KeyEvent key code values Note: Remote controls typically include keys whose values are already defined elsewhere, such as under Multimedia keys or Audio control keys. Those keys' values will match what's documented in those tables. KeyboardEvent.key Value Description Virtual Keycode Windows Mac Linux Android "AVRInput" [3] Changes the input mode on an external audio/video receiver (AVR) unit. KEYCODE_AVR_INPUT (182) "AVRPower" [3] Toggles the power on an external AVR unit. KEYCODE_AVR_POWER (181) "ColorF0Red"...
...And 4 more matches
MediaQueryList - Web APIs
A MediaQueryList object stores information on a media query applied to a document, with support for both immediate and event-driven matching against the state of the document. You can create a MediaQueryList by calling matchMedia() on the window object. The resulting object handles sending notifications to listeners when the media query state changes (i.e. when the media query test starts or stops evaluating to true). This is very useful for adaptive design, since this makes it possible to observe a document to detect when its media queries change, instead of polling the values periodically, and allows you to programmatically make changes to a document based on media query status. Properties The MediaQueryList interface inherits properties from its parent interface, EventTarget. matchesRead...
...ptive design, since this makes it possible to observe a document to detect when its media queries change, instead of polling the values periodically, and allows you to programmatically make changes to a document based on media query status. Properties The MediaQueryList interface inherits properties from its parent interface, EventTarget. matchesRead only A Boolean that returns true if the document currently matches the media query list, or false if not. mediaRead only A DOMString representing a serialized media query. Methods The MediaQueryList interface inherits methods from its parent interface, EventTarget. ...
... only A Boolean that returns true if the document currently matches the media query list, or false if not. mediaRead only A DOMString representing a serialized media query. Methods The MediaQueryList interface inherits methods from its parent interface, EventTarget. addListener() Adds to the MediaQueryList a callback which is invoked whenever the media query status--whether or not the document matches the media queries in the list--changes. This method exists primarily for backward compatibility; if possible, you should instead use addEventListener() to watch for the change event. ...
...And 4 more matches
Online and offline events - Web APIs
ation based itself off of these prior implementations), so you can begin using it immediately. Network status autodetection was implemented in Firefox 2. "online" and "offline" events Firefox 3 introduces two new events: "online" and "offline". These two events are fired on the <body> of each page when the browser switches between online and offline mode. ...
... off of these prior implementations), so you can begin using it immediately. Network status autodetection was implemented in Firefox 2. "online" and "offline" events Firefox 3 introduces two new events: "online" and "offline". These two events are fired on the <body> of each page when the browser switches between online and offline mode. Additionally, the events bubble up from document.body, to document, ending at window. ...
...(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. ...
...And 4 more matches
NodeIterator.whatToShow - Web APIs
Shows all nodes. NodeFilter.SHOW_ATTRIBUTE 2 Shows attribute Attr nodes. This is meaningful only when creating a NodeIterator or TreeWalker with an Attr node as its root; in this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree. NodeFilter.SHOW_CDATA_SECTION 8 Shows CDATASection nodes. NodeFilter.SHOW_COMMENT 128 Shows Comment nodes. NodeFilter.SHOW_DOCUMENT 256 Shows Document nodes. NodeFilter.SHOW_DOCUMENT_FRAGMENT 1024 Shows DocumentFragment nodes. NodeFilter.SHOW_DOCUMENT_TYPE 512 Shows DocumentType nodes. NodeFilter.SHOW_ELEM...
...NT_TYPE 512 Shows DocumentType nodes. NodeFilter.SHOW_ELEMENT 1 Shows Element nodes. NodeFilter.SHOW_ENTITY 32 Shows Entity nodes. This is meaningful only when creating a NodeIterator or TreeWalker with an Entity node as its root; in this case, it means that the Entity node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree. NodeFilter.SHOW_ENTITY_REFERENCE 16 Shows EntityReference nodes. NodeFilter.SHOW_NOTATION 2048 Shows Notation nodes. This is meaningful only when creating a NodeIterator or TreeWalker with a Notation node as its root; in this case, it means that the Notation node will appear in the first position of...
...document tree. NodeFilter.SHOW_ENTITY_REFERENCE 16 Shows EntityReference nodes. NodeFilter.SHOW_NOTATION 2048 Shows Notation nodes. This is meaningful only when creating a NodeIterator or TreeWalker with a Notation node as its root; in this case, it means that the Notation node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree. NodeFilter.SHOW_PROCESSING_INSTRUCTION 64 Shows ProcessingInstruction nodes. NodeFilter.SHOW_TEXT 4 Shows Text nodes. ...
...And 4 more matches
ParentNode.prepend() - Web APIs
Parameters nodesToPrepend One or more nodes to insert before the first child node currently in the ParentNode. Each node can be specified as either a Node object or as a string; strings are inserted as new Text nodes. Return value undefined. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...re nodes to insert before the first child node currently in the ParentNode. Each node can be specified as either a Node object or as a string; strings are inserted as new Text nodes. Return value undefined. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...d node currently in the ParentNode. Each node can be specified as either a Node object or as a string; strings are inserted as new Text nodes. Return value undefined. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...And 4 more matches
ParentNode.replaceChildren() - Web APIs
To do this, we give each of the buttons a click event handler, which collects together the selected options you want to transfer in one constant, and the existing options in the list you are transferring to in another constant. It then calls replaceChildren() on the list to transfer the options to, using the spread operator to pass in all the options contained in both constants. ...
...vent handler, which collects together the selected options you want to transfer in one constant, and the existing options in the list you are transferring to in another constant. It then calls replaceChildren() on the list to transfer the options to, using the spread operator to pass in all the options contained in both constants. ...
...cted options you want to transfer in one constant, and the existing options in the list you are transferring to in another constant. It then calls replaceChildren() on the list to transfer the options to, using the spread operator to pass in all the options contained in both constants. ...
...And 4 more matches
StyleSheet.media - Web APIs
Web › API › StyleSheet › media
The media property of the StyleSheet interface specifies the intended destination media for style information. It is a read-only, array-like MediaList object and can be removed with deleteMedium() and added with appendMedium(). ...
... a read-only, array-like MediaList object and can be removed with deleteMedium() and added with appendMedium(). ...
...ith deleteMedium() and added with appendMedium(). ...
...And 4 more matches
TreeWalker.whatToShow - Web APIs
f unsigned long) Shows all nodes. NodeFilter.SHOW_ATTRIBUTE 2 Shows attribute Attr nodes. This is meaningful only when creating a TreeWalker with an Attr node as its root; in this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree. NodeFilter.SHOW_CDATA_SECTION 8 Shows CDATASection nodes. NodeFilter.SHOW_COMMENT 128 Shows Comment nodes. NodeFilter.SHOW_DOCUMENT 256 Shows Document nodes. NodeFilter.SHOW_DOCUMENT_FRAGMENT 1024 Shows DocumentFragment nodes. NodeFilter.SHOW_DOCUMENT_TYPE 512 Shows DocumentType nodes. NodeFilter.SHOW_ELEM...
...lter.SHOW_DOCUMENT_TYPE 512 Shows DocumentType nodes. NodeFilter.SHOW_ELEMENT 1 Shows Element nodes. NodeFilter.SHOW_ENTITY 32 Shows Entity nodes. This is meaningful only when creating a TreeWalker with an Entity node as its root; in this case, it means that the Entity node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree. NodeFilter.SHOW_ENTITY_REFERENCE 16 Shows EntityReference nodes. NodeFilter.SHOW_NOTATION 2048 Shows Notation nodes. This is meaningful only when creating a TreeWalker with a Notation node as its root; in this case, it means that the Notation node will appear in the first position of the traversal. ...
...ersing over the document tree. NodeFilter.SHOW_ENTITY_REFERENCE 16 Shows EntityReference nodes. NodeFilter.SHOW_NOTATION 2048 Shows Notation nodes. This is meaningful only when creating a TreeWalker with a Notation node as its root; in this case, it means that the Notation node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree. NodeFilter.SHOW_PROCESSING_INSTRUCTION 64 Shows ProcessingInstruction nodes. NodeFilter.SHOW_TEXT 4 Shows Text nodes. ...
...And 4 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
false, only XR device changes to the view are permitted. enableForcePolyfill If this Boolean is true, the example will attempt to use the WebXR polyfill even if the browser actually has support for WebXR. If false, the polyfill is only used if the browser doesn't implement navigator.xr. SESSION_TYPE The type of XR session to create: inline for an inline session presented in the context of the document and immersive-vr to present the scene to an immersive VR headset. MOUSE_SPEED A multiplier used to scale the inputs from the mouse used for pitch and yaw control. MOVE_DISTANCE The distance to move in response to any of the keys used to move the viewer through the scene. Note: This example always displays what it renders on the screen, even if using immersive-vr mode. This lets you compare...
...ion and orientation. The fragment shader returns the color of each vertex, interpolating as needed from the values found in the texture and applying the lighting effects. Starting up and shutting down WebXR Upon initially loading the script, we install a handler for the load event, so that we can perform initialization. ...
...und in the texture and applying the lighting effects. Starting up and shutting down WebXR Upon initially loading the script, we install a handler for the load event, so that we can perform initialization. ...
...And 4 more matches
Using the alert role - Accessibility
t. If the element was already in the original source code when the page loaded, the screen reader will announce the error immediately after announcing the page title. ...
...e original source code when the page loaded, the screen reader will announce the error immediately after announcing the page title. <h2 role="alert">Your form could not be submitted because of 3 validation errors.</h2> Example 2: Dynamically adding an element with the alert role This snippet dynamically creates an element with an alert role and adds it to the document structure. ...
... immediately after announcing the page title. <h2 role="alert">Your form could not be submitted because of 3 validation errors.</h2> Example 2: Dynamically adding an element with the alert role This snippet dynamically creates an element with an alert role and adds it to the document structure. ...
...And 4 more matches
Cognitive accessibility - Accessibility
Cognitive impairment refers to a broad range of disabilities, from people with intellectual disabilities who may have the most-limited capabilities, to age-related issues with thinking and remembering. The range includes people with mental illnesses, such as depression and schizophrenia. It also includes people with learning disabilities, such as dyslexia and attention deficit hyperactivity disorder (ADHD). ...
... as dyslexia and attention deficit hyperactivity disorder (ADHD). Though there is a lot of diversity within clinical definitions of cognitive impairments, people with them experience a common set of functional problems. These problems include difficulty with understanding content, remembering how to complete tasks, and confusion caused by inconsistent or non-traditional web page layouts. In this document, we focus on steps developers should take to improve the cognitive accessibility of their web sites and applications. Overview Cognitive and intellectual disabilities cover a large spectrum, and may be momentary, temporary, or permanent conditions. For example, dementia and Alzheimer's are permanent cognitive impairments that get progressively worse. Other permanent cognitive impairments includ...
...ion to time out and result in lost data. The exception to this is preserving data for more than 20 hours when no actions are taken. Navigation Guideline 2.4 states "provide ways to help users navigate, find content, and determine where they are," and provides 10 guidelines to ensure the site is navigable and content is findable: Include a <title> Make sure to include a <title> for the document, as titles provide a quick and easy to reference description of the screen's main point. People with cognitive disabilities, limited short-term memory, and reading disabilities all benefit from being able to identify the purpose of content this way. Heading and labels Include clear and descriptive headings so users can easily find information and understand relationships between differen...
...And 4 more matches
Text labels and names - Accessibility
ia-label to contain the label text: <div role="dialog" aria-label="Personal details updated confirmation"> <p>Your personal details were successfully updated. You can change your details at any time in the user account section.</p> <button>Close</button> </div> See also role="dialog" role="alertdialog" aria-label aria-labelledby WAI-ARIA: dialog role Dialog authoring practices Documents must have a title It is important on each HTML document to include a <title> that describes the page's purpose. A common navigation technique for users of assistive technology is to infer what content a page contains by reading its title. If the title is not available, they have to navigate the page to determine its content, which can be a time consuming and potentially confusing process. Exam...
...ose. A common navigation technique for users of assistive technology is to infer what content a page contains by reading its title. If the title is not available, they have to navigate the page to determine its content, which can be a time consuming and potentially confusing process. ...
...descriptive title helps users of assistive technology understand what the element is showing. Figures with optional captions should be labeled For best accessibility, include a <figcaption> within a <figure> element, even though doing so is technically optional. The caption is in addition to any alternative text on images within the figure. The caption describes the purpose of the figure in the document, which may be different from a simple description of a visual item, as provided by the alternative text. Example The following example shows code for a figure with a caption. The alt attribute of the <img> describes the appearance of the image; the <figcaption> describes it from a functional perspective (in this case, the Latin name of the flower in the image). <figure> <img src="milkweed.jg...
...And 4 more matches
Detecting CSS animation support - CSS: Cascading Style Sheets
code to simulate a similar effect. This article, based on this blog post by Chris Heilmann, demonstrates a technique for doing this. ...
... animate. ...
...Otherwise, we c...
...And 4 more matches
Guide to scroll anchoring - CSS: Cascading Style Sheets
scroll to read the content; while you are busy reading, the part of the page you are looking at suddenly jumps. This has happened because large images or some other elements have just loaded further up in the content. Scroll anchoring is a browser feature that aims to solve this problem of content jumping, which happens if content loads in after the user has already scrolled to a new part of the document. How does it work? Scroll anchoring adjusts the scroll position to compensate for the changes outside of the viewport. This means that the point in the document the user is looking at remains in the viewport, which may mean their scroll position actually changes in terms of how far they have moved through the document. How do I turn on scroll anchoring? You don't! The feature is enabled by de...
... anchor using the layout.css.scroll-anchoring.highlight switch. That will show a purple overlay on top of the anchor node. If one node doesn't seem appropriate to be an anchor, you can exclude it using overflow-anchor, as described below. What if I need to disable it? The specification provides a new property, overflow-anchor, which can be used to disable scroll anchoring on all or part of the document. ...
... overflow-anchor, which can be used to disable scroll anchoring on all or part of the document. It's essentially a way to opt out of the new behavior. The only possible values are auto or none: auto is the initial value; as long as the user has a supported browser the scroll anchoring behavior will happen, and they should see fewer content jumps. none means that you have explicitly opted the document, or part of the document, out of scroll anchoring. ...
...And 4 more matches
Overview of events and handlers - Developer guides
This code relies on the agreement that there is a kind...
... This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function wi...
...s a second example, much modern JavaScript integrated into web pages is wrapped into an event function call to ensure that the code is only executed when the HTML has been processed and is available for alteration or decoration. For example, code might be attached as: var funcInit = function(){ // user code goes here and can safely address all the HTML elements from the page // since the document has successfully been 'loaded' } document.addEventListener('DOMContentLoaded', funcInit); so that this code will only be executed after the document object emits the 'DOMContentLoaded' event because the HTML has been parsed and Javasript objects created representing each of the nodes of the HTML document. Note that in this example, the code does not even name the event argument to the function ...
...And 4 more matches
Making content editable - Developer guides
does it work? All you have to do is set the contenteditable attribute on nearly any HTML element to make it editable. Here's a simple example which creates a <div> element whose contents the user can edit. <div contenteditable="true"> This text can be edited by the user. </div> Here's the above HTML in action: Executing commands When an HTML element has contenteditable set to true, the document.execCommand() method is made available. This lets you run commands to manipulate the contents of the editable region. Most commands affect the document's selection by, for example, applying a style to the text (bold, italics, etc), while others insert new elements (like adding a link) or affect an entire line (indenting). When using contentEditable, calling execCommand() will affect the currently...
...re somewhat more consistent. As of Firefox 60, Firefox will be updated to wrap the separate lines in <div> elements, matching the behavior of Chrome, modern Opera, Edge, and Safari. Try it out in the above example. Note: Internet Explorer, which is no longer being developed, uses <p> elements instead of <div>. If you want to use a different paragraph separator, the above browsers all support document.execCommand, which provides a defaultParagraphSeparator command to allow you to change it. For example, to use <p> elements: document.execCommand("defaultParagraphSeparator", false, "p"); Additionally, Firefox supports the non-standard 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...
... elements: document.execCommand("defaultParagraphSeparator", false, "p"); Additionally, Firefox supports the non-standard 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.mozil...
...And 4 more matches
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
Web › HTML › Element › iframe
element (<iframe>) represents a nested browsing context, embedding another HTML page into the current 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. Each embedded browsing context has its own session history and document. The browsing context that embeds the others is called the parent browsing context. The topmost browsing context -- the one with no parent -- is usually the browser window, represented by the Window object. Because each browsing context is a complete document environment, every <iframe> in a page requires increased memory and other computing resources. While theoretically you can use as many <i...
... Content categories Flow content, phrasing content, embedded content, interactive content, palpable content. Permitted content None. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts embedded content. Implicit ARIA role No corresponding role Permitted ARIA roles application, document, img, none, presentation DOM interface HTMLIFrameElement Attributes This element includes the global attributes. allow Specifies a feature policy for the <iframe>. See the article Privacy, permissions, and information security for details on security issues and how <iframe> works with Feature Policy to keep systems safe. allowfullscreen Set to true if the <iframe> can ac...
...rigin of the referring page: its scheme, host, and port. origin-when-cross-origin: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path. same-origin: A referrer will be sent for same origin, but cross-origin requests will contain no referrer information. strict-origin: Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS->HTTPS), but don't send it to a less secure destination (HTTPS->HTTP). strict-origin-when-cross-origin: Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS->HTTPS), and send no header to a less secure destination (HTTPS->HTTP). unsafe-url: The r...
...And 4 more matches
<input type="file"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › file
may be identified in more than one manner, it's useful to provide a thorough set of type specifiers when you need files of a given format. For instance, there are a number of ways Microsoft Word files can be identified, so a site that accepts Word files might use an <input> like this: <input type="file" id="docpicker" accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"> capture The capture attribute value is a string that specifies which camera to use for capture of image or video data, if the accept attribute indicates that the input should be of one of those types. A value of user indicates that the user-facing camera and/or microphone should be used. A value of environment specifies that the outward-facing camera and/or microphon...
...me examples: accept="image/png" or accept=".png" -- Accepts PNG files. accept="image/png, image/jpeg" or accept=".png, .jpg, .jpeg" -- Accept PNG or JPEG files. accept="image/*" -- Accept any file with an image/* MIME type. (Many mobile devices also let the user take a picture with the camera when this is used.) accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" -- accept anything that smells like an MS Word document. Let's look at a more complete example: <form method="post" enctype="multipart/form-data"> <div> <label for="profile_pic">Choose file to upload</label> <input type="file" id="profile_pic" name="profile_pic" accept=".jpg, .jpeg, .png"> </div> <div> <button>Submit</button> </div> </fo...
...ggle an option in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types. Because of this, you should make sure that the accept attribute is backed up by appropriate server-side validation. Notes You cannot set the value of a file picker from a script -- doing something like the following has no effect: const input = document.querySelector("input[type=file]"); input.value = "foo"; When a file is chosen using an <input type="file">, the real path to the source file is not shown in the input's value attribute for obvious security reasons. Instead, the filename is shown, with C:\fakepath\ appended to the beginning of it. There are some historical reasons for this quirk, but it is supported across all modern browse...
...And 4 more matches
<template>: The Content Template element - HTML: Hypertext Markup Language
Web › HTML › Element › 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. 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. Content categories Metadata content, flow content, phrasing content, script-supporting element Permitted content No restrictions Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts metadata ...
...orting elements. Also allowed as a child of a <colgroup> element that does not have a span attribute. Implicit ARIA role No corresponding role Permitted ARIA roles No role permitted DOM interface HTMLTemplateElement Attributes This element only includes the global attributes. However, the HTMLTemplateElement has a content property, which is a read-only DocumentFragment containing the DOM subtree which the template represents. Note that directly using the value of the content could lead to unexpected behavior, see Avoiding DocumentFragment pitfall section below. Examples First we start with the HTML portion of the example. <table id="producttable"> <thead> <tr> <td>UPC_Code</td> <td>Product_Name</td> </tr> </thead> <tbody> ...
...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 template element's content attribute. ...
...And 4 more matches
Link types - HTML: Hypertext Markup Language
List of the defined link types and their significance in HTML Link Type Description Allowed in these elements Not allowed in these elements alternate If the element is <link> and the rel attribute also contains the stylesheet type, the link defines an alternative style sheet; in that case the title attribute must be present and not be the empty string. If the type is set to application/rss+xml or application/atom+xml, the link defines a syndication feed. The first one defined on the page is the default. ...
...For example, a blog entry could link to a monthly index page this way. Note: Although recognized, the singular archive is incorrect and must be avoided. <a>, <area>, <link> <form> author Defines a hyperlink to a page describing the author or providing a way to contact the author. Note: This may be a mailto: hyperlink, ...
...<form> last Indicates that the hyperlink leads to the last resource of the sequence the current page is in. Note: Other link types related to linking resources in the same sequence are first, prev, next. Although recognized, the synonym end is incorrect and must be avoided. <a>, <area>, <link> <form> license Indicates that the hyperlink leads to a document describing the licensing information. If not inside the <head> element, the standard doesn't distinguish between a hyperlink applying to a specific part of the document or to the document as a whole. Only the data on the page can indicate this. Note: Although recognized, the synonym copyright is incorrect and must be avoided. <a>, <area>, <form>, <link> None. manifest I...
...And 4 more matches
Using the application cache - HTML: Hypertext Markup Language
first time a user loads an application that uses the application cache. The notification bar displays a message such as: This website (example.com) is asking to store data on your computer for offline use. [Allow] [Never for This Site] [Not Now] The term "offline(-enabled) applications" sometimes refers specifically to applications that the user has allowed to use offline capabilities. Loading documents The use of an application cache modifies the normal process of loading a document: If an application cache exists, the browser loads the document and its associated resources directly from the cache, without accessing the network. This speeds up the document load time. The browser then checks to see if the cache manifest has been updated on the server. If the cache manifest has been update...
...che, without accessing the network. This speeds up the document load time. The browser then checks to see if the cache manifest has been updated on the server. If the cache manifest has been updated, the browser downloads a new version of the manifest and the resources listed in the manifest. This is done in the background and does not affect performance significantly. The process for loading documents and updating the application cache is specified in greater detail below: When the browser visits a document that includes the manifest attribute, if no application cache exists, the browser loads the document and then fetches all the entries listed in the manifest file, creating the first version of the application cache. ...
...In addition, the browser also sends a checking event to the window.applicationCache object, and fetches the manifest file, following the appropriate HTTP caching rules. ...
...And 4 more matches
HTTP conditional requests - HTTP
HTTP has a concept of conditional requests, where the result, and even the success of a request, can be changed by comparing the affected 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. Principles HTTP conditional requests are requests that are executed differently, depending on the value of specific headers. These headers define a precondition, and the result of the request will be different if the precondition is matched or not. The different behaviors are defined by the method of the request used, and by the set of headers used for a precondition: ...
...ts are requests that are executed differently, depending on the value of specific headers. These headers define a precondition, and the result of the request will be different if the precondition is matched or not. The different behaviors are defined by the method of the request used, and by the set of headers used for a precondition: for safe methods, like GET, which usually tries to fetch a document, the conditional request can be used to send back the document, if relevant only. Therefore, this spares bandwidth. for unsafe methods, like PUT, which usually uploads a document, the conditional request can be used to upload the document, only if the original it is based on is the same as that stored on the server. Validators All conditional headers try to check if the resource stored on the...
...k if the resource stored on the server matches a specific version. To achieve this, the conditional requests need to indicate the version of the resource. As comparing the whole resource byte to byte is impracticable, and not always what is wanted, the request transmits a value describing the version. Such values are called validators, and are of two kinds: the date of last modification of the document, the last-modified date. an opaque string, uniquely identifying each version, called the entity tag, or the etag. Comparing versions of the same resource is a bit tricky: depending on the context, there are two kinds of equality checks: Strong validation is used when byte to byte identity is expected, for example when resuming a download. Weak validation is used when the user-agent only ne...
...And 4 more matches
Cross-Origin-Opener-Policy - HTTP
This allows you to have more control over references to a window than rel=noopener, which only affects outgoing navigations. ...
...This allows you to have more control over references to a window than rel=noopener, which only affects outgoing navigations. ...
...This allows you to have more control over references to a window than rel=noopener, which only affects outgoing navigations. ...
...And 4 more matches
Large-Allocation - HTTP
tions can use large contiguous blocks of allocated memory. For complex games, for example, these allocations can be quite large, sometimes as large as 1GB. The Large-Allocation tells the browser that the web content in the to-be-loaded page is going to want to perform a large contiguous memory allocation and the browser can react to this header by starting a dedicated process for the to-be-loaded document, for example. Header type Response header Forbidden header name no Syntax Large-Allocation: 0 Large-Allocation: <megabytes> Directives 0 0 is a special value which represents uncertainty as to what the size of the allocation is. <megabytes> The expected size of the allocation to be performed, in megabytes. Examples Large-Allocation: 0 Large-Allocation: ...
...in the web console. This page was loaded in a new process due to a Large-Allocation header. This message means that the browser saw the Large-Allocation header, and was able to reload the page into a new process which should have more available contiguous memory. A Large-Allocation header was ignored due to the load being triggered by a non-GET request. When a POST request is used to load a document, that load cannot currently be redirected into a new process. This error is displayed when loading a document with a Large-Allocation header with a non-GET HTTP method. This could be caused due to the document being loaded by a form submission, for example. A Large-Allocation header was ignored due to the presence of windows which have a reference to this browsing context through the frame hiera...
...w process. This error is displayed when loading a document with a Large-Allocation header with a non-GET HTTP method. This could be caused due to the document being loaded by a form submission, for example. A Large-Allocation header was ignored due to the presence of windows which have a reference to this browsing context through the frame hierarchy or window.opener. This error means that the document was not loaded at the top level of an user-opened or noopener-opened tab or window. It can occur in these situations: The document with the Large-Allocation header was loaded in an <iframe>. Firefox cannot move an iframe into a new process currently, so the document must load in the current process. ...
...And 4 more matches
Introduction - JavaScript
u 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. 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 lea...
...r them. JavaScript contains a standard library of objects, such as Array, Date, and Math, and a core set of language elements such as operators, control structures, and statements. Core JavaScript can be extended for a variety of purposes by supplementing it with additional objects; for example: Client-side JavaScript extends the core language by supplying objects to control a browser and its Document Object Model (DOM). For example, client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation. Server-side JavaScript extends the core language by supplying objects relevant to running JavaScript on a server. For example, server-side extensions allow an application to communicate with a database, pr...
...merly an acronym for the European Computer Manufacturers Association) to deliver a standardized, international programming language based on JavaScript. This standardized version of JavaScript, called ECMAScript, behaves the same way in all applications that support the standard. Companies can use the open standard language to develop their implementation of JavaScript. The ECMAScript standard is documented in the ECMA-262 specification. See New in JavaScript to learn more about different versions of JavaScript and ECMAScript specification editions. The ECMA-262 standard is also approved by the ISO (International Organization for Standardization) as ISO-16262. You can also find the specification on the Ecma International website. The ECMAScript specification does not describe the Document Object ...
...And 4 more matches
xlink:href - SVG: Scalable Vector Graphics
0" xmlns="http://www.w3.org/2000/svg"> <a xlink:href="https://developer.mozilla.org/"><text x="10" y="25">MDN Web Docs</text></a> </svg> a For <a>, xlink:href defines the location of the referenced object. Value <iri> Default value None Animatable Yes altGlyph For <altGlyph>, xlink:href defines the reference either to a <glyph> element in an SVG document fragment or to an <altGlyphDef> element. If the reference is to a <glyph> element and that glyph is available, then that glyph is rendered instead of the characters that are inside of the <altGlyph> element. If the reference is to an <altGlyphDef> element, then if an appropriate set of alternate glyphs is located from processing the <altGlyphDef> element, then those alternate glyphs are ren...
... <iri> Default value None Animatable No animate, animateColor, animateMotion, animateTransform, set For <animate>, <animateColor>, <animateMotion>, <animateTransform>, and <set>, xlink:href defines the reference to the element which is the target of this animation and which therefore will be modified over time. The target element must be part of the current SVG document fragment. The value must point to exactly one target element which is capable of being the target of the given animation. If the xlink:href attribute is not provided, the target element will be the immediate parent element of the current animation element. Refer to the descriptions of the individual animation elements for any restrictions on what types of elements can be targets of particular ...
...ovides the image of the cursor. Value <funciri> Default value None Animatable Yes feImage For <feImage>, xlink:href defines the reference to the image source. Value <iri> Default value None Animatable Yes filter For <filter>, xlink:href defines the reference to another <filter> element within the current SVG document fragment. Any attributes which are defined on the referenced <filter> element which are not defined on this element are inherited by this element. If this element has no defined filter nodes, and the referenced element has defined filter nodes (possibly due to its own xlink:href attribute), then this element inherits the filter nodes defined from the referenced <filter> element. Inheritance can b...
...And 4 more matches
Example - SVG: Scalable Vector Graphics
. </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 software is free for you to use in any way whatsoever, and comes with no warranty at all. </div> <form action="" onsubmit="return false;"> <p> <label>Number of motes:</label> <input id='num_motes' value='5'/> <br/> <label>Max. Velocity:</label> <input id='max_velocity' value='15'/> <br/> ...
... <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') ); var height = parseInt( display.getAttributeNS(null,'height') ); return [width,height]; } // This is called b...
...{ // Our Rendering Element var display = Display(); var width = parseInt( display.getAttributeNS(null,'width') ); var height = parseInt( display.getAttributeNS(null,'height') ); return [width,height]; } // This is called by mouse move events var mouse_x = 200, mouse_y = 150; function OnMouseMove(evt) { mouse_x = evt.clientX; mouse_y = evt.clientY; var widget = document.getElementById('cursor'); widget.setAttributeNS(null,'cx',mouse_x); widget.setAttributeNS(null,'cy',mouse_y); } document.onmousemove = OnMouseMove; // Determine (x,y) of the cursor function Cursor() { return [mouse_x, mouse_y]; } // Determine average (x,y) of the swarm function AverageMotePosition() { if( !motes ) return [0,0]; if( motes.length == 0 ) r...
...And 4 more matches
Using shadow DOM - Web Components
is, providing a way to attach a hidden separated DOM to an element. This article covers the basics of using the Shadow DOM. Note: Shadow DOM is supported by default in Firefox (63 and onwards), Chrome, Opera, and Safari. The new Chromium-based Edge (75 and onwards) supports it too; the old Edge didn't. High-level view This article assumes you are already familiar with the concept of the DOM (Document Object Model) -- a tree-like structure of connected nodes that represents the different elements and strings of text appearing in a markup document (usually an HTML document in the case of web documents). As an example, consider the following HTML fragment: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Simple DOM example</title> </head> <body> <section> ...
...'s worth. If you are attaching a shadow DOM to a custom element as part of its constructor (by far the most useful application of the shadow DOM), you would use something like this: let shadow = this.attachShadow({mode: 'open'}); When you've attached a shadow DOM to an element, manipulating it is a matter of just using the same DOM APIs as you use for the regular DOM manipulation: let para = document.createElement('p'); shadow.appendChild(para); // etc. 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 provid...
...fines all the functionality the element will have when an instance of it is instantiated. ...
...And 4 more matches
XML introduction - XML: Extensible Markup Language
, and shared. Most importantly, since the fundamental format of XML is standardized, if you share or transmit XML across systems or platforms, either locally or over the internet, the recipient can still parse the data due to the standardized XML syntax. There are many languages based on XML, including XHTML, MathML, SVG, XUL, XBL, RSS, and RDF. You can also define your own. Structure of an XML document This sub-article in process writing... Whole structure XML and XML based languages built on tags. XML declaration XML - declaration is not a tag. It is used for the transmission of the meta-data of a document. <?xml version="1.0" encoding="UTF-8"?> Attributes: version : Used version XML in this document. encoding : Used encoding in this document. Comments <!-- Comment --> "Corr...
... Document must conform to all XML syntax rules. Document must conform to semantic rules, which are usually set in an XML schema or a DTD (Document Type Definition). ...
... is not a tag. It is used for the transmission of the meta-data of a document. <?xml version="1.0" encoding="UTF-8"?> Attributes: version : Used version XML in this document. encoding : Used encoding in this document. Comments <!-- Comment --> "Correct" XML (valid and well-formed) ?orrect design rules For an XML document to be correct, the following conditions must be fulfilled: Document must be well-formed. Document must conform to all XML syntax rules. Document must conform to semantic rules, which are usually set in an XML schema or a DTD (Document Type Definition). Example <?xml version="1.0" encoding="UTF-8"?> <message> <warning> Hello World <!--missing </warning> --> </message> Now let's look at a corrected version of that same document: <?xml versio...
...And 4 more matches
An Overview - XSLT: Extensible Stylesheet Language Transformations
<< Transforming XML with XSLT The eXtensible Stylesheet Language/Transform is a very powerful language, and a complete discussion of it is well beyond the scope of this article, but a brief discussion of some basic concepts will be helpful in understanding the description of Netscape's capabilities that follows. An XSLT stylesheet is an XML document. Unlike CSS, which has its own specialized syntax, an XSLT stylesheet is an XML document, which must conform to all XML rules, including well-formedness. So the model for transformation is that one XML document is used to transform another XML document. An XSLT stylesheet is marked as such by the inclusion of a standard XSLT heading. The outermost element in an XSLT stylesheet must be the <xsl:stylesheet> element (an acceptable alternate...
...ique identifier for a known set of elements. The string "http://www.w3.org/1999/XSL/Transform" is a constant that designates the elements so marked as belonging to the set of tags designated by the W3C in the 1999 XSLT Recommendation. Another string that is occasionally seen in stylesheets, "http://www.w3.org/TR/WD-xsl", indicates compliance with an earlier working draft (hence the WD) of the W3C document. This latter namespace is not compatible with the one that the W3C eventually adopted and is not supported by Netscape. Because typing "http://www.w3.org/1999/XSL/Transform" repeatedly would be tedious and would render the markup difficult to read, there is a standard mechanism for assigning a shorthand name to the namespace in the stylesheet heading. Thus a full example of the opening styleshe...
...er the markup difficult to read, there is a standard mechanism for assigning a shorthand name to the namespace in the stylesheet heading. Thus a full example of the opening stylesheet element might look like this. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> The xmlns pseudo-attribute maps the shorthand name xsl onto the full namespace for use throughout the document that follows. Thus the stylesheet element above is prefixed with xsl:. Although xsl is the conventionally used shorthand name (called the prefix), it is not mandatory and it is quite possible to choose a different one. The examples in this article all assume the use of the xsl prefix. All XSLT transformations are performed on trees, not documents. The XSLT transformation engine, called the pr...
...And 4 more matches
panel - Archive of obsolete content
s.Panel({ contentURL: self.data.url("panel.html"), onHide: handleHide }); function handleChange(state) { if (state.checked) { myPanel.show({ position: button }); } } function handleHide() { button.state('window', {checked: false}); } Updating panel content You can update the panel's content by: sending a message to a content script that updates the DOM in the same document. This is usually the best approach. embedding an iframe in the panel, and changing its document setting the panel's contentURL property. However, doing this will cause any content scripts to be unloaded and then reloaded, so it may be less efficient, and you'll lose any state associated with the scripts. Scripting panel content You can't directly access your panel's content from your main ad...
... text the user // entered. // In this implementation we'll just log the text to the console. textEntryPanel.port.on("text-entered", function (text) { console.log(text); textEntryPanel.hide(); }); The content script "get-text.js" looks like this: // When the user hits return, send the "text-entered" // message to main.js. // The message payload is the contents of the edit box. var textArea = document.getElementById("edit-box"); textArea.addEventListener('keyup', function onkeyup(event) { if (event.keyCode == 13) { // Remove the newline. text = textArea.value.replace(/(\r\n|\n|\r)/gm,""); self.port.emit("text-entered", text); textArea.value = ''; } }, false); // Listen for the "show" event being sent from the // main add-on code. It means that the panel's about // to be sho...
...sole. textEntryPanel.port.on("text-entered", function (text) { console.log(text); textEntryPanel.hide(); }); The page script is exactly the same as the content script above, except that instead of self, we use addon to access the messaging APIs: // When the user hits return, send the "text-entered" // message to main.js. // The message payload is the contents of the edit box. var textArea = document.getElementById("edit-box"); textArea.addEventListener('keyup', function onkeyup(event) { if (event.keyCode == 13) { // Remove the newline. text = textArea.value.replace(/(\r\n|\n|\r)/gm,""); addon.port.emit("text-entered", text); textArea.value = ''; } }, false); // Listen for the "show" event being sent from the // main add-on code. It means that the panel's about // to be sh...
...And 3 more matches
Canvas code snippets - Archive of obsolete content
elcolour(canvas, x, y) { var cx = canvas.getContext('2d'); var pixel = cx.getImageData(x, y, 1, 1); return { r: pixel.data[0], g: pixel.data[1], b: pixel.data[2], a: pixel.data[3] }; } Chaining methods This class provides jQuery-style chained access to 2D context methods and properties. ...
...f getterMethods) { let method = m; Canvas2DContext.prototype[method] = function() { return this.ctx[method].apply(this.ctx, arguments); }; } for (let p of props) { let prop = p; Canvas2DContext.prototype[prop] = function(value) { if (value === undefined) return this.ctx[prop]; this.ctx[prop] = value; return this; }; } }; var canvas = document.getElementById('canvas'); // Use context to get access to underlying context var ctx = Canvas2DContext(canvas) .strokeStyle('rgb(30, 110, 210)') .transform(10, 3, 4, 5, 1, 0) .strokeRect(2, 10, 15, 20) .context; // Use property name as a function (but without arguments) to get the value var strokeStyle = Canvas2DContext(canvas) .strokeStyle('rgb(50, 110, 210)') .strokeStyle(); Cod...
...are running the page from chrome. If you try running the code as a plain webpage, you will get a 'Security error" code: "1000' error. RemoteCanvas = function() { this.url = 'http://developer.mozilla.org'; }; RemoteCanvas.CANVAS_WIDTH = 300; RemoteCanvas.CANVAS_HEIGHT = 300; RemoteCanvas.prototype.load = function() { var windowWidth = window.innerWidth - 25; var iframe; iframe = document.createElement('iframe'); iframe.id = 'test-iframe'; iframe.height = '10px'; iframe.width = windowWidth + 'px'; iframe.style.visibility = 'hidden'; iframe.src = this.url; // Here is where the magic happens... add a listener to the // frame's onload event iframe.addEventListener('load', this.remotePageLoaded, true); //append to the end of the page window.docu...
...And 3 more matches
Dialogs and Prompts - Archive of obsolete content
ns buttons is made with <dialogheader>: <dialogheader title="General" description="whatever"/> Note, that you should only use this element in a <dialog>, because otherwise it may be not styled properly. (Although it seems to work in <window> as well). Programmatic button access If you want to access the accept ("OK") and cancel buttons from script, use this: // Disable the OK and Cancel btns document.documentElement.getButton("accept").disabled = true; document.documentElement.getButton("cancel").disabled = true; Links dialog.xml -- XBL bindings for <dialog> and <dialogheader> elements. Passing parameter to a dialog and getting return values from it. Passing arguments and displaying a dialog The following code demonstrates how to pass custom arguments to a dialog, process those argu...
... // Notice if user clicks cancel, window.arguments[0].out remain...
... // Notice if user clicks cancel, window.arguments[0].out remains null // because this function is never called window.arguments[0...
...And 3 more matches
Miscellaneous - Archive of obsolete content
e 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. ...
...It also collapses consecutive whitespaces into a single whit...
...ined at //github.com/RealityRipple/Pale-Moon/blob/master/palemoon/base/content/browser.js#L5113. Note that it returns the empty string (""), not false, when nothing is selected. getBrowserSelection() is not implemented on some platforms, such as Thunderbird and Songbird. See also http://mxr.mozilla.org/seamonkey/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...
...And 3 more matches
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
which allows to not override values, but also lets you define getters and setters. Alternative: Proxy If you cannot override objects or properties easily, e.g. because the object is frozen or sealed, then creating a Proxy around the object might be a viable approach. Triggering event handlers Sometimes scripts might want to manually trigger an event handler that is defined directly in the XUL document. ...
...t want to manually trigger an event handler that is defined directly in the XUL document. Consider the following XUL fragment throughout the rest of this section. <menuitem id="mymenu" oncommand="executeSomething(); executeSomethingElse();"/> <label id="mylabel" onclick="executeSomething(); executeSomethingElse();"/> Add-on authors commonly use eval to trigger the handlers. // DO NOT USE eval(document.getElementById("mymenu").getAttribute("oncommand")); eval(document.getElementById("mylabel").getAttribute("onclick")); Alternative: Dispatch real events Dispatching real events has the added bonus that all other event listeners for that Element (and the corresponding bubbling/capturing chain) will fire as well, so this method will have the closed resemblance to a real user event. // Fake a co...
...).getAttribute("oncommand")); eval(document.getElementById("mylabel").getAttribute("onclick")); Alternative: Dispatch real events Dispatching real events has the added bonus that all other event listeners for that Element (and the corresponding bubbling/capturing chain) will fire as well, so this method will have the closed resemblance to a real user event. ...
...And 3 more matches
Appendix F: Monitoring DOM changes - Archive of obsolete content
DOM mutation events were introduced to HTML several years ago in order to allow web applications to monitor changes to the DOM by other scripts. Unfortunately, adding listeners for any of these events to a document has a highly deleterious effect on performance, an effect which is not mitigated in the slightest by later removing those listeners. For this reason, it is best to avoid using mutation listeners at all costs, especially from extensions. This document lays out some alternatives which do not have such severe performance impacts. Mutation observers Mutation observers are the more efficient, W3C speced replacement for the highly inefficient mutation events. Their major advantage is in their performance and their ease of use, especially when combined with simple libraries. Their main disa...
...ired if one wishes to support other browsers, or to run in non-chrome-privileged scopes. /** * Watches for nodes matching the given CSS selector to become * available. * * @param {string} selector The CSS selector of nodes about which you * want to be notified. * @param {function(Event)} callback The function which is to be called * when matching nodes become available. * @param {Document} doc The document in which to watch for new nodes. * @optional @default document * * @returns {function} A function which may be called to unregister the * listener. */ if ('MozCSSKeyframeRule' in window || 'CSSKeyframeRule' in window) { var watchNodes = function watchNodes(selector, callback, doc) { const EVENT = watchNodes.PREFIX + (watchNodes._i++); const XHTML = '...
...* @optional @default document * * @returns {function} A function which may be called to unregister the * listener. ...
...And 3 more matches
Security best practices in extensions - Archive of obsolete content
Your goal is to keep your users safe. Some items mentioned are strict guidelines, meaning that if you don't follow them then your add-on will not be approved on Mozilla add-ons. Other items are recommendations. The difference will be clearly flagged. This is written from the perspective of a Firefox extension, but most items apply to extensions for other Mozilla-based applications such as Thunderbird or SeaMonkey. Web content handling In general the best way to ensure that the browser is not compromised when you load content is to make sure it does not have those privileges. ...
...items apply to extensions for other Mozilla-based applications such as Thunderbird or SeaMonkey. Web content handling In general the best way to ensure that the browser is not compromised when you load content is to make sure it does not have those privileges. A more detailed explanation of this process is in Displaying web content in an extension without security issues. The privileges that a document gets also depend on where it comes from. For example, if you load a chrome URL, this means the content has been registered with Firefox and has full access. Content from a domain (such as http://www.example.com) can only access that same domain. Files loaded using the file protocol can access files on the user's disk and other local devices. There are ways to get around the content/chrome securi...
...me domain. Files loaded using the file protocol can access files on the user's disk and other local devices. There are ways to get around the content/chrome security barrier, if for example, 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.allowJavascript = 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 ...
...And 3 more matches
Add-ons - Archive of obsolete content
Archived add-ons documentation. Add-on SDK Using the Add-on SDK, you can create Firefox add-ons. You can use various standard Web technologies: JavaScript, HTML, and CSS, to create the add-ons. The SDK includes JavaScript APIs, which you can use to create add-ons and tools for creating, running, testing, and packaging add-ons. 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 ... Creating custom Firefox extensions with the Mozilla build system There is a wealth of material on creating extensions for Firefox. ...
... add-ons. 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 ... 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 Extensio...
...y structure which can provide chrome, components, and other files to extend the functionality of an XUL program. Extensions support in SeaMonkey 2 Starting with SeaMonkey 2 Alpha 1 SeaMonkey supports toolkit/-style extensions. These type of extensions have many advantages for both users and developers compared to the old xpinstall/-style extensions. Firefox addons developer guide The original document is in Japanese and distributed via the xuldev.org website. So there may be still some reference to the xuldev website (we want to host source code on MDC, not on xuldev), and to Japanese things (like some specific locales, which have been translated to French since non-latin characters are not well supported). Hotfix Extension This document has been moved to the Add-ons wiki. How to convert an...
...And 3 more matches
Using XML Data Islands in Mozilla - Archive of obsolete content
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. ...
...Here is a co...
...> <head> <title>XML Data Block Demo</title> <script id="purchase-order" type="application/xml"> <purchaseOrder xmlns="http://example.mozilla.org/PurchaseOrderML"> <lineItem> <name>Line Item 1</name> <price>1.25</price> </lineItem> <lineItem> <name>Line Item 2</name> <price>2.48</price> </lineItem> </purchaseOrder> </script> <script> function runDemo() { var orderSource = document.getElementById("purchase-order").textContent; var parser = new DOMParser(); var doc = parser.parseFromString(orderSource, "application/xml"); var lineItems = doc.getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "lineItem"); var firstPrice = lineItems[0].getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "price")[0].textContent; document.body.textCon...
...And 3 more matches
Creating a Microsummary - Archive of obsolete content
efox encounters a <link rel="microsummary"> element, it loads the URL in the href attribute. If the URL points to a generator, it uses the generator to generate the microsummary for the page. Otherwise, if the URL returns plain text content (or HTML content that can be converted to plain text), Firefox uses the content as the microsummary for the page. Beginnings Generators are expressed as XML documents whose root element is the <generator> element in the http://www.mozilla.org/microsummaries/0.1 namespace. To begin building the generator, create a new empty text file and add an XML declaration and empty <generator> tag to it: <?xml version="1.0" encoding="UTF-8"?> <generator xmlns="http://www.mozilla.org/microsummaries/0.1"> </generator> Giving it a Name Generators should have name attribu...
...Firefox Download Count": <?xml version="1.0" encoding="UTF-8"?> <generator xmlns="http://www.mozilla.org/microsummaries/0.1" name="Firefox Download Count"> </generator> Adding an XSLT Transform Sheet Generators must include an XSLT transform sheet (also known as an XSLT stylesheet) which transforms the page content into its microsummary. XSLT is a powerful language for transforming documents into different representations of the same information. Add the XSLT transform sheet to the generator by including it within a <template> element: <?xml version="1.0" encoding="UTF-8"?> <generator xmlns="http://www.mozilla.org/microsummaries/0.1" name="Firefox Download Count"> <template> <transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0"> </transform> ...
...But fo...
...And 3 more matches
JavaScript crypto - Archive of obsolete content
vices are available via the DOM window object as window.crypto. Services are provided to enable: smart card events, generating certificate requests, importing user certs, generating random numbers, logging out of your tokens, and signing text. Handling smart card events Web sites can make themselves more SmartCard friendly by listening for SmartCard insertion and removal events. To enable your document to receive these events, you must first tell the crypto system you are interested by setting window.crypto.enableSmartCardEvents to true. You can then register event handlers for these events with the document.addEventListener() method. Two smart card related events are generated: smartcard-insert when SmartCards are inserted, and smartcard-remove when SmartCards are removed. Web sites which us...
...re generated: smartcard-insert when SmartCards are inserted, and smartcard-remove when SmartCards are removed. Web sites which use SSL clientAuth login could use the following code to refresh the page on token insertions and removals: <!DOCTYPE html> <p>... ...
...remove when SmartCards are removed. Web sites which use SSL clientAuth login could use the following code to refresh the page on token insertions and removals: <!DOCTYPE html> <p>... ...
...And 3 more matches
Namespaces - Archive of obsolete content
To quote Wikipedia: "In general, a namespace is an abstract container providing context for the items ... it holds and allows disambiguation of items having the same name." If you are familiar with C++ namespaces, Java packages, perl packages, or Python module importing, you are already familiar with the namespace concept. An XML namespace is identified by an unique name (called a URI, not a URL, even though it can look like a URL). ...
...(e.g., <textbox/>) in their schema/DTD. Any element type or attribute name in an XML namespace can be uniquely identified by its XML namespace and its "local name". Together, these two items define a qualified name, or QName. For example, <xul:textbox/> uses a namespace named "xul" and a local name "textbox". This distinguishes it from, for example, <foobar:textbox/> which might occur in the same document. ...
...an XML namespace can be uniquely identified by its XML namespace and its "local name". Together, these two items define a qualified name, or QName. For example, <xul:textbox/> uses a namespace named "xul" and a local name "textbox". This distinguishes it from, for example, <foobar:textbox/> which might occur in the same document. The xul and foobar namespaces must be defined at the top of the XML document in which they are used, like so: <foobar:some-element xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:foobar="the-foobar-namespace"> <xul:textbox id="foo" value="bar"/> <foobar:textbox favorite-food="pancakes"/> </foobar:some-element> Notice I've mixed two <textboxes/> in the same document. The only way to distinguish that they have different mea...
...And 3 more matches
PopupEvents - Archive of obsolete content
e popupshown event will be fired when the UI is updated and the popup is visible. One possible use of the popupshown event is to open another menu. This technique, as shown in the following example, is needed if you wish to open a submenu programmatically. This is because you cannot open a submenu directly without first opening the parent menu. ...
...wing example, is needed if you wish to open a submenu programmatically. This is because you cannot open a submenu directly without first opening the parent menu. ...
...his is because you cannot open a submenu directly without first opening the parent menu. ...
...And 3 more matches
The Joy of XUL - Archive of obsolete content
ificant amount of effort to achieve these results 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 ...
...s supported platforms, and access to native resources such as shared libraries and the local file system. Whether you need to migrate an existing web application to the desktop, are looking for a technology that will enable you to easily port your applications to multiple platforms, or want to integrate your own cool features into the browser, XUL warrants serious consideration. ...
...al file system. Whether you need to migrate an existing web application to the desktop, are looking for a technology that will enable you to easily port your applications to multiple platforms, or want to integrate your own cool features into the browser, XUL warrants serious consideration. ...
...And 3 more matches
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
this.clipboard : '';"/> </handlers> </binding> Th...
...A field clip...
...A field clipboard has been added to it to store the clipboard contents. This does mean that the clipboard operations are limited to this single text...
...And 3 more matches
Manipulating Lists - Archive of obsolete content
ns be used instead when possible. These functions are bit simpler and will do the right thing. The appendItem() function is used to append a new item to the end a list. Similar to the DOM appendChild() function except that it takes a string label, and you do not have to worry about where to add it in the list structure. Here is an example: Example 1 : Source View <script> function addItem(){ document.getElementById('thelist').appendItem("Thursday", "thu"); } </script> <listbox id="thelist"/> <button label="Add" oncommand="addItem();"/> The appendItem() takes two arguments, the label, in this case 'Thursday', and a value 'thu'. The two arguments correspond to the label attribute and the value attribute on the listitem element. The value is used only as an extra optional value associated wi...
... a new value to change the selection. In the next example, the selectedIndex property of a radiogroup element is changed based on the value entered in a textbox. This code isn't foolproof though; for example it doesn't check if the value entered is out of range. You will want to make sure that you add this kind of error checking. ...
... of a radiogroup element is changed based on the value entered in a textbox. This code isn't foolproof though; for example it doesn't check if the value entered is out of range. You will want to make sure that you add this kind of error checking. ...
...And 3 more matches
Modifying a XUL Interface - Archive of obsolete content
<< PreviousNext >> The DOM provides various functions to modify the document. Creating New Elements You can create new elements using the createElement() function of the document. It takes one argument, the tag name of the element to create. You can then set attributes of the element using the setAttribute() function and append it to the XUL document using the appendChild() function. ...
...w elements using the createElement() function of the document. It takes one argument, the tag name of the element to create. You can then set attributes of the element using the setAttribute() function and append it to the XUL document using the appendChild() function. For example, the following will add a button to a XUL window: Example 1 : Source View <script> function addButton(){ var aBox = document.getElementById("aBox"); var button = document.createElement("button"); button.setAttribute("label","A new Button"); aBox.appendChild(button); } </script> <box id="aBox" width="200"> <button label="Add" oncommand="addButton();"/> </box> This example has two parts a box container element in XUL. Notice that this is NOT the same as a vbox or an hbox. (This is discussed more i...
...ble box, so it becomes visible as well. The button with the label "Add" can be pressed multiple times and it will continue to add new buttons, each of which will have the label "A new Button", and will only be distinguishable by their place as children in the box element with the id "abox". The createElement() function will create the default type of element for the document. For XUL documents, this generally means that a XUL element will be created. For an HTML document, an HTML element will be created, so it will have the features and functions of an HTML element instead. The createElementNS() function may be used to create elements in a different namespace. The appendChild() function is used to add an element as a child of another element. Three related functions ...
...And 3 more matches
XUL Structure - Archive of obsolete content
gin by looking at how the XUL is handled in Mozilla. How XUL is Handled In Mozilla, XUL is handled in much the same way as HTML or other types of content are handled. When you type the URL of an HTML page into the browser's address field, the browser locates the web site and downloads the content. The Mozilla rendering engine takes the content in the form of HTML source and transforms it into a document tree. The tree is then converted into a set of objects that can be displayed on the screen. Style sheets (CSS), images, and other technologies are used to control the presentation. XUL functions in much the same way. In fact, in Mozilla, all document types, whether they are HTML or XUL, or even SVG, are all handled by the same underlying code. This means that the same CSS properties may be used ...
...ures that are specific to HTML, such as forms, and others which are specific to XUL, such as overlays. Since XUL and HTML are handled in the same way, you can load both from either your local file system, from a web page, or from an extension or standalone XULRunner application. Content from remote sources (e.g. http://localhost/~username/ ), regardless of whether they are HTML or XUL or another document type, are limited in the type of operations they can perform, for security reasons. For this reason, Mozilla provides a method of installing content locally and registering the installed files as part of its chrome system. This allows a special URL form, called a chrome:// URL, to be used. By accessing a file using a chrome URL, the files receive elevated privileges to access local files, access ...
...ozilla does not use the file extension, unless reading files from the file system, but you should use the .xul extension for all XUL files. You can load XUL files from your own machine by opening them in the browser, or by double-clicking the file in your file manager. Remember that remote XUL will have significant restrictions on what it can do, and DOES NOT WORK WITH CURRENT FIREFOX VERSIONS! Document types: HTML XML XUL CSS Mozilla uses a distinctly different kind of document object (DOM) for HTML and XUL, although they share much of the same functionality. There are three main types of document in Mozilla: HTML, XML, and XUL. Naturally, the HTML document is used for HTML documents, the XUL document is used for XUL documents, and the XML document is used for other types of XML documents. Sin...
...And 3 more matches
Gecko Compatibility Handbook - Archive of obsolete content
ns). 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 the W3 standards and Gecko browsers Content differs i...
...aths in URLs such as http://example.com/directory/... Verify that all hyperlinks use forward slashes (/) Clicking on a link displays a "download" or displays HTML code instead of rendering the page correctly, but works as expected in Internet Explorer The Web Server has incorrectly specified the MIME type for the content. Internet Explorer tries to guess the MIME type of documents while Gecko browsers relies upon the Web Server to specify the correct MIME type. Gecko does not try to 'sniff' the MIME type for a document in order to reduce the possibility of unsecure, dangerous content masquerading as as a safe MIME type. Use Perl's HEAD utitility to determine the actual MIME type being used by the Web Server. Correct any incorrect Server MIME types. (related ...
...y following the tag name with a space followed with as slash as in <tag />. To be backwardly compatible you must have a space before the trailing />. In addition, you must only use the XML Empty tag notation for HTML Elements that are always Empty - and not for HTML Elements that have optional ending tags. For example, it is ok to code <br> as <br /> although there is no benefit to do so in HTML documents. But it is not OK to code <option> as <option />. To understand why, consider the following: HTML without optional ending tags Equivalent HTML with optional ending tags <select> <option>OptionValue </select> <select> <option>OptionValue</option> </select> Now consider if we used the XML Empty tag notation: the <option />. HTML with XM...
...And 3 more matches
Mozilla release FAQ - Archive of obsolete content
No guarantee of factuality in this FAQ is made, and it is maintained by Pat Gunn, who is not affiliated with Netscape. Various other people have contributed to this FAQ. General Questions about the Mozilla Project What is Mozilla? Mozilla is a project to continue Netscape Communicator as an open project. The project is maintained by employees of Netscape (now a division of AOL), Red Hat, some other companies, as well as contributors from the community. ...
...re expected to have a pretty good knowlege of it first. For example, if you were to make a proposal to compress whole webpages before sending them, devise a new protocol to do so, research how HTTP works, how HTML works, and think about all the good *and* bad points of reworking things. To start understanding the issues with this example, you should dig up the RFCs for the relevant protocols, any documents written on the subject, etc. For this particular example, you would want to go look at Relevant Topics Stuart Cheshire's discussion on Latency versus Bandwidth Internet -- Under the Covers (by me) The RFC for HTTP The w3's HTML 4.0 definition Building Mozilla I get x error when trying to build Mozilla - what's wrong? First, make sure that you have the latest release of the Mozilla sour...
...for help. Finally, you should make sure that someone is not already working on the code you would need to modify to implement your feature. On www.mozilla.org, there is a list of module 'owners'. This system ensures that 2 people are not working on the same part at the same time. Check for for the module owner, and contact him/her. The specific area that you can find this is on the Mozilla Owners Document. How do I embed Mozilla's rendering engine into my application? Check out GTKmozilla in your tree at webshell/embed/gtk for an example of how to do this Common Topics of Discussion What's this section about? This section is to prevent rehashing of the same debates over and over again on the newsgroups. It might slightly reflect the opinions of Pat Gunn, and if you're really angry about this, drop...
...And 3 more matches
Extentsions FAQ - Archive of obsolete content
em there from the toolbar customisation window, like you would when adding buttons to the toolbars." Option #4 Install Toolbar Control <http://webdesigns.ms11.net/chromeditp.html> Asking for help with getting an extension to process Windows messages. ...
...ng buttons to the toolbars." Option #4 Install Toolbar Control <http://webdesigns.ms11.net/chromeditp.html> Asking for help with getting an extension to process Windows messages. use WM_COPYDATA How to creating an extension that can replace HTML code on a specific page that does not use Greasemonkey? var newNode = document.createElement(" ... html content here ... ...
...etched to the size of the stack. <image left="0" top="0"> would seem to suffice. Could there be more than two images to reflect more than two states?Does the rules in the CSS file have to be in any particular order (if two rules match, which is chosen)? I have two states switching images in the tool bar and would have no problem implementing a third, so yes it's possible. ...
...And 3 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
Public-key cryptography and related standards and techniques underlie the security features of many products such as signed and encrypted email, single sign-on, and Secure Sockets Layer (SSL) communications. This document introduces the basic concepts of public-key cryptography. For an overview of SSL, see "Introduction to SSL." For an overview of encryption and decryption, see "Encryption and Decryption." Information on digital signatures is available from "Digital Signatures." Public-key cryptography is a set of well-established techniques and standards for protecting communications from eavesdropping, tampering, and impersonation attacks. Encryption and decryption allow two communicating parties to disguise information they send to each other. The sender encrypts, or scrambles, info...
...aphy that underlie these capabilities. Certificates and Authentication Managing Certificates Certificates and Authentication A Certificate Identifies Someone or Something Authentication Confirms an Identity How Certificates Are Used Contents of a Certificate How CA Certificates Are Used to Establish Trust A Certificate Identifies Someone or Something A certificate is an electronic document used to identify an individual, a server, a company, or some other entity and to associate that identity with a public key. Like a driver's license, a passport, or other commonly used personal IDs, a certificate provides generally recognized proof of a person's identity. Public-key cryptography uses certificates to address the problem of impersonation. To get a driver's license, you typically ap...
...receiving end, the user will be alerted. The digital signature is unique to the message it accompanies. If the message received differs in any way from the message that was sent-even by the addition or deletion of a comma-the digital signature cannot be validated. Therefore, signed email also provides some assurance that the email has not been tampered with. As discussed at the beginning of this document, this kind of assurance is known as nonrepudiation. In other words, signed email makes it very difficult for the sender to deny having sent the message. This is important for many forms of business communication. (For information about the way digital signatures work, see "Digital Signatures".) S/MIME also makes it possible to encrypt email messages. This is also important for some business user...
...And 3 more matches
Developing cross-browser and cross-platform pages - Archive of obsolete content
re support detection, you only implement those features whose support you have first tested and verified on the visiting browser. This method has the advantage of not requiring you to test for anything except whether the particular features you code are supported in the visiting browser. Let's see a basic, simple object support detection example. ...
...plement those features whose support you have first tested and verified on the visiting browser. This method has the advantage of not requiring you to test for anything except whether the particular features you code are supported in the visiting browser. Let's see a basic, simple object support detection example. ...
...ested and verified on the visiting browser. This method has the advantage of not requiring you to test for anything except whether the particular features you code are supported in the visiting browser. Let's see a basic, simple object support detection example. ...
...And 3 more matches
Archive of obsolete content
e that are using older hardware, for example, and can't upgrade to the latest and greatest browsers. Or for "reasons," your company is required to use very old software and you need to build Web content that runs on that software. Or perhaps you're just curious about the history of an obsolete feature or API, and how it worked. There are many reasons older documentation can be useful. So, we've established this area into which we can archive older documentation. Material in this Archived content zone should not be used for building new Web sites or apps for modern browsers. It's here for historical reference only. See the complete index of archived content Note to writers: We need to try to...
... MDN Web Docs room on Matrix before moving content here. .htaccess ( hypertext access ) File Accessing : htaccess files can be opened using any text editor, like Windows Notepad, Vin, Sublime text editor or any other. Syntax highliting support for .htaccess files less. 2015 MDN Fellowship Program Add-ons Archived add-ons documentation. Adding preferences to an extension This article takes the Creating a dynamic status bar extension sample to the next level, adding a popup menu that lets you quickly switch between multiple stocks to watch. It also adds a preference dialog that lets you switch to a stock other than one of the ones included in the popup menu. An Interview W...
...r 11, 2002, Wired launched a brand-new site design that uses validating XHTML for its structure and a small collection of CSS files for its layout. The new design clearly shows what some experts have been saying: that standards-based design can be visually compelling and preserve the interface conventions we've come to expect from Web pages. API Archived documentation about obsolete web standards APIs. Archived Mozilla and build documentation These articles are archived, obsolete documents about Mozilla, Gecko, and the process of building Mozilla projects. Archived open Web documentation The documentation listed below is archived, obsolete material about open Web topics. Beginner tutorials This page includes...
...And 3 more matches
How CSS is structured - Learn web development
e of CSS, let's examine the structure of CSS. Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of How CSS works. Objective: To learn CSS's fundamental syntax structures in detail. Applying CSS to HTML First, let's examine three methods of applying CSS to a document: with an external stylesheet, with an internal stylesheet, and with inline styles. External stylesheet An external stylesheet contains CSS in a separate file with a .css extension. This is the most common and useful method of bringing CSS to a document. You can link a single CSS file to multiple web pages, styling all of them with the same CSS stylesheet. In the Getting started with CSS, we lin...
...d> <body> <h1>Hello World!</h1> <p>This is my first CSS example</p> </body> </html> The CSS stylesheet file might look like this: h1 { color: blue; background-color: yellow; border: 1px solid black; } p { color: red; } The href attribute of the <link> element needs to reference a file on your file system. In the example above, the CSS file is in the same folder as the HTML document, but you could place it somewhere else and adjust the path. Here are three examples: <!-- Inside a subdirectory called styles inside the current directory --> <link rel="stylesheet" href="styles/style.css"> <!-- Inside a subdirectory called general, which is in a subdirectory called styles, inside the current directory --> <link rel="stylesheet" href="styles/general/style.css"> <!-- Go up one ...
...t" href="styles/style.css"> <!-- Inside a subdirectory called general, which is in a subdirectory called styles, inside the current directory --> <link rel="stylesheet" href="styles/general/style.css"> <!-- Go up one directory level, then inside a subdirectory called styles --> <link rel="stylesheet" href="../styles/style.css"> Internal stylesheet An internal stylesheet resides within an HTML document. To create an internal stylesheet, you place CSS inside a <style> element contained inside the HTML <head>. The HTML for an internal stylesheet might look like this: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My CSS experiment</title> <style> h1 { color: blue; background-color: yellow; border: 1px solid black; } p { ...
...And 3 more matches
Debugging HTML - Learn web development
ode in detail to see how the browser has tried to fix our HTML errors (we did the review in Firefox; other modern browsers should give the same result): The paragraphs and list items have been given closing tags. It isn't clear where the first <strong> element should be closed, so the browser has wrapped each separate block of text with its own strong tag, right down to the bottom of the document! The incorrect nesting has been fixed by the browser as shown here: <strong>strong <em>strong emphasised?</em> </strong> <em> what is this?</em> The link with the missing double quote has been deleted altogether. The last list item looks like this: <li> <strong>Unclosed attributes: Another common source of HTML problems. Let's look at an example: </strong> </li> ...
... <li> <strong>Unclosed attributes: Another common source of HTML problems. Let's look at an example: </strong> </li> HTML validation So you can see from the above example that you really want to make sure your HTML is well-formed! But how? In a small example like the one seen above, it is easy to search through the lines and find the errors, but what about a huge, complex HTML document? The best strategy is to start by running your HTML page through the Markup Validation Service -- created and maintained by the W3C, the organization that looks after the specifications that define HTML, CSS, and other web technologies. This webpage takes an HTML document as an input, goes through it, and gives you a report to tell you what is wrong with your HTML. To specify the HTML to vali...
... W3C, the organization that looks after the specifications that define HTML, CSS, and other web technologies. This webpage takes an HTML document as an input, goes through it, and gives you a report to tell you what is wrong with your HTML. To specify the HTML to validate, you can provide a web address, upload an HTML file, or directly input some HTML code. Active learning: Validating an HTML document Let's try this with our sample document. First, load the Markup Validation Service in one browser tab, if it isn't already open. Switch to the Validate by Direct Input tab. Copy all of the sample document's code (not just the body) and paste it into the large text area shown in the Markup Validation Service. Press the Check button. This should give you a list of errors and other informat...
...And 3 more matches
Handling common accessibility problems - Learn web development
xt way too small or hide it using CSS), but will also be usable by assistive technologies like screen readers (apps that literally read out a web page to their user), and confer other advantages too. Semantic structure The most important quick win in semantic HTML is to use a structure of headings and paragraphs for your content; this is because screen reader users tend to use the headings of a document as signposts to find the content they need more quickly. If your content has no headings, all they will get is a huge wall of text with no signposts to find anything. Examples of bad and good HTML: <font size="7">My heading</font> <br><br> This is the first section of my document. <br><br> I'll add another paragraph here too. <br><br> <font size="5">My subheading</font> <br><br> This is the firs...
...nd the content they need more quickly. If your content has no headings, all they will get is a huge wall of text with no signposts to find anything. Examples of bad and good HTML: <font size="7">My heading</font> <br><br> This is the first section of my document. <br><br> I'll add another paragraph here too. <br><br> <font size="5">My subheading</font> <br><br> This is the first subsection of my document. I'd love people to be able to find this content! <br><br> <font size="5">My 2nd subheading</font> <br><br> This is the second subsection of my content. I think it is more interesting than the last one. <h1>My heading</h1> <p>This is the first section of my document.</p> <p>I'll add another paragraph here too.</p> <h2>My subheading</h2> <p>This is the first subsection of my document. I'd lov...
...-div-buttons.html example (see source code). Here we've given our fake <div> buttons the ability to be focused (including via tab) by giving each one the attribute tabindex="0" (see WebAIM's tabindex article for more really useful details). This allows us to tab to the buttons, but not to activate them via the Enter/Return key. To do that, we had to add the following bit of JavaScript trickery: document.onkeydown = function(e) { if(e.keyCode === 13) { // The Enter/Return key document.activeElement.onclick(e); } }; Here we add a listener to the document object to detect when a button has been pressed on the keyboard. We check what button was pressed via the event object's keyCode property; if it is the keycode that matches Return/Enter, we run the function stored in the button's onclick...
...And 3 more matches
Accessibility Features in Firefox
antor Access Consulting Firefox includes keyboard access to all of its amazing features: Browse with caret allows users to select arbitrary content with the keyboard and move through content as if inside a read-only editor. This allows copying arbitrary pieces of text to the clipboard. The F7 key toggles this feature on/off. Tabbed browsing helps keyboard users by putting all of the browsed documents in one Firefox application window rather than cluttering the Alt+Tab order which makes keyboard navigation within the entire Windows OS much simpler. Both history and bookmarks can be searched with a "quick search" field that quickly narrows the list down via a substring search. Bookmarks can have a keyword assigned to them which can be typed into the address bar to bring up the bookmark. A "s...
...going to the search tool's web site. Custom searches can be added to this quick search bar and the user can switch between them by choosing from a drop down available via the standard Alt+down arrow key combination. The built-in text zoom feature can be accessed with the Ctrl+plus and Ctrl+minus hotkeys. The Accessibility Extension may be installed on top of Firefox, allowing keyboard access to document structure. The Find Bar allows for quick navigation to links and text searching without opening a separate dialog -- this allows more convenient use by screen magnification users because there is a single point of regard for the search. It also assists users of 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 ...
...ndows, 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 contrast, with large or sma...
...And 3 more matches
How Mozilla's build system works
For that, see the Build Documentation. ...
...For that, see the Build Documentation. ...
... for Mozilla developers who need to work on Mozilla's build system. The contents below will explain the basic concepts and terminology of the build system and how to do common tasks such as compiling components and creating jar files. For many developers, typing mach build to build the tree is sufficient to work with the source tree. This document explains how the build system works. Note: This document is not intended for developers who just want to build Mozilla. For that, see the Build Documentation. Phases When you type mach build to build the tree, three high-level phases occur within the build system: System detection and validation Preparation of the build backend Invocation of the build backend Phase 1: configure Phase 1 centers around the configure script. The configure script...
...And 3 more matches
Contributing to the Mozilla code base
and ask your questions in our chatroom, where we can help you get started. We know even before you start contributing that getting set up to work on Firefox and finding a bug that's a good fit for your skills can be a challenge. We're always looking for ways to improve this process: making Mozilla more open, accessible, and easier to participate with. ...
...is documentation, or hit a barrier you can't get around, please contact Mike Hoye at mhoye@mozilla.com. We're determined to solve hurdles for new contributors. What skills do I need? ...
...et around, please contact Mike Hoye at mhoye@mozilla.com. We're determined to solve hurdles for new contributors. What skills do I need? 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. ...
...And 3 more matches
Error codes returned by Mozilla APIs
_BASE_STREAM_BAD_CONVERSION (0x80470006) This error occurs when the component nsIStringBundleService has been set with a badly encoded property file. Try using UTF-8 encoding instead. See nsIStringBundle. NS_BASE_STREAM_WOULD_BLOCK (0x80470007) This error occurs when an attempt is made to read from a non blocking stream yet there is not enough data available to read without waiting for more. Document and Node Errors The following errors can occur when using documents, nodes and elements. NS_ERROR_DOM_INDEX_SIZE_ERR (0x80530001) An attempt was made to adjust the value of a text node using an index that was out of range. NS_ERROR_DOM_DOMSTRING_SIZE_ERR (0x80530002) An attempt was made to create a string larger than is supported. NS_ERROR_DOM_HIERARCHY_REQUEST_ERR (0x80530003) A node wa...
...An attempt was made to adjust the value of a text node using an index that was out of range. NS_ERROR_DOM_DOMSTRING_SIZE_ERR (0x80530002) An attempt was made to create a string larger than is supported. NS_ERROR_DOM_HIERARCHY_REQUEST_ERR (0x80530003) A node was inserted into a location where it cannot go. For instance, a node cannot be inserted into a descendant of itself. NS_ERROR_DOM_WRONG_DOCUMENT_ERR (0x80530004) An operation was performed on a document involving a node that was created in a different document. The document.importNode method may need to be used to import the node into the document first. NS_ERROR_DOM_INVALID_CHARACTER_ERR (0x80530005) An invalid character was used in a tag or attribute name. NS_ERROR_DOM_NO_DATA_ALLOWED_ERR (0x80530006) NS_ERROR_DOM_NO_MODIFICATIO...
... NS_ERRO...
...And 3 more matches
IME handling guide
Introduction IME is an abbreviation of Input Method Editor. This is a technical term from Windows but these days, this is used on other platforms as well. IME is a helper application of a user's text input. It handles native key events before or after focused application (depending on the platform) and creates a composition string (a.k.a. preedit string), suggests a list of what the user attempts to input, commits composition string as a selected item off the list and commits composition string without any conversion. IME is used by Chinese, Japanese, Korean and Taiwan users for inputting Chinese characters because the number of them is beyond thousands and cannot be input from the keyboard directly. ...
...ments, we call that state "enabled". If IME is not fully available(i.e., user cannot enable IME), we call this state "disabled". If IME is enabled but users use direct input mode (e.g., for inputting Latin characters), we call it "IME is closed". Otherwise, we call it "IME is open". (FYI: "open" is also called "active" or "turned on". "closed" is also called "inactive" or "turned off") So, this document is useful when you're try to fix a bug for text input in Gecko. Composition string and clauses Typical Japanese IME can input two or more words into a composition string. When a user converts from Hiragana characters to Chinese characters the composition string, Japanese IME separates the composition string into multiple clauses. For example, if a user types "watasinonamaehanakanodesu", it's co...
...Then, it sends the events and the event target to IMEStateManager. mozilla::IMEStateManager IMEStateManager looks for a TextComposition instance whose native IME context is same as the widget' which dispatches the widget event. If there is no proper TextComposition instance, it creates the instance. And it sends the event to the TextComposition instance. Note that all instances of...
...And 3 more matches
NSS_3.12.1_release_notes.html
NSS 3.12.1 Release Notes 2008-09-05 Newsgroup: mozilla.dev.tech.crypto Contents Introduction Distribution Information New in NSS 3.12.1 Bugs Fixed Documentation Compatibility Feedback Introduction Network Security Services (NSS) 3.12.1 is a patch release for NSS 3.12. The bug fixes in NSS 3.12.1 are described in the "Bugs Fixed" section below. NSS 3.12.1 is tri-licensed under the MPL 1.1/GPL 2.0/LGPL 2.1. Distribution Information The CVS tag for the NSS 3.12.1 release is NSS_3_12_1_RTM. NSS 3.12.1 requires NSPR 4.7.1. See the Documentation section for the build instructions. NSS 3.12.1 source and binary distributions are also available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/r...
...NVERTIBLE (maximum invertibility) Bugs Fixed The following bugs have been fixed in NSS 3.12.1. Bug 67890: create self-signed cert with existing key that signed CSR Bug 129303: NSS needs to expose interfaces to deal with multiple token sources of certs. ...
... Bug 417399: Arena Allocation results are not checked in pkix_pl_InfoAccess_ParseLocation Bug 420644: Improve SSL tracing of key derivation Bug 426886: Use const char* in PK11_ImportCertForKey Bug 428103: CERT_EncodeSubjectKeyID is not defined in any public header file Bug 429716: debug builds of libPKIX unconditionally dump socket traffic to stdout Bug 430368: vfychain -t option is undocumented Bug 430369: vfychain -o succeeds even if -pp is not specified Bug 430399: vfychain -pp crashes Bug 430405: Error log is not produced by CERT_PKIXVerifyCert Bug 430743: Update ssltap to understand the TLS session ticket extension Bug 430859: PKIX: Policy mapping fails verification with error invalid arguments Bug 430875: Document the policy for the order of cipher suites in SSL_Imple...
...And 3 more matches
Observer Notifications
browser-lastwindow-close-granted Sent when all interested parties have responded to the browser-lastwindow-close-requested notification and none of them requested that the close be aborted. After this is sent and handled, the browser window will close. browser-delayed-startup-finished Sent when the browser window and all its components have been loaded and initialized. Documents These topics indicate notifications you can monitor related to DOM documents. Topic Subject Data Description chrome-document-global-created nsIDOMWindow null Sent immediately after a chrome document window has been set up, but before any script code has been executed. This lets extensions inject API into chrome windows as needed (see nsIDOMGlobalPropertyInit...
...This lets extensions inject API into content windows as needed (see nsIDOMGlobalPropertyInitializer for an alternative method of doing this). ...
...ument window has been set up, but before any script code has been executed. This lets extensions inject API into chrome windows as needed (see nsIDOMGlobalPropertyInitializer for an alternative method of doing this, which uses significantly less memory). data is intentionally left blank. content-document-global-created nsIDOMWindow origin Sent immediately after a web content document window has been set up, but before any script code has been executed. ...
...And 3 more matches
nsISHistory
Whe...
... boolean modifyIndex); void PurgeHistory(in long numEntries); void reloadCurrentEntry(); void removeSHistoryListener(in nsISHistoryListener aListener); Attributes Attribute Type Description count long The number of toplevel documents currently available in session history. Read only. index long The index of the current document in session history. Read only. maxLength long Used to Get/Set the maximum number of toplevel documents, session history can hold for each instance. requestedIndex long The index of the last document that started to load that is not yet finished loading. When the document finishes loading the value -1 is returned. Read only. SHistoryEnumerator nsISimpleEn...
...The enumerator object thus returned by this method can be traversed using nsISimpleEnumerator. To access individual history entries of the enumerator, perform the following steps: Call GetSHistoryEnumerator() to obtain handle the nsISimpleEnumerator object. ...
...And 3 more matches
XUL Overlays
Mozilla › Tech › XUL › Overlays
n added as a result of an update or enhancement of some kind, they can be used in many different ways. Overlays provide a general mechanism for: Adding UI for additional components, as described in the example above Overriding small pieces of a XUL file without having to resupply the whole UI Reusing particular pieces of the UI XUL files and overlays work together to describe a single master document. Though there is no formal restriction on what kind of XUL content is located in "base" XUL files and what kind should be put in overlays, XUL overlays generally define items that are not present in the basic versions of the UI, such as additional components. When plug-ins, browser extensions, or other applications provide new UI elements to the browser, these elements should be defined in overla...
...itly, it means that you intend to make it available every time the base file is loaded. Since one of the main purposes of overlays is to provide UI for additions or components to the basic package, explicit loading can be somewhat problematic when the overlay defines optional UI elements. Loading overlays explicitly A processing instruction is used to load overlay files explicitly into the master document. Inserting the following processing instruction before the DOCTYPE declaration in a base file tells the layout engine to load the named overlay file: <?xul-overlay href="chrome://component/content/componentOverlay.xul"?> where component is the name of the package being overlayed (e.g., chrome://navigator/content/navigatorOverlay.xul). The layout engine loads any overlay files and then flows the r...
...he following processing instruction before the DOCTYPE declaration in a base file tells the layout engine to load the named overlay file: <?xul-overlay href="chrome://component/content/componentOverlay.xul"?> where component is the name of the package being overlayed (e.g., chrome://navigator/content/navigatorOverlay.xul). The layout engine loads any overlay files and then flows the resulting XUL document, so problems associated with incremental insertion in menus, boxes, tables, and forms are avoided. Any number of overlays can be loaded into a master document, and an overlay can also load other overlays. Because an overlay is superimposed on the master document, there are no ambiguities relating to scoping of style sheets or scripts. Style sheets and scripts loaded by the overlay simply apply to...
...And 3 more matches
Plug-in Basics - Plugins
he following example uses JavaScript to determine whether the Adobe Flash plug-in is installed. If it is, a movie is displayed. ...
... Understanding the Plug-in API Plug-ins and Platform Independence Understanding the plug-in API A plug-in i...
...lay with a plug-in? var plugin = mimetype.enabledPlugin; if (plugin) { // Yes, so show the data in-line document.writeln("Here\'s a movie: <object data='mymovie.swf' height='100' width='100'></object>"); } else { // No, so provide a link to the data document.writeln("<a href='mymovie.swf'>Click here</a> to see a movie."); } } else { // No, so tell them so document.writeln("Sorry, can't show you this movie."); } Overview of plug-in structure This section is an overview of basic information you will need as you develop plug-ins. Understanding the Plug-in API Plug-ins and Platform Independence Understanding the plug-in API A plug-in is a native code library whose source conforms to standard C syntax. The Plug-in Application Programming Interface (AP...
...And 3 more matches
Web Console remoting - Firefox Developer Tools
Introduction This document describes the way Web Console remoting works. The Web Console is split between a client with its user interface, and the server which has listeners for all the things that happen in the tab. For communication between the server and the client we use the Remote Debugging Protocol. This architecture allows you to connect a Web Console client instance to a server running on B2G, Fennec or some other Firefox instance. To better understand the architecture of the Web Console we recommend learning about the debugger architecture. The remote Web Console is a feature introduced in Firefox 18. This document describes the latest protocol, with changes that have been made since then. The WebConsoleActor and the WebConsoleClient The WebConsoleActor lives in dbg-webcon...
...allows one to retrieve the cached messages from before the Web Console was open. You can only get cached messages for page errors and console API calls. The reply looks like this: { "messages": [ ... ], "from": "conn0.console9" } Each message in the array is of the same type as when we send typical page errors and console API calls. These will be explained in the following sections of this document. Actor preferences To allow the Web Console to configure logging options while it is running, we have added the setPreferences packet: { "to": "conn0.console9", "type": "setPreferences", "preferences": { "NetworkMonitor.saveRequestAndResponseBodies": false } } Reply: { "updated": [ "NetworkMonitor.saveRequestAndResponseBodies" ], "from": "conn0.console10" } For conve...
...le event object received from the observer service. To see these differences please look in the Console API implementation: dom/base/ConsoleAPI.js. JavaScript evaluation The evaluateJS request and response packets The Web Console client provides the evaluateJS(requestId, string, onResponse) method which sends the following packet: { "to": "conn0.console9", "type": "evaluateJS", "text": "document", "bindObjectActor": null, "frameActor": null, "url": null, "selectedNodeActor": null, } The bindObjectActor property is an optional ObjectActor ID that points to a Debugger.Object. This option allows you to bind _self to the Debugger.Object of the given object actor, during string evaluation. See evalInGlobalWithBindings() for information about bindings. The variable view needs to up...
...And 3 more matches
Attr - Web APIs
Web › API › Attr
A DOMString representing the namespace prefix of the attribute, or null if no prefix is specified. ownerElement Read only The element holding the attribute. Note: DOM Level 4 removed this property. The assumption was that since you get an Attr object from an Element, you should already know the associated element. As that doesn't hold true in cases like Attr objects being returned by Document.evaluate, the DOM Living Standard reintroduced the property. Gecko outputs a deprecation note starting from Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4). This note was removed again in Gecko 49.0 (Firefox 49.0 / Thunderbird 49.0 / SeaMonkey 2.46). specified Read only This property always returns true. Originally, it returned true if the attribute was explicitly specified in ...
... starting from Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4). This note was removed again in Gecko 49.0 (Firefox 49.0 / Thunderbird 49.0 / SeaMonkey 2.46). specified Read only This property always returns true. Originally, it returned true if the attribute was explicitly specified in the source code or by a script, and false if its value came from the default one defined in the document's DTD. value The attribute's value. Note: DOM Level 3 defined namespaceURI, localName and prefix on the Node interface. In DOM4 they were moved to Attr. This change is implemented in Chrome since version 46.0 and Firefox since version 48.0. Deprecated properties and methods The following properties have been deprecated. Where available, the appropriate replacement is noted. attributes...
...replacement is noted. attributes This property now always returns NULL. childNodes Obsolete since Gecko 14 This property now always returns an empty NodeList. firstChild Obsolete since Gecko 14 This property now always returns NULL. isId Read only Indicates whether the attribute is an "ID attribute". An "ID attribute" being an attribute which value is expected to be unique across a DOM Document. In HTML DOM, "id" is the only ID attribute, but XML documents could define others. Whether or not an attribute is unique is often determined by a DTD or other schema description. lastChild Obsolete since Gecko 14 This property now always returns NULL. nextSibling This property now always returns NULL. nodeName Use Attr.name instead. nodeType This property now always returns 2 (ATTRIBUTE_...
...And 3 more matches
CanvasRenderingContext2D.arcTo() - Web APIs
) 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. ...
...="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. ...
... 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" type="range" id="radius" min...
...And 3 more matches
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
eters 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. ...
...h 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. ...
...ample draws two buttons on a canvas. The drawFocusIfNeeded() method is used to draw a focus ring when appropriate. ...
...And 3 more matches
Advanced animations - Web APIs
advanced. Drawing a ball We are going to use a ball for our animation studies, so let's first draw that ball onto the canvas. The following code will set us up. <canvas id="canvas" width="600" height="300"></canvas> As usual, we need a drawing context first. To draw the ball, we will create a ball object which contains properties and a draw() method to paint it on the canvas. ...
...elp of the arc() method. Adding velocity Now that we have a ball, we are ready to add a basic animation like we have learned in the last chapter of this tutorial. Again, window.requestAnimationFrame() helps us to control the animation. The ball gets moving by adding a velocity vector to the position. For each frame, we also clear the canvas to remove old circles from prior frames. ...
...the draw method: if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } First demo Let's see how it looks in action so far. Move your mouse into the canvas to start the animation. ...
...And 3 more matches
Basic usage of canvas - Web APIs
e a different browser that supports canvas does not help users who can't read the canvas at all, for example. Providing a useful fallback text or sub DOM helps to make the canvas more accessible. Required </canvas> tag As a consequence of the way fallback is provided, unlike the <img> element, the <canvas> element requires the closing tag (</canvas>). If this tag is not present, the rest of the document would be considered the fallback content and wouldn't be displayed. If fallback content is not needed, a simple <canvas id="foo" ...></canvas> is fully compatible with all browsers that support canvas at all. The rendering context The <canvas> element creates a fixed-size drawing surface that exposes one or more rendering contexts, which are used to create and manipulate the content shown. In ...
...ally blank. To display something, a script first needs to access the rendering context and draw on it. The <canvas> element has a method called getContext(), used to obtain the rendering context and its drawing functions. getContext() takes one parameter, the type of context. For 2D graphics, such as those covered by this tutorial, you specify "2d" to get a CanvasRenderingContext2D. var canvas = document.getElementById('tutorial'); var ctx = canvas.getContext('2d'); The first line in the script retrieves the node in the DOM representing the <canvas> element by calling the document.getElementById() method. Once you have the element node, you can access the drawing context using its getContext() method. Checking for support The fallback content is displayed in browsers which do not support <ca...
...ById() method. Once you have the element node, you can access the drawing context using its getContext() method. Checking for support The fallback content is displayed in browsers which do not support <canvas>. Scripts can also check for support programmatically by simply testing for the presence of the getContext() method. Our code snippet from above becomes something like this: var canvas = document.getElementById('tutorial'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); // drawing 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. <!DOCTYPE htm...
...And 3 more matches
Pixel manipulation with canvas - Web APIs
in the pixel array that getImageData() provides us. Finally, we use the array data to set a background color and a text in the <div> to display the color. ...
..."canvas" width="300" height="227" style="float:left"></canvas> <div id="color" style="width:200px;height:50px;float:left"></div> var img = new Image(); img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg'; var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); img.onload = function() { ctx.drawImage(img, 0, 0); img.style.display = 'none'; }; var color = document.getElementById('color'); function pick(event) { var x = event.layerX; var y = event.layerY; var pixel = ctx.getImageData(x, y, 1, 1); var data = pixel.data; var rgba = 'rgba(' + data[0] + ', ' + data[1] + ', ' + data[2] + ', ' + (data[3] / 255) + ')'; color.style.background = rgba; color.textContent = rgba; } canvas.addEventListener('mousemove', pick); Painting pix...
...e Grayscale on Wikipedia for more information. ...
...And 3 more matches
DOMImplementation - Web APIs
Such an object is returned by the Document.implementation property. Property This interface has no specific property and doesn't inherit any. Methods No inherited method. DOMImplementation.createDocument() Creates and returns an XMLDocument. DOMImplementation.createDocumentType() Creates and returns a DocumentType. DOMImplementation.createHTMLDocument() Creates and returns an HTML Document. DOMImplementation.hasFeature() Returns a Boolean indicating if a given feature is supported or not. ...
... DOMImplementation.hasFeature() Returns a Boolean indicating if a given feature is supported or not. This function is unreliable and kept for compatibility purpose alone: except for SVG-related queries, it always returns true. Old browsers are very inconsistent in their behavior. ...
... not. This function is unreliable and kept for compatibility purpose alone: except for SVG-related queries, it always returns true. Old browsers are very inconsistent in their behavior. Specifications Specification Status Comment DOMThe definition of 'DOMImplementation' in that specification. Living Standard Removed the getFeature() method. ...
...And 3 more matches
Element.attributes - Web APIs
of all attribute nodes registered to the specified node. It is a NamedNodeMap, not an Array, so it has no Array methods and the Attr nodes' indexes may differ among browsers. To be more specific, attributes is a key/value pair of strings that represents any information regarding that attribute. Syntax var attr = element.attributes; Example Basic examples // Get the first <p> element in the document var para = document.getElementsByTagName("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. <!DOCTYPE html> <html> <head> <title>Attributes example</t...
...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. ...
...ing 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. ...
...And 3 more matches
Element.classList - Web APIs
Web › API › Element › classList
st elementClasses = elementNodeReference.classList; Returns A DOMTokenList representing the contents of the element's class attribute. If the class attribute is not set or empty, it returns an empty DOMTokenList, i.e. a DOMTokenList with the length property equal to 0. The DOMTokenList itself is read-only, although you can modify it using the add() and remove() methods. ...
...nList': The token provided must not be empty." ); if((wsIndex=V.search(wsRE))!==-1) throw new DOMException("Failed to execute '"+O+"' on 'DOMTokenList': " + "The token provided ('"+V[wsIndex]+"') contains HTML space characters, which are not valid in tokens."); } // 2. ...
...provided must not be empty." ); if((wsIndex=V.search(wsRE))!==-1) throw new DOMException("Failed to execute '"+O+"' on 'DOMTokenList': " + "The token provided ('"+V[wsIndex]+"') contains HTML space characters, which are not valid in tokens."); } // 2. ...
...And 3 more matches
Element.computedStyleMap() - Web APIs
nd 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(). ...
... <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(). ...
...In other browsers you'll just s...
...And 3 more matches
Element.getBoundingClientRect() - Web APIs
ne of the viewport area (or any other scrollable element) is taken into account when computing the bounding rectangle. This means that the rectangle's boundary edges (top, right, bottom, left) change their values every time the scrolling position changes (because their values are relative to the viewport and not absolute). If you need the bounding rectangle relative to the top-left corner of the document, just add the current scrolling position to the top and left properties (these can be obtained using window.scrollX and window.scrollY) to get a bounding rectangle which is independent from the current scrolling position. Cross-browser fallback Scripts requiring high cross-browser compatibility can use window.pageXOffset and window.pageYOffset instead of window.scrollX and window.scrollY. Scrip...
...e obtained using window.scrollX and window.scrollY) to get a bounding rectangle which is independent from the current scrolling position. Cross-browser fallback Scripts requiring high cross-browser compatibility can use window.pageXOffset and window.pageYOffset instead of window.scrollX and window.scrollY. ...
...d using window.scrollX and window.scrollY) to get a bounding rectangle which is independent from the current scrolling position. Cross-browser fallback Scripts requiring high cross-browser compatibility can use window.pageXOffset and window.pageYOffset instead of window.scrollX and window.scrollY. ...
...And 3 more matches
Element.getClientRects() - Web APIs
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. ...
...idth is the same as the rectangle's width. Note: the overlays will be out of place if the user resizes or zooms. ...
... is the same as the rectangle's width. Note: the overlays will be out of place if the user resizes or zooms. ...
...And 3 more matches
Element.requestFullscreen() - Web APIs
that the element will be put into full screen mode. If permission to enter full screen mode is granted, the returned Promise will resolve and the element will receive a fullscreenchange event to let it know that it's now in full screen mode. If permission is denied, the promise is rejected and the element receives a fullscreenerror event instead. If the element has been detached from the original document, then the document receives these events instead. Earlier implementations of the Fullscreen API would always send these events to the document rather than the element, and you may need to be able to handle that situation. Check Browser compatibility in fullscreen for specifics on when each browser made this change. Note: This method must be called while responding to a user interaction or a de...
...th a value of undefined when the transition to full screen is complete. Exceptions Rather than throw a traditional exception, the requestFullscreen() procedure announces error conditions by rejecting the Promise it has returned. The rejection handler receives one of the following exception values: TypeError The TypeError exception may be delivered in any of the following situations: The document containing the element isn't fully active; that is, it's not the current active document. The element is not contained by a document. The element is not permitted to use the "fullscreen" feature, either because of Feature Policy configuration or other access control features. The element and its document are the same node. Usage notes Compatible elements An element that you wish to ...
... Additionally, of course, the Feature Policy "fullscreen" permission must be granted. ...
...And 3 more matches
Event.preventDefault() - Web APIs
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. ...
...d 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. ...
...="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. ...
...And 3 more matches
Event.type - Web APIs
Web › API › Event › type
. 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. ...
...ue 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. ...
...logs the event type whenever you press a keyboard key or click a mouse button. ...
...And 3 more matches
Introduction to the File and Directory Entries API - Web APIs
read, write, and create files and directories in a sandboxed, virtual file system. The File and Directory Entries API interacts with other related APIs. It was built on the File Writer API, which, in turn, was built on File API. Each of the APIs adds different functionality. These APIs are a giant evolutionary leap for web apps, which can now cache and process large amounts of data. ...
... The specification is still being defined and is subject to change. Overview The File and Directory Entries API includes both asynchronous and synchronous versions of the interfaces. ...
...nt storage for data that you want your app to keep--such as user-generated or unique data. Browsers impose storage quotas To prevent a web app from using up the entire disk, browsers might impose a quota for each app and allocate storage among web apps. How storage space is granted or allocated and how you can manage storage are idiosyncratic to the browser, so you need to check the respective documentation of the browser. Google Chrome, for example, allows temporary storage beyond the 5 MB required in the specifications and supports the Quota Management API. To learn more about the Chrome-specific implementation, see Managing HTML5 Offline Storage. The File and Directory Entries API has asynchronous and synchronous versions The File and Directory Entries API comes with asynchronous and synch...
...And 3 more matches
HTMLImageElement - Web APIs
middle">HTMLImageElement</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Constructor Image() The Image() constructor creates and returns a new HTMLImageElement object representing an HTML <img> element which is not attached to any DOM tree. It accepts optional width and height parameters. When called without parameters, new Image() is equivalent to calling document.createElement("img"). Properties Inherits properties from its parent, HTMLElement. HTMLImageElement.alt A DOMString that reflects the alt HTML attribute, thus indicating the alternate fallback content to be displayed if the image has not been loaded. HTMLImageElement.complete Read only Returns a Boolean that is true if the browser has finished fetching the image, whether successful or n...
... part of a server-side image map. This is different from a client-side image map, specified using an <img> element and a corresponding <map> which contains <area> elements indicating the clickable areas in the image. The image must be contained within an <a> element; see the ismap page for details. HTMLImageElement.loading A DOMString providing a hint to the browser used to optimize loading the document by determining whether to load the image immediately (eager) or on an as-needed basis (lazy). HTMLImageElement.naturalHeight Read only Returns an integer value representing the intrinsic height of the image in CSS pixels, if it is available; else, it shows 0. This is the height the image would be if it were rendered at its natural full size. HTMLImageElement.naturalWidth Read only An intege...
...which tells the user agent how to decide which referrer to use in order to fetch the image. Read this article for details on the possible values of this string. HTMLImageElement.sizes A DOMString reflecting the sizes HTML attribute. This string specifies a list of comma-separated conditional sizes for the image; that is, for a given viewport size, a particular image size is to be used. Read the documentation on the sizes page for details on the format of this string. HTMLImageElement.src A USVString that reflects the src HTML attribute, which contains the full URL of the image including base URI. You can load a different image into the element by changing the URL in the src attribute. HTMLImageElement.srcset A USVString reflecting the srcset HTML attribute. This specifies a list of candidate...
...And 3 more matches
Drag Operations - Web APIs
The draggable Attribute In a web page, there are certain cases where a default drag behavior is used. These include text selections, images, and links. When an image or link is dragged, the URL of the image or link is set as the drag data, and a drag begins. For other elements, they must be part of a selection for a default drag to occur. ...
...ut it can also be to a <canvas> or any other element. The feedback image will be generated from whatever the image looks like on screen, although for images, they will be drawn at their original size. The second and third arguments to the setDragImage() method are offsets where the image should appear relative to the mouse pointer. It is also possible to use images and canvases that are not in a document. ...
...t their original size. The second and third arguments to the setDragImage() method are offsets where the image should appear relative to the mouse pointer. It is also possible to use images and canvases that are not in a document. This technique is useful when drawing custom drag images using the canvas element, as in the following example: function dragWithCustomImage(event) { const canvas = document.createElement("canvas"); canvas.width = canvas.height = 50; const ctx = canvas.getContext("2d"); ctx.lineWidth = 4; ctx.moveTo(0, 0); ctx.lineTo(50, 50); ctx.moveTo(0, 50); ctx.lineTo(50, 0); ctx.stroke(); const dt = event.dataTransfer; dt.setData('text/plain', 'Data to Drag'); dt.setDragImage(canvas, 25, 25); } In this example, we make one canvas the drag image. As the ...
...And 3 more matches
MediaDevices.ondevicechange - Web APIs
:left; width: 48%; margin-right: 2% } .right { float:right; width: 48%; margin-left: 2% } .deviceList { border: 1px solid black; list-style-type: none; margin-top: 2px; padding: 6px; } JavaScript content Other code Below is other code which, while needed to make this example work, isn'tt related directly to ondevicechange, so we won't go into any detail. ...
... float:right; width: 48%; margin-left: 2% } .deviceList { border: 1px solid black; list-style-type: none; margin-top: 2px; padding: 6px; } JavaScript content Other code Below is other code which, while needed to make this example work, isn'tt related directly to ondevicechange, so we won't go into any detail. ...
...st-style-type: none; margin-top: 2px; padding: 6px; } JavaScript content Other code Below is other code which, while needed to make this example work, isn'tt related directly to ondevicechange, so we won't go into any detail. ...
...And 3 more matches
Using the Media Capabilities API - Web APIs
>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], bitrate: document.getElementById('bitrate').value, framerate: document.getElementById('framerate').value, } } }, testit: function () { let content =...
...' IS ' : 'IS NOT ') + ' supported, ' + (result.smooth ? ...
...onfiguration.video; content = 'A ' + mcv.width + 'x' + mcv.height + ', ' + mcv.contentType + ' at ' + mcv.framerate + 'fps and ' + mcv.bitrate + ' bps video ' + (result.supported ? ' IS ' : 'IS NOT ') + ' supported, ' + (result.smooth ? ' IS ' : ' is NOT ') + ' smooth, and' + (result.powerEfficient ? ...
...And 3 more matches
Node.appendChild() - Web APIs
Web › API › Node › appendChild
So if the node already has a parent, the node is first removed, then appended at the new position. The Node.cloneNode() method can be used to make a copy of the node before appending it under the new parent. ...
...So if the node already has a parent, the node is first removed, then appended at the new position. The Node.cloneNode() method can be used to make a copy of the node before appending it under the new parent. ...
...node). This means that a node can't be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position. The Node.cloneNode() method can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode will not be automatically kept in sync. If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node. Newer API avaliable! The ParentNode.append() method supports multiple arguments and appending strings. Syntax element.appendChild(aChild) Parameters aChild The node to append to the given parent node (commonly an element). Return value The returned value is the appended ch...
...And 3 more matches
Node.removeChild() - Web APIs
Web › API › Node › removeChild
not a child of this node. If the child doesn't exist on the DOM of the page, the method throws the following exception: Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'. ...
...oesn't exist on the DOM of the page, the method throws the following exception: Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'. ...
...t of type 'Node'. ...
...And 3 more matches
NodeList - Web APIs
Web › API › NodeList
NodeList objects are collections of nodes, usually returned by properties such as Node.childNodes and methods such as document.querySelectorAll(). Although NodeList is not an Array, it is possible to iterate over it with forEach(). It can also be converted to a real Array using Array.from(). However, some older browsers have not implemented NodeList.forEach() nor Array.from(). This can be circumvented by using Array.prototype.forEach() -- see this document's Example. Live vs. Static NodeLists Although they are both considered NodeLists, there are 2 varieties of NodeList: live and static. ...
...This can be circumvented by using Array.prototype.forEach() -- see this document's Example. Live vs. Static NodeLists Although they are both considered NodeLists, there are 2 varieties of NodeList: live and static. Live NodeLists In some cases, the NodeList is live, which means that changes in the DOM automatically update the collection. ...
...considered NodeLists, there are 2 varieties of NodeList: live and static. Live NodeLists In some cases, the NodeList is live, which means that changes in the DOM automatically update the collection. For example, Node.childNodes is live: const parent = document.getElementById('parent'); let child_nodes = parent.childNodes; console.log(child_nodes.length); // let's assume "2" parent.appendChild(document.createElement('div')); console.log(child_nodes.length); // outputs "3" Static NodeLists In other cases, the NodeList is static, where any changes in the DOM does not affect the content of the collection. The ubiquitous document.querySelectorAll() method returns a static NodeList. It's good to keep this distinction in mind when you choose how to iterate over the items in the NodeList, and whet...
...And 3 more matches
ParentNode.append() - Web APIs
Web › API › ParentNode › append
pend several nodes and strings, whereas Node.appendChild() can only append one node. Syntax // [Throws, Unscopable] ParentNode.append(...nodesOrDOMStrings) // returns undefined Parameters nodes A set of Node or DOMString objects to insert. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...s Node.appendChild() can only append one node. Syntax // [Throws, Unscopable] ParentNode.append(...nodesOrDOMStrings) // returns undefined Parameters nodes A set of Node or DOMString objects to insert. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...rns undefined Parameters nodes A set of Node or DOMString objects to insert. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...And 3 more matches
PerformanceNavigationTiming - Web APIs
The PerformanceNavigationTiming interface provides methods and properties to store and retrieve metrics regarding the browser's document navigation events. For example, this interface can be used to determine how much time it takes to load or unload a document. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/PerformanceEntry" target="_top"><rect x="1" y="1" width="160" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="81" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,mono...
...ne="middle">PerformanceNavigationTiming</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties This interface extends the following PerformanceEntry properties for navigation performance entry types by qualifying and constraining them as follows: PerformanceEntry.entryType Read only Returns "navigation". PerformanceEntry.name Read only Returns the document's address. PerformanceEntry.startTime Read only Returns a DOMHighResTimeStamp with a value of "0". PerformanceEntry.duration Read only Returns a timestamp that is the difference between the PerformanceNavigationTiming.loadEventEnd and PerformanceEntry.startTime properties. This interface also extends following PerformanceResourceTiming properties for navigation performance entry types by ...
... properties for navigation performance entry types by qualifying and constraining them as follows: PerformanceResourceTiming.initiatorTypeRead only Returns "navigation". The interface also supports the following properties: PerformanceNavigationTiming.domComplete Read only A DOMHighResTimeStamp representing a time value equal to the time immediately before the browser sets the current document readiness of the current document to complete. PerformanceNavigationTiming.domContentLoadedEventEnd Read only A DOMHighResTimeStamp representing the time value equal to the time immediately after the current document's DOMContentLoaded event completes. PerformanceNavigationTiming.domContentLoadedEventStart Read only A DOMHighResTimeStamp representing the time value equal to the time immedia...
...And 3 more matches
Range.selectNodeContents() - Web APIs
ge to contain the contents of a Node. The parent Node of the start and end of the Range will be the reference node. The startOffset is 0, and the endOffset is the number of child Nodes or number of characters contained in the reference node. Syntax range.selectNodeContents(referenceNode); Parameters referenceNode The Node whose contents will be selected within a Range. Example range = document.createRange(); referenceNode = document.getElementsByTagName("div")[0]; range.selectNodeContents(referenceNode); Live sample This example lets the user select and deselect a paragraph with buttons. Document.createRange(), Range.selectNodeContents(), and Selection.addRange() are used to select the content. Window.getSelection() and Selection.removeAllRanges() are used to deselect it. HTML <p ...
...nge.selectNodeContents(), and Selection.addRange() are used to select the content. Window.getSelection() and Selection.removeAllRanges() are used to deselect it. ...
...are used to select the content. Window.getSelection() and Selection.removeAllRanges() are used to deselect it. ...
...And 3 more matches
Using the Screen Capture API - Web APIs
pass into getDisplayMedia(); here, the cursor property is set to always, indicating that the mouse cursor should always be included in the captured media. Note: Some properties are not widely implemented and might not be used by the engine. cursor, for example, has limited support. Finally, event listeners are established to detect user clicks on the start and stop buttons. ...
...erty is set to always, indicating that the mouse cursor should always be included in the captured media. Note: Some properties are not widely implemented and might not be used by the engine. cursor, for example, has limited support. Finally, event listeners are established to detect user clicks on the start and stop buttons. ...
...ursor should always be included in the captured media. Note: Some properties are not widely implemented and might not be used by the engine. cursor, for example, has limited support. Finally, event listeners are established to detect user clicks on the start and stop buttons. ...
...And 3 more matches
ShadowRoot - Web APIs
You can retrieve a reference to an element's shadow root using its Element.shadowRoot property, provided it was created using Element.attachShadow() with the mode option set to open. Properties ShadowRoot.delegatesFocus Read only Returns a boolean that indicates whether delegatesFocus was set when the shadow was attached (see Element.attachShadow()). ShadowRoot.host Read only Returns a reference to the DOM element the ShadowRoot is attached to. ...
...)). 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. ...
...ed 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. ...
...And 3 more matches
Writing WebSocket client applications - Web APIs
JSON to send reasonably complex data to the server. For example, a chat program can interact with a server using a protocol implemented using packets of JSON-encapsulated data: // Send text to all users through the server function sendText() { // Construct a msg object containing the data the server needs to process the message from the chat client. ...
...ontaining the data the server needs to process the message from the chat client. var msg = { type: "message", text: document.getElementById("text").value, id: clientID, date: Date.now() }; // Send the msg object as a JSON-formatted string. exampleSocket.send(JSON.stringify(msg)); // Blank the text input element, ready to receive the next line of text from the user. document.getElementById("text").value = ""; } Receiving messages from the server WebSockets is an event-driven API; when messages are received, a message event is sent to the WebSocket object. To handle it, add an event listener for the message event, or use the onmessage event handler. To begin listening for incoming data, you can do something like this: exampleSocket.onmessage = function (event) { ...
...a); } Receiving and interpreting JSON objects Let's consider the chat client application first alluded to in Using JSON to transmit objects. ...
...And 3 more matches
Using the Web Storage API - Web APIs
cts, which the localStorage and sessionStorage properties are members of) -- invoking one of these will create an instance of the Storage object, through which data items can be set, retrieved, and removed. A different Storage object is used for the sessionStorage and localStorage for each origin -- they function and are controlled separately. So, for example, initially calling localStorage on a document will return a Storage object; calling sessionStorage on a document will return a different Storage object. Both of these can be manipulated in the same way, but separately. Feature-detecting localStorage To be able to use localStorage, we should first verify that it is supported and available in the current browsing session. Testing for availability Note: This API is available in current ver...
...s empty or not. Getting values from storage As noted above, values can be retrieved from storage using Storage.getItem(). This takes the key of the data item as an argument, and returns the data value. For example: function setStyles() { var currentColor = localStorage.getItem('bgcolor'); var currentFont = localStorage.getItem('font'); var currentImage = localStorage.getItem('image'); document.getElementById('bgcolor').value = currentColor; document.getElementById('font').value = currentFont; document.getElementById('image').value = currentImage; htmlElem.style.backgroundColor = '#' + currentColor; pElem.style.fontFamily = currentFont; imgElem.setAttribute('src', currentImage); } Here, the first three lines grab the values from local storage. Next, we set the values display...
...es/decorative image on the page, so your customization options come up again on reload. Setting values in storage Storage.setItem() is used both to create new data items, and (if the data item already exists) update existing values. This takes two arguments -- the key of the data item to create/modify, and the value to store in it. function populateStorage() { localStorage.setItem('bgcolor', document.getElementById('bgcolor').value); localStorage.setItem('font', document.getElementById('font').value); localStorage.setItem('image', document.getElementById('image').value); setStyles(); } The populateStorage() function sets three items in local storage -- the background color, font, and image path. It then runs the setStyles() function to update the page styles, etc. We've also included...
...And 3 more matches
Window.scrollY - Web APIs
Web › API › Window › scrollY
The read-only scrollY property of the Window interface returns the number of pixels that the document is currently scrolled vertically. This value is subpixel precise in modern browsers, meaning that it isn't necessarily a whole number. You can get the number of pixels the document is scrolled horizontally from the scrollX property. Syntax var y = window.scrollY Value In practice, the returned value is a double-precision floating-point value indicating the number of pixels the document is currently scrolled vertically from the origin, where a positive value means the content is scrolled to upward. ...
... If you need an integer value, you can use Math.round() to round it off. ...
... If you need an integer value, you can use Math.round() to round it off. In more technical terms, scrollY returns the Y coordinate of the top edge of the current viewport. ...
...And 3 more matches
HTML in XMLHttpRequest - Web APIs
XML parsing. This feature allows Web apps to obtain an HTML resource as a parsed DOM using XMLHttpRequest. To get an overview of how to use XMLHttpRequest in general, see Using XMLHttpRequest. Limitations To discourage the synchronous use of XMLHttpRequest, HTML support is not available in the synchronous mode. Also, HTML support is only available if the responseType property has been set to "document". This limitation avoids wasting time parsing HTML uselessly when legacy code uses XMLHttpRequest in the default mode to retrieve responseText for text/html resources. Also, this limitation avoids problems with legacy code that assumes that responseXML is null for HTTP error pages (which often have a text/html response body). Usage Retrieving an HTML resource as a DOM using XMLHttpRequest works...
...text/html resources. Also, this limitation avoids problems with legacy code that assumes that responseXML is null for HTTP error pages (which often have a text/html response body). ...
...mitation avoids problems with legacy code that assumes that responseXML is null for HTTP error pages (which often have a text/html response body). Usage Retrieving an HTML resource as a DOM using XMLHttpRequest works just like retrieving an XML resource as a DOM using XMLHttpRequest, except you can't use the synchronous mode and you have to explicitly request a document by assigning the string "document" to the responseType property of the XMLHttpRequest object after calling open() but before calling send(). var xhr = new XMLHttpRequest(); xhr.onload = function() { console.log(this.responseXML.title); } xhr.open("GET", "file.html"); xhr.responseType = "document"; xhr.send(); Feature detection Method 1 This method relies on the "force async" nature of the feature. When you try to set respo...
...And 3 more matches
XPathResult.resultType - Web APIs
STRING_TYPE 2 A result containing a single string. BOOLEAN_TYPE 3 A result containing a single boolean value. This is useful for example, in an XPath expression using the not() function. UNORDERED_NODE_ITERATOR_TYPE 4 A result node-set containing all the nodes matching the expression. The nodes may not necessarily be in the same order that they appear in the document. ORDERED_NODE_ITERATOR_TYPE 5 A result node-set containing all the nodes matching the expression. The nodes in the result set are in the same order that they appear in the document. UNORDERED_NODE_SNAPSHOT_TYPE 6 A result node-set containing snapshots of all the nodes matching the expression. The nodes may not necessarily be in the same order that they appear in the ...
.... ORDERED_NODE_ITERATOR_TYPE 5 A result node-set containing all the nodes matching the expression. The nodes in the result set are in the same order that they appear in the document. UNORDERED_NODE_SNAPSHOT_TYPE 6 A result node-set containing snapshots of all the nodes matching the expression. The nodes may not necessarily be in the same order that they appear in the document. ORDERED_NODE_SNAPSHOT_TYPE 7 A result node-set containing snapshots of all the nodes matching the expression. The nodes in the result set are in the same order that they appear in the document. ...
...y appear in the document. ORDERED_NODE_SNAPSHOT_TYPE 7 A result node-set containing snapshots of all the nodes matching the expression. The nodes in the result set are in the same order that they appear in the document. ANY_UNORDERED_NODE_TYPE 8 A result node-set containing any single node that matches the expression. The node is not necessarily the first node in the document that matches the expression. FIRST_ORDERED_NODE_TYPE 9 A result node-set containing the first node in the document that matches the expression. Example The following example shows the use of the resultType property. ...
...And 3 more matches
XPathResult - Web APIs
erface makes it possible to determine and handle the type and value of the result. Properties XPathResult.booleanValueRead only A boolean representing the value of the result if resultType is BOOLEAN_TYPE. XPathResult.invalidIteratorStateRead only Signifies that the iterator has become invalid. It is true if resultType is UNORDERED_NODE_ITERATOR_TYPE or ORDERED_NODE_ITERATOR_TYPE and the document has been modified since this result was returned. XPathResult.numberValueRead only A number representing the value of the result if resultType is NUMBER_TYPE. XPathResult.resultTypeRead only A number code representing the type of the result, as defined by the type constants. XPathResult.singleNodeValueRead only A Node representing the value of the single node result, which may be null. ...
...thods XPathResult.iterateNext() If the result is a node set, this method iterates over it and returns the next node from it or null if there are no more nodes. XPathResult.snapshotItem() Returns an item of the snapshot collection or null in case the index is not within the range of nodes. Unlike the iterator result, the snapshot does not become invalid, but may not correspond to the current document if it is mutated. Constants Result Type Defined Constant Value Description ANY_TYPE 0 A result set containing whatever type naturally results from evaluation of the expression. Note that if the result is a node-set then UNORDERED_NODE_ITERATOR_TYPE is always the resulting type. NUMBER_TYPE 1 A result containing a single number. This is useful fo...
... STRING_TYPE 2 A result containing a single string. BOOLEAN_TYPE 3 A result containing a single boolean value. This is useful for example, in an XPath expression using the not() function. UNORDERED_NODE_ITERATOR_TYPE 4 A result node-set containing all the nodes matching the expression. The nodes may not necessarily be in the same order that they appear in the document. ORDERED_NODE_ITERATOR_TYPE 5 A result node-set containing all the nodes matching the expression. The nodes in the result set are in the same order that they appear in the document. UNORDERED_NODE_SNAPSHOT_TYPE 6 A result node-set containing snapshots of all the nodes matching the expression. The nodes may not necessarily be in the same order that they appear in the ...
...And 3 more matches
ARIA: grid role - Accessibility
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.row = row; el.dataset.co...
...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.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(newrow, newcol) { var tgt = document.querySelector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt && (tgt.getAttribute('role')==='gridcell') ) { Array.prototype.forEach.call(document.querySelectorAll('[role=gridcell]'), function(el, i){ el.setAttribute('tabindex', '-1'); }); tgt.setAttribute('tabindex', '0'); tgt.focus(); return true; } else { return false; } } document.queryS...
...target.dataset.row, 10), 0); } break; case "End": if (event.ctrlKey) { var i = maxrow; var result; do { var j = maxcol; do { result = moveto(i, j); j--; } while (result == false); i--; } while (result == false); } else { moveto(parseInt(event.target.dataset.row, 10), document.querySelector('[data-row="' + event.target.dataset.row + '"]:last-of-type').dataset.col); } break; case "PageUp": var i = 0; var result; do { result = moveto(i, event.target.dataset.col); i++; } while (result == false); break; case "PageDown": var i = maxrow; var result; do { result = moveto(i, event.targe...
...And 3 more matches
ARIA: Region role - Accessibility
It is used to provide a generic landmark for people to be able to navigate to easily when none of the other landmark roles are appropriate. <div role="region" aria-label="Example"> <!-- region content --> </div> Description The region role is an ARIA landmark role. Landmark roles provide a way to identify the organization and structure of a web page. By classifying and labeling sections of a page, structural information conveyed visually through layout is represented programmatically. Screen readers use landmark roles to provide keyboard navigation to important sections of a page. ...
...banner, main, contentinfo, complementary, or navigation. Every element with a region role should include a label that describes the purpose of the content in the region, preferably with an aria-labelledby referencing a visible header. If no visible appropriate header is present, aria-label should be used.. region landmark roles content should make sense if separated from the main content of the document. Using the <section> element will automatically communicate a section has a role of region if it is 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 attribu...
...teractions None. Required JavaScript features None. Examples <div role="region" aria-labelledby="region-heading"> <h2 id="region-heading">This heading's <code>id</code> attribute helps this region have an accessible name</h2> <!-- region content --> </div> Accessibility concerns Use sparingly! Landmark roles are intended to be used sparingly, to identify larger overall sections of the document. Using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. Only use the region role if no other relevant content sectioning element or landmark role applies. If multiple regions exist on a page, it may be worth reinvestigating the page's overall structure. Best practices Prefer HTML Using the <section> element will au...
...And 3 more matches
WAI-ARIA Roles - Accessibility
le indicates to assistive technologies that an element and all of its children should be treated similar to a desktop application, and no traditional HTML interpretation techniques should be used. This role should only be used to define very dynamic and desktop-like web applications.ARIA: article roleThe article role indicates a section of a page that could easily stand on its own on a page, in a document, or on a website. It is usually set on related content items such as comments, forum posts, newspaper articles or other items grouped together on one page.ARIA: banner roleA banner role represents general and informative content frequently placed at the beginning of the page. This usually includes a logo, company name, search icon, photo related to the page, or slogan.ARIA: button roleThe button ...
...role is used to mark up an HTML based application dialog or window that separates content or UI from the rest of the web application or page. Dialogs are generally placed on top of the rest of the page content using an overlay. ...
...tes content or UI from the rest of the web application or page. Dialogs are generally placed on top of the rest of the page content using an overlay. Dialogs can be either non-modal (it's still possible to interact with content outside of the dialog) or modal (only the content in the dialog can be interacted with).ARIA: document roleGenerally used in complex composite widgets or applications, the document role can inform assistive technologies to switch context to a reading mode: The document role tells assistive technologies with reading or browse modes to use the document mode to read the content contained within this element.ARIA: feed roleA feed is a dynamic scrollable list of articles in which articles are added to or removed from either end of the list as the user scrolls. A feed enables scr...
...And 3 more matches
Alerts - Accessibility
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 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). ...
... handler in JavaScript's default 'alert' function). ...
...And 3 more matches
CSS Animations tips and tricks - CSS: Cascading Style Sheets
However, there are things you might want to do that aren't obvious, or clever ways to do things that you might not come up with right away. This article is a collection of tips and tricks we've found that may make your work easier, including how to run a stopped animation again. Run an animation again The CSS Animations specification doesn't offer a way to run an animation again. There's no magic resetAnimation() method on elements, and you can't even just set the element's animation-play-state to "running" again. Instead, you have to use clever tricks to get a stopped animation to replay. ...
...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. ...
...s 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 changing"; }); }); } This looks weird, doesn't it? That's because the only way to play an animation again is to remove the animation effect, let the document recompute styles so that it knows you've done that, then add the animation effect back to the element. To make that happen, we have to be creative. Here's what happens when the play() function g...
...And 3 more matches
Audio and video manipulation - Developer guides
" width="480" height="270"></canvas> JavaScript This code handles altering the frames. ...
...his code handles altering the frames. ...
... 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. ...
...And 3 more matches
DOM onevent handlers - Developer guides
ressed 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 handler can then ...
... any data from the event object, you can leave out the event when calling onclick(). This continues until every handler has been called, unless one of the event handlers explicitly halts the processing of the event by calling stopPropagation() on the event object itself. Non-element objects Event handlers can also be set with properties on non-element objects that generate events, like window, document, XMLHttpRequest, and others. For example, for the progress event on instances of XMLHttpRequest: const xhr = 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. When the element is built from the HTML, the value of its onevent attributes...
...hen 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. ...
...And 3 more matches
Constraint validation - Developer guides
'^(F-)?\\d{5}$' , "France ZIPs must have exactly 5 digits: e.g. F-75012 or 75012" ], de : [ '^(D-)?\\d{5}$' , "Germany ZIPs must have exactly 5 digits: e.g. ...
...], de : [ '^(D-)?\\d{5}$' , "Germany ZIPs must have exactly 5 digits: e.g. ...
... Limiting the size of a file before its upload Another common constraint is to limit the size of a file to be uploaded. Checking this on the client side before the file is transmitted to the server requires combining the Constraint Val...
...And 3 more matches
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
s of a box's borders. background-color The background color to use in areas of the element that have no foreground content. column-rule-color The color to use when drawing the line separating columns of text. outline-color The color to use when drawing an outline around the outside of the element. This outline is different from the border in that it doesn't get space set aside for it in the document (so it may overlap other content). It's generally used as a focus indicator, to show which element will receive input events. Borders Any element can have a border drawn around it. A basic element border is a line drawn around the edges of the element's content. See Box properties in The box model to learn about the relationship between elements and their borders, and the article Styling borde...
... { 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. ...
...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. ...
...And 3 more matches
<main> - HTML: Hypertext Markup Language
Web › HTML › Element › main
Content categories Flow content, palpable content. Permitted content Flow content. ...
... Content categories Flow content, palpable content. Permitted content Flow content. ...
... Content categories Flow content, palpable content. Permitted content Flow content. Tag omission None; both the starting and ending tags are mandatory. ...
...And 3 more matches
<nextid>: The NeXT ID element (Obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › nextid
ould produce an entry in the Table of Contents like this: <A NAME="z0" HREF="#z4">FIRST SECTION NAME</A> and the section header would be marked like this: <H2><A NAME="z4">FIRST SECTION NAME</A></H2>. This continues for the next three sections, z5, z6, and z7 (and Table of Contents entries named z1, z2, and z3), each automatically given anchors with these names. The user then saves and closes the document. ...
...NAME="z0" HREF="#z4">FIRST SECTION NAME</A> and the section header would be marked like this: <H2><A NAME="z4">FIRST SECTION NAME</A></H2>. This continues for the next three sections, z5, z6, and z7 (and Table of Contents entries named z1, z2, and z3), each automatically given anchors with these names. The user then saves and closes the document. ...
...AME</A></H2>. This continues for the next three sections, z5, z6, and z7 (and Table of Contents entries named z1, z2, and z3), each automatically given anchors with these names. The user then saves and closes the document. NeXT would then add, within the header of the HTML document, a special tag, <NEXTID N="z8">, to inform where to continue its naming convention. Imagine the web author opens the document for further editing. They want to add a couple new sections after the second section, appending four more sections at the end. When opening the document, the NeXT editor finds and reads this <NEXTID N="z8"> tag, and now knows to give the first of these new sections the name of z8 in the Table of Contents, and z14 to the content body. This might look like this: <HTML> <HEAD> <TITLE> .
...And 3 more matches
<script>: The Script element - HTML: Hypertext Markup Language
Web › HTML › Element › script
minimal information to the window.onerror for scripts which do not pass the standard CORS checks. To allow error logging for sites which use a separate domain for static media, use this attribute. See CORS settings attributes for a more descriptive explanation of its valid arguments. defer This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded. Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded 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 def...
...vent the DOMContentLoaded event from firing until the script has loaded 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. nomodul...
...rigin of the referring page: its scheme, host, and port. origin-when-cross-origin: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path. same-origin: A referrer will be sent for same origin, but cross-origin requests will contain no referrer information. strict-origin: Only send the origin of the document as the referrer when the protocol security level stays the same (e.g. HTTPS->HTTPS), but don't send it to a less secure destination (e.g. HTTPS->HTTP). strict-origin-when-cross-origin: Send a full URL when performing a same-origin request, but only send the origin when the protocol security level stays the same (e.g.HTTPS->HTTPS), and send no header to a less secure destination (e.g. HTTPS->HTT...
...And 3 more matches
Evolution of HTTP - HTTP
esolution and 3D. Invention of the World Wide Web In 1989, while he was working at CERN, Tim Berners-Lee wrote a proposal to build a hypertext system over the Internet. Initially calling it the Mesh, it was later renamed to World Wide Web during its implementation in 1990. Built over the existing TCP and IP protocols, it consisted of 4 building blocks: A textual format to represent hypertext documents, the HyperText Markup Language (HTML). A simple protocol to exchange these documents, the HypertText Transfer Protocol (HTTP). A client to display (and accidentally edit) these documents, the first Web browser called WorldWideWeb. A server to give access to the document, an early version of httpd. These four building blocks were completed by the end of 1990, and the first servers were alrea...
...llowed by the path to the resource (not the URL as both the protocol, server, and port are unnecessary once connected to the server). GET /mypage.html The response is extremely simple too: it only consisted of the file itself. <HTML> A very simple HTML page </HTML> Unlike subsequent evolutions, there were no HTTP headers, meaning that only HTML files could be transmitted, but no other type of documents. There were no status or error codes: in case of a problem, a specific HTML file was send back with the description of the problem contained in it, for human consumption. HTTP/1.0 - Building extensibility HTTP/0.9 was very limited and both browsers and servers quickly extended it to be more versatile: Versioning information is now sent within each request (HTTP/1.0 is appended to the GET li...
...and the success or failure of the request and to adapt its behavior in consequence (like in updating or using its local cache in a specific way) The notion of HTTP headers has been introduced, both for the requests and the responses, allowing metadata to be transmitted and making the protocol extremely flexible and extensible. With the help of the new HTTP headers, the ability to transmit other documents than plain HTML files has been added (thanks to the Content-Type header). At this point, a typical request and response looked like this: GET /mypage.html HTTP/1.0 User-Agent: NCSA_Mosaic/2.0 (Windows 3.1) 200 OK Date: Tue, 15 Nov 1994 08:12:31 GMT Server: CERN/3.0 libwww/2.17 Content-Type: text/html <HTML> A page with an image <IMG SRC="/myimage.gif"> </HTML> Followed by a second connect...
...And 3 more matches
Content Security Policy (CSP) - HTTP
Web › HTTP › CSP
ts to allow users of a web application to include images from any origin in their own content, but to restrict audio or video media to trusted providers, and all scripts only to a specific server that hosts trusted code. Content-Security-Policy: default-src 'self'; img-src *; media-src media1.com media2.com; script-src userscripts.example.com Here, by default, content is only permitted from the document's origin, with the following exceptions: Images may load from anywhere (note the "*" wildcard). Media is only allowed from media1.com and media2.com (and not from subdomains of those sites). Executable script is only allowed from userscripts.example.com. Example 4 A web site administrator for an online banking site wants to ensure that all its content is loaded using TLS, in order to prev...
...and not from subdomains of those sites). Executable script is only allowed from userscripts.example.com. Example 4 A web site administrator for an online banking site wants to ensure that all its content is loaded using TLS, in order 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-s...
...example.com/collector.cgi Then you need to set up your server to receive the reports; it can store or process them in whatever manner you determine is appropriate. Violation report syntax The report JSON object contains the following data: blocked-uri The URI of the resource that was blocked from loading by the Content Security Policy. If the blocked URI is from a different origin than the document-uri, then the blocked URI is truncated to contain just the scheme, host, and port. disposition Either "enforce" or "report" depending on whether the Content-Security-Policy-Report-Only header or the Content-Security-Policy header is used. document-uri The URI of the document in which the violation occurred. effective-directive The directive whose enforcement caused the violation. origin...
...And 3 more matches
Namespaces crash course - SVG: Scalable Vector Graphics
cko-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. Background It has been a long standing goal of the W3C to make it possible for different types of XML based content to be mixed together in the same XML file. For example, SVG and MathML might be incorporated directly into an XHTML based scientific document. ...
...For example, both XHTML and SVG have a <title> element. ...
...t it is an XML error to use a prefix that hasn't been bound to a namespace name. The binding created by the xmlns:xlink parameter in the example above is absolutely essential for the xlink:href parameter to not cause an error. This XLink parameter is also frequently used in SVG on the <a>, <use> and <image> elements among others, so it's a good idea to always include the XLink declaration in your documents. As an aside, it's useful to know that namespace prefixes can also be used for element names. This tells the user agent that that particular element (but not its children this time!) belongs to the namespace assigned to the prefix. Knowing this will save you some confusion if you come across markup like in the following example: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http:...
...And 3 more matches
Rosetta - Archive of obsolete content
|*| This framework is released under the GNU Public License, version 3 or later. ...
... sMimeType = oScript.getAttribute("type").toLowerCase(), oBaton = document.createComment(" The previous code has been automatically translated from \"" + sMimeType + "\" to \"text/ecmascript\". ...
...oReq.onload = reqSuccess; oReq.onerror = reqError; oReq.refScript = oScript; oReq.open("GET", oScript.src, true); oReq.send(null); } function parseScript (oScript) { if (oScript.hasAttribute("type") && !rIgnoreMimes.test(oScript.getAttribute("type").toLowerCase())) { oScript.hasAttribute("src") ? ...
...And 2 more matches
Toolbar - Archive of obsolete content
ust not insert your toolbar button between any of the following elements: the combined back/forward button, the location bar, the stop botton, or the reload button. These elements have special behaviors when placed next to eachother, and will break if separated by another element. /** * Installs the toolbar button with the given ID into the given * toolbar, if it is not already present in the document. ...
... element. /** * Installs the toolbar button with the given ID into the given * toolbar, if it is not already present in the document. * * @param {string} toolbarId The ID of the toolbar to install to. * @param {string} id The ID of the button to install. * @param {string} afterId The ID of the element to insert after. ...
...he given ID into the given * toolbar, if it is not already present in the document. * * @param {string} toolbarId The ID of the toolbar to install to. * @param {string} id The ID of the button to install. * @param {string} afterId The ID of the element to insert after. ...
...And 2 more matches
Firefox addons developer guide - Archive of obsolete content
So there may be still some reference to the xuldev website (we want to host source code on MDC, not on xuldev), and to Japanese things (like some specific locales, which have been translated to French since non-latin characters are not well supported). ...
...nction names should have parentheses after them. For example, here: https://developer.mozilla.org/En/Firefox_addons_developer_guide/Let's_build_a_Firefox_extension#init_method The text of the paragraph should begin "The <code>init()</code> method is as shown...". If you use the Interface template when mentioning interfaces by name, MDC will automatically format them and generate links to their documentation, like this: nsIConsoleService. If you prefer, you can just link to the articles directly. Either way, these links should be added. These articles are all tagged as covering Firefox 3.1 using the fx_minversion_header template, but I don't think that's the case. Certainly Appendix 2 doesn't care what version of Firefox you're using, since it's just about open source software licenses. Tod...
...ce. If you prefer, you can just link to the articles directly. Either way, these links should be added. These articles are all tagged as covering Firefox 3.1 using the fx_minversion_header template, but I don't think that's the case. Certainly Appendix 2 doesn't care what version of Firefox you're using, since it's just about open source software licenses. ...
...And 2 more matches
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
thousands of pages; Simple markup allows for rapid changes to templates; Average page weight dropped by almost half; Page layout accomplished with simple CSS positioning; Vastly increased accessibility without special coding or user agent detection. Why did you pursue a standards-based redesign of Wired News? As Network Design Manager at Lycos for the last two years, I've been creating and documenting design standards for our network of sites. This includes rules and guidelines applying to everything from headers, footers, page hierarchy, titles, typography, iconography, navigation, and others. So I'm very familiar with standards and the benefits of using them. With the Wired News design process, the scenario was reversed. As I was designing the product, I began discovering a broader set of...
...ired News design eliminated the majority of our tables, but left one master table to control the primary columns of each page. That approach meant that the content of every column would have to be loaded and calculated before it would be rendered in the browser window. That wasn't good enough. Around that time, I started discovering great sites like glish.com and bluerobot.com. Both presented and documented viable means of producing multi-column layouts without a single table. Despite some initial setbacks with those approaches due to our own unique scenarios, it wasn't long before I discovered a variation of one of their methods that worked for the Wired News design. By eliminating tables that were strictly used for layout, we significantly cut back on the amount of markup and useless tags in ou...
...atter of taking into account several considerations. Are you tired of the maintenance headaches caused by the glut of extra tables and presentation tags in your markup? Can you see an advantage to reducing file size and speeding up download time? Do you have the resources to invest in making some significant changes up front which can save time and money in the long run? Is it important that your documents be backward-compatible with older or specialized browsing environments? And forward-compatible with browser applications of the future? Are you comfortable with the idea that your documents may not look exactly the same in every browser? If the answer to one or more of those questions is "yes," chances are, you could be ripe to make the leap. Keep in mind the last disadvantage I just mentioned.
...And 2 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
Its original inspiration comes from http://www.alain.knaff.lu/howto/MozillaCustomization/ and http://mit.edu/~firefox/www/maintain...utoconfig.html. For history, I've kept Mozilla and Netscape chapters, as certain points are complementary to the web-based AutoConfig file. This MCD (aka autoconfig here), is not to be confused with https://wiki.mozilla.org/Thunderbird...oconfiguration . ...
...d) $ rpm -qi firefox Name : firefox Relocations: (not relocatable) Version : 2.0.0.2 Vendor: Remi Collet Release : 1.fc6.remi Build Date: Sat 24 Feb 2007 01:45:37 PM CET Install Date: Tue 20 Mar 2007 02:47:27 PM CET Build Host: remi.famillecollet.com Packager : http://remi.collet.free.fr/ References Other Documents About AutoConfig http://mit.edu/~firefox/www/maintain...utoconfig.html http://www.alain.knaff.lu/howto/Mozi...ion/index.html http://thegoldenear.org/toolbox/wind...re-config.html http://ilias.ca/blog/2005/03/locking...efox-settings/ Compile on Windows: http://forums.mozillazine.org/viewtopic.php?t=276014 http://www.mozilla.org/community/dev...er-forums.html http://forums.mozillazine.org/...
...nix (export MOZILLA_DEBUG=1) or in the command.com environment in Windows (set MOZILLA_DEBUG=1). Blank Space Bug I noticed a problem which is due to be corrected in Mozilla 1.8 I think... Here's the report and workaround: bug 229271. To fix, add the following: start_pos += search_key.length; //start start_pos +=1; //end to function getLDAPValue() in autoconfig/preffcalls.js. ...
...And 2 more matches
Notes on HTML Reflow - Archive of obsolete content
t, with continuing frames (or continuations ) created for subsequent lines. HTML uses a flow based layout model, meaning that most of the time it is possible to compute the geometry in a single pass. Elements later "in the flow" typically do not affect the geometry of elements that are earlier "in the flow", so layout can proceed left-to-right, top-to-bottom through the document. There are exceptions to this rule: most notably, HTML tables may require more than one pass. The XUL box layout model, on the other hand, is constraint based , meaning that geometric preferences and constraints of neighboring elements are taken into consideration before the elements' final geometry can be computed. The box is the geometric primitive for the XUL layout model. Al...
... constraint based , meaning that geometric preferences and constraints of neighboring elements are taken into consideration before the elements' final geometry can be computed. The box is the geometric primitive for the XUL layout model. All HTML reflow, including the initial reflow , begins at the root frame , which corresponds to the <html> element of the HTML document. Reflow proceeds recursively through some or all of the frame hierarchy, computing geometric information for each frame object that requires it. Reflow may have the side-effect of creating new continuation frames, for example, for a text frame when the text must be wrapped. Some reflows are immediate in response to user or script actions; for example, resizing the window or changing the ...
.... Reflow proceeds recursively through some or all of the frame hierarchy, computing geometric information for each frame object that requires it. Reflow may have the side-effect of creating new continuation frames, for example, for a text frame when the text must be wrapped. Some reflows are immediate in response to user or script actions; for example, resizing the window or changing the document's default font. These are dispatched directly from the presentation shell (e.g., nsIPresShell::StyleChangeReflow), and affect the entire frame tree. Other reflows are incremental and are dealt with asynchronously; for example, when content streams in from the network. Incremental reflows are queued by the presentation shell for batched dispatch. Reflow State The reflow state obj...
...And 2 more matches
Block and Line Layout Cheat Sheet - Archive of obsolete content
Objects This section presents some of the classes involved in block and line reflow, along with important members of each object that control reflow processing. nsFrame The base class for all frames. mFlags Flags set on the frame to indicate its state. ...
... Objects This section presents some of the classes involved in block and line reflow, along with important members of each object that control reflow processing. nsFrame The base class for all frames. mFlags Flags set on the frame to indicate its state. ...
...tes that this is a frame from which child margins can be calculated. The absence of this flag implies that child margin calculations should ignore the frame and look further up the parent chain. Used in nsBlockReflowContext::ComputeCollapsedTopMargin(). This flag causes the nsBlockReflowState's constructor to set the BRS_ISTOPMARGINROOT and BRS_ISBOTTOMMARGINROOT flags. ...
...And 2 more matches
Style System Overview - Archive of obsolete content
s collection of rules Other special things: @import, @media, @namespace, etc. A rule is a selector and a declaration block. A declaration block is a group of declarations. A declaration is a property and a value. p { color: green; font-size: 12em; } selector { property: value; property: value; } CSS Style Rules What do style rules mean? Selector matches elements in the document. Rule applies to matched elements. "cascaded" value for property + element: if 0 rules matching the element have the property: some properties inherit and some properties use initial value. inherited: 'font-size', 'color', etc. "reset": 'border', 'background', etc. 1 matching rule: use value 2+ matching rules: cascade decides which wins: sort by ori...
... the property: some properties inherit and some properties use initial value. inherited: 'font-size', 'color', etc. "reset": 'border', 'background', etc. ...
... ? ? title para class="emph" para ? ? quote quote ? ...
...And 2 more matches
Menu - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Menu
Jetpack's menu API allows features to access and modify the browser's built-in menus. Features can also create new menus and attach them almost anywhere, chrome or content, as popup menus or context menus. Two namespaces are associated with this API: jetpack.menu, which provides access to the browser's menus, and jetpack.Menu, the constructor for making new menus. The API is fairly comprehensive, so you may want to start by reading through some examples. ...
... the bookmark toolbar's context menu. To work around this limitation, try using beforeShow and examining the node that the user clicked. For example, to add an item to the tabs' context menu, try: jetpack.menu.context.browser.beforeShow = function (menu, context) { menu.reset(); if (context.node.localName === "tab") menu.add("Hey, a tab!"); }; (The reason this problem exists is because document.querySelectorAll() does not match anonymous content in XUL. Many parts of Firefox's interface are actually anonymous content. A future version of Jetpack will hopefully provide a better solution.) jetpack.menu.context.page The content context menu. This is the context menu that appears when right-clicking on a Web page. A ContextMenuSet object. Context objects Some callbacks passed into the API...
...escription node The DOM node on which the menu is shown. This is the node the user clicked to open the menu. Be careful when dealing with nested nodes. For example, if the user clicks on an image inside a link, this property will be set to the image, not the link. Similarly, if the user clicks a node within a div, this property will be the node, not the div. document The content document in which the menu is shown. window The content window in which the menu is shown. Targets Some methods act on existing items within a menu. Existing items are always identified using targets. A target is a string, regular expression, or integer. A string target is case-insensitively matched against the label, id, and xulId properties of ...
...And 2 more matches
Monitoring downloads - Archive of obsolete content
t displays the full source URL of the file. Download the full sample. Setting up When the extension loads, it will do some housekeeping chores. In particular, it needs to get an instance of the Download Manager's nsIDownloadManager interface and create the database into which its data will be stored. ...
... .get("ProfD", Components.interfaces.nsIFile); this.dbFile.append("downloadlogger.sqlite"); // Get access to the storage service and open the database this.storageService = Components.classes["@mozilla.org/storage/service;1"] .getService(Components.interfaces.mozIStorageService); var dbConn = this.storageService.openDatabase(this.dbFile); var loglist = document.getElementById("loglist"); var statement = dbConn.createStatement("SELECT * FROM items"); // Get all items in table try { while (statement.executeStep()) { var row = document.createElement('listitem'); // Add the cells to the row var cell = document.createElement('listcell'); var sourceStr = statement.getString(0); row.setAttribute("tooltiptext",...
...row = document.createElement('listitem'); // Add the cells to the row var cell = document.createElement('listcell'); var sourceStr = statement.getString(0); row.setAttribute("tooltiptext", sourceStr); sourceStr = sourceStr.slice(sourceStr.lastIndexOf("/")+1); cell.setAttribute("label", sourceStr); // Source row.appendChild(cell); cell = document.createElement('listcell'); cell.setAttribute("label", (statement.getInt64(1) / 1024).toFixed(1) + "KB"); // Size cell.setAttribute("style", "text-align:right"); row.appendChild(cell); var theDate = new Date(statement.getInt64(2) / 1000); // Start time cell = document.createElement('listcell'); var dateStr = theDate.toLocaleString(); cell...
...And 2 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
le, is a set of XPCOM components that can be accessed and used by any Mozilla application. File I/O, security, password management, and profiles are also separate XPCOM components that you can use in your own application development. Other Features of XPCOM: XPIDL, a language for defining interfaces in a language-neutral way and the XPIDL compiler can create header files, binary type libraries, documentation, and even generate stub C++ code for your component implementations. Tools including various XPCOM manager interfaces, smart pointers, special string classes, and an extensive collection of macros that make your C++ implementations easy to write and extend. A special base class, <tt>nsISupports</tt>, that helps manage object lifetime and reference counting. Sample component implementations...
... code for your component implementations. Tools including various XPCOM manager interfaces, smart pointers, special string classes, and an extensive collection of macros that make your C++ implementations easy to write and extend. A special base class, <tt>nsISupports</tt>, that helps manage object lifetime and reference counting. Sample component implementations you can extend and learn from. Documentation. Web Services Mozilla includes built-in support for popular web services standards XML-RPC, SOAP, and WSDL as well as a simple XMLHttpRequest object similar to the one in IE. All services are available from JavaScript code, which allows even simple XUL+JS applications to take advantage of them. Mozilla's XML-RPC support includes synchronous and asynchronous requesting and downloading of dat...
... security model for web services that will ease the deployment of applications using web services while maintaining the security of sites inside the user's firewall. More Information Using the Mozilla SOAP API (an article written for the Apple Developer Connection) XML Extras (the home page for the XML Extras code module, which contains Mozilla's web services support) SOAP Scripts in Mozilla (documentation on SOAP in Mozilla from the engineer who implemented it) XPInstall, Mozilla's Cross Platform Installation Technology One of the many things that makes the Mozilla platform easy for both users and developers is that applications can be installed, extended, or upgraded with simple web page links. The technology that makes this possible, XPInstall, allows application developers to write JavaSc...
...And 2 more matches
Plug-n-Hack Phase1 - Archive of obsolete content
H) phase 1 allows easier integration and defines how security tools can advertise their capabilities to browsers. Security tool manifest To support PnH-1 security tools provide a manifest over HTTP(S) which defines the capabilities that the browser can make use of. It is up to the tool authors to decide how the URL of the manifest is published. The tool configures itself by serving an HTML document (we'll call this the Configuration Document) to the browser. This can cause the browser to inspect the manifest and register the tool by firing a CustomEvent with the type ConfigureSecTool and a properties object which specifies the URL of the tool manifest. For example: var manifest = {"detail":{"url":"http://localhost:8080/manifest"}}; var evt = new CustomEvent('ConfigureSecTool', manifest); It...
... a properties object which specifies the URL of the tool manifest. For example: var manifest = {"detail":{"url":"http://localhost:8080/manifest"}}; var evt = new CustomEvent('ConfigureSecTool', manifest); It is suggested that browsers wishing to support PnH restrict handling of CustomEvents such that they're ignored where the event happens outside of user initiated actions. ...
...{"url":"http://localhost:8080/manifest"}}; var evt = new CustomEvent('ConfigureSecTool', manifest); It is suggested that browsers wishing to support PnH restrict handling of CustomEvents such that they're ignored where the event happens outside of user initiated actions. ...
...And 2 more matches
XBL 1.0 Reference - Archive of obsolete content
The element with a binding specified, called the bound element, acquires the new behavior specified by the binding. Bindings can be bound to elements using Cascading Style Sheets (CSS) or DOM. One element can be bound to several bindings at once. Functionally bindings should be correlated with Behaviors and Viewlink but being implemented as one integrated XML solution. ...
...L solution. Bindings can contain event handlers that are registered on the bound element, an implementation of new methods and properties that become accessible from the bound element, and anonymous content that is inserted around the bound element. There are numerous adjustments in the current implementation in comparison of earlier XBL proposals, and not all of them are reflected yet in this document. The documentation process is still in progress: please keep it in your mind while using the provided information. XBL Elements XBL 1.0 elements are in the http://www.mozilla.org/xbl namespace. bindings binding content children implementation constructor destructor field property getter setter method parameter body handlers handler resources stylesheet image Binding Atta...
... 1.0 elements are in the http://www.mozilla.org/xbl namespace. ...
...And 2 more matches
OpenClose - Archive of obsolete content
open property which may be set to true to open the menu, or false to close the menu. A simple example: somemenu.open = true; This single line of code will open a menu referenced by the variable 'somemenu'. Note that the open property applies to the menu or button, not to the menupopup. Here is a complete example which uses a button to open a menu: <button label="Open Menu" oncommand="document.getElementById('editMenu').open = true;"/> <menu id="editMenu" label="Edit"> <menupopup> <menuitem label="Cut"/> <menuitem label="Copy"/> <menuitem label="Paste"/> </menupopup> </menu> This technique may be used for both menupopups that use the menu tag, the button tag and the toolbarbutton tag. For menupopups attached to other elements using the popup or context attributes, se...
...is case, the parent menu must be opened first. If you do want to open a submenu, open the parent menu first, and then open the child menu in a popupshown event listener. See The popupshown event for an example of how to do this. a menu in an unprivileged content window (such as a web page) can only open a popup while its window is focused, and it is in the currently active tab. That means that a document in a background tab cannot open a menu or popup. Closing Menus Menus will close automatically once the user has made a selection from the menu. When an menu item is selected, it fires a command event so that code may be used to perform an action. The user may cancel selecting a command from a menu by pressing the Escape key. This will close a single menu, but if this menu has a parent menu, th...
...d the toolbarbutton tag. For menupopups attached to other elements using the popup or context attributes, see Closing a Popup below. When a menu is closed, the popuphiding event is fired at the menupopup. Attaching an event listener which listens for the popuphiding event can be used to remove any commands that were adding during the popupshowing event. Menus and popups are also closed when the document or window they are contained within is closed, or if the menupopup element is removed from the document. These are situations when the popuphiding or popuphidden events may not fire as the element the events would be fired on are no longer available. If you need to perform uninitialization that would be done during these events, this could be done during an unload event. Testing Menu Open State ...
...And 2 more matches
Template Builder Interface - Archive of obsolete content
If so, a template builder will be created for the element and attached to the element. If the element is a <tree> element and has the flags attribute set to "dont-build-content", a tree builder will be created. Otherwise, a content builder will be created. Both types of builder share much of the same code except for how they generate output to be displayed. Both types of builders implement the nsIXULTemplateBuilder interface, while the tree builder also implements the nsIXULTreeBuilder interface. ...
...associated with an element is accessible via the element's 'builder' property both for content builders and for tree builders. An element that does not have a builder will have this property set to null. The processes of creating a builder for an element applies both when an element is created when the window is loaded and when an element is inserted dynamically. Templates can only be used in XUL documents, however, there is no requirement that the templates generate XUL elements. They could also be used, for example, to generate HTML elements. This isn't a very common technique, however, here is an example of how this can be used: <html:div id="photosList" datasources="template-guide-photos5.rdf" ref="http://www.xulplanet.com/rdf/myphotos" xmlns:html="http://www.w3.org/1999/xh...
...Source method. You can add as many datasources as you wish, and you can remove them using the RemoveDataSource method. A common pattern is to use the following: var RDF = Components.classes["@mozilla.org/rdf/rdf-service;1"]. getService(Components.interfaces.nsIRDFService); var ds = RDF.GetDataSource("http://www.xulplanet.com/ndeakin/tests/xul/template-guide-streets.rdf"); var tree = document.getElementById("theTree"); tree.database.AddDataSource(ds); tree.builder.rebuild(); This is the typical way to add a datasource to an element, in this case to the tree with the id 'theTree'. The datasource is retrieved using the RDF service's GetDataSource method. After adding a datasource, the tree builder's rebuild method is invoked to rebuild the template with the new data. This doesn't happe...
...And 2 more matches
Focus and Selection - Archive of obsolete content
emoved from an element. You can respond to focus changes by adding an onfocus or onblur attribute on an element. They work just like their HTML counterparts. You might use these event handlers to highlight the element or display text on a status bar. The following example can be used to apply a function to handle a focus event. Example 2 : Source View <script> function displayFocus(){ var elem=document.getElementById('sbar'); elem.setAttribute('value','Enter your phone number.'); } </script> <textbox id="tbox1"/> <textbox id="tbox2" onfocus="displayFocus();"/> <description id="sbar" value=""/> The focus event, when it occurs, will call the displayFocus function. This function will change the value of the text label. We could extend this example to remove the text when the blur event occurs...
... of which there is only one for the window. The command dispatcher is responsible for keeping track of the focused element as the user uses the interface. The command dispatcher has other roles, which will be discussed in a later section on commands. For now, we'll look at some of the focus related features of the command dispatcher. You can retrieve the command dispatcher from a window using the document's commandDispatcher property. From there, you can get the focused element with the dispatcher's focusedElement property. The example below shows this. Example 3 : Source View <window id="focus-example" title="Focus Example" onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function init(){ addEventListener("focus",setFocusedElement...
...e focused element with the dispatcher's focusedElement property. The example below shows this. Example 3 : Source View <window id="focus-example" title="Focus Example" onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function init(){ addEventListener("focus",setFocusedElement,true); } function setFocusedElement(){ var focused = document.commandDispatcher.focusedElement; document.getElementById("focused").value = focused.tagName; } </script> <hbox> <label control="username" value="User Name:"/> <textbox id="username"/> </hbox> <button label="Hello"/> <checkbox label="Remember This Decision"/> <label id="focused" value="-No focus-"/> </window> In this example, a focus event handler is attached the window. We want to use...
...And 2 more matches
Tree Box Objects - Archive of obsolete content
alent to: let boxobject = tree.boxObject; boxobject.queryInterface("Components.interfaces.nsITreeBoxObject"); Scrolling the Tree You can also scroll the tree using four different methods, similar to those available for listboxes. The scrollToRow() function may be used to scroll to a particular row. Here is a simple example. ...
....queryInterface("Components.interfaces.nsITreeBoxObject"); Scrolling the Tree You can also scroll the tree using four different methods, similar to those available for listboxes. The scrollToRow() function may be used to scroll to a particular row. Here is a simple example. ...
...ree.boxObject.getRowAt( 50, 100 ); This example will return the index of the row with a horizontal position of 50 and a vertical position of 100. Naturally, it doesn't really matter what the value of the x coordinate is since rows always take up the entire horizontal space of the tree. ...
...And 2 more matches
XUL element attributes - Archive of obsolete content
have a template element as a child. For RDF templates, the specified datasources are combined into a single composite datasource which holds the data from all of the datasources. This composite datasource is accesssible via a script through the database property. For XML datasources, only one source is used, either the URL of an XML file or an anchor reference to another element within the same document. ...
... dir Type: one of the values below The direction in which the child elements of the element are placed. ...
...an element with the id 'data'. If you plan on adding a datasource to an element but don't want one to be added right away, set this attribute to 'rdf:null'. This will make the element so that its contents can be generated from a datasource. Otherwise, you cannot add one later. When the XUL document is contained on a remote web site, the datasources may only be loaded from the same domain as the document. dir Type: one of the values below The direction in which the child elements of the element are placed. normal For scales, the scale's values are ordered from left to right (for horizontal scales) or from top to bottom (for vertical scales) For other elements, the elements are placed left to right or top to bottom in the order they appear in the XUL code. reverse For scales, t...
...And 2 more matches
xbDesignMode.js - Archive of obsolete content
mmunications Corporation. * Portions created by the Initial Developer are Copyright (C) 2003 * the Initial Developer. All Rights Reserved. ...
...eserved. ...
... * ***** END LICENSE BLOCK ***** */ /* xbDesignMode a JavaScript wrapper for browsers that support designMode */ function xbDesignMode(aIFrame){ this.mEditorDocument = null; this.mIFrameElement = null; // argument is a string, therefore an ID if ( (typeof(aIFrame) == "string") && (document.getElementById(aIFrame).tagName.toLowerCase()=="iframe") ){ this.mIFrameElement = document.getElementById(aIFrame); } else if( (typeof(aIFrame)=="object") && (aIFrame.tagName.toLowerCase() == "iframe") ){ this.mIFrameElement = aIFrame; } else { throw "Argument isn't an id of an iframe or an iframe reference"; } if (this.mIFrameElement.contentDocument){ // Gecko this.mEditorDocument = this.mIFrameElement.contentDocument; this.mEditorDocument.designMode = "On...
...And 2 more matches
Displaying notifications (deprecated) - Archive of obsolete content
vents you can listen to on created notifications: onclick This event is fired when the user clicks (or taps) on the notification. onclose This event is fired when the notification is closed (whether by being clicked or by some other means). Note: If the notification is dismissed by the user clicking on it, both events will get fired. ...
...d when the user clicks (or taps) on the notification. onclose This event is fired when the notification is closed (whether by being clicked or by some other means). Note: If the notification is dismissed by the user clicking on it, both events will get fired. ...
...fication is closed (whether by being clicked or by some other means). Note: If the notification is dismissed by the user clicking on it, both events will get fired. ...
...And 2 more matches
Processing XML with E4X - Archive of obsolete content
A full definition of E4X can be found in the Ecma-357 specification. ...
... after the literal to alter it (see below). While one can interpolate attribute names as well as attribute values: var a = 'att'; var b = <b {a}='value'/>; alert(b); // Gives: <b att="value"/> ...one cannot interpolate a whole expression at once (e.g., <b {a}>.) After executing the above example, the variable languages references an XML object corresponding to the <languages> node in the XML document. This node has one attribute, type, which can be accessed and updated in a number of ways: alert(languages.@type); // Alerts "dynamic" languages.@type = "agile"; alert(languages.@type); // Alerts "agile" alert(languages.toString()); /* Alerts: <languages type="agile"><lang>JavaScript</lang><lang>Python</lang></languages> */ Note that if one wishes to make comparisons of retrieved at...
...avaScript's E4X support: for each (var lang in languages.lang) { alert(lang); } for each...in can also be used with regular JavaScript objects to iterate over the values (as opposed to the keys) contained in the object. As with for...in, using it with arrays is strongly discouraged. It is possible to create an XMLList using XML literal syntax without needing to create a well-formed XML document, using the following syntax: var xmllist = <> <lang>JavaScript</lang> <lang>Python</lang> </>; The += operator can be used to append new elements to an XMLList within a document: languages.lang += <lang>Ruby</lang>; Note that unlike node lists returned by regular DOM methods, XMLLists are static and are not automatically updated to reflect changes in the DOM. If you create an XMLLi...
...And 2 more matches
Introduction - Archive of obsolete content
id 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 appendChild var element1 = <foo/>; var element2 = <bar/>; element1.appendChild(element2); ...
...>; 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 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. ...
...Note, however, that XML elements can only have text as their value. ...
...And 2 more matches
Error.description - Archive of obsolete content
ontained in this property to alert a user to an error. The description and message properties provide the same functionality; the descriptionproperty provides backward compatibility; the message property complies with the ECMA standard. Example The following example illustrates the use of the description property. ...
...rty to alert a user to an error. The description and message properties provide the same functionality; the descriptionproperty provides backward compatibility; the message property complies with the ECMA standard. Example The following example illustrates the use of the description property. ...
...ription and message properties provide the same functionality; the descriptionproperty provides backward compatibility; the message property complies with the ECMA standard. Example The following example illustrates the use of the description property. ...
...And 2 more matches
XForms Custom Controls - Archive of obsolete content
nnot anticipate all of the possible use cases that will evolve in web applications and web pages as XForms matures and the user base grows. And with these new uses, more and more flexibility will be desired from the controls. Introducing custom controls into your environment may be just the solution you are looking for. For example, you might want to render images that are held inside an instance document or you would like to show a disabled trigger when its bound node becomes irrelevant rather than having it not display (the current default behavior). Every XForms control's presentation has its own XBL binding. In many cases different values provided for the appearance or mediatype attributes will determine which XBL binding will be used for a particular XForms control on the form. As mentioned i...
...ol. </body> </method> <constructor> // We should redirect calls of input's 'refresh' method to custom control 'refresh' method. var control = this; var refreshStub = function() { control.refresh(); } this.ref1.refresh = refreshStub; this.ref2.refresh = refreshStub; </constructor> <property name="ref1" readonly="true" onget="return this.ownerDocument.getAnonymousElementByAttribute(this, 'anonid', 'ref1');"/> <property name="ref2" readonly="true" onget="return this.ownerDocument.getAnonymousElementByAttribute(this, 'anonid', 'ref2');"/> </implementation> New Host Language The Mozilla XForms implementation currently only supports XForms hosted in XHTML or XUL documents. If you need to have XForms in other kinds of documents like ...
...The XForms implementation has base XBL bindings for every XForms control. You can write implementation bindings that will inherit from these base bindings. ...
...And 2 more matches
Mozilla XForms Specials - Archive of obsolete content
ad of using digest('abc', 'SHA-1') explicitly use the third parameter (the results are equal): digest('abc', 'SHA-1', 'base64') (limitation tracked in bug 477857) Extensions Enumerating Instances The standardized nsIXFormsModelElement does not allow one to enumerate over all possible instances, but only to retrieve instances by their name. In the Mozilla XForms Extension we added a getInstanceDocuments() function to the model which returns all the model's instance documents. This is documented in nsIXFormsNSModelElement. Getting To Instance Element From A Data Node In the XForms 1.0 specification there is no way to get to the instance element from an instance data node. We have added a function via the getFeature() call on each node, that allows the form author to do that. That is, if instance...
...h returns all the model's instance documents. This is documented in nsIXFormsNSModelElement. Getting To Instance Element From A Data Node In the XForms 1.0 specification there is no way to get to the instance element from an instance data node. We have added a function via the getFeature() call on each node, that allows the form author to do that. That is, if instanceNode is a node in an instance document, then: instanceNode.getFeature("org.mozilla.xforms.instanceOwner", "1.0") will return the <instance> element (in the main document) that the node belongs to. Getting To The Instance Document From The Instance Element In the XForms 1.0 specification you have to go through the model element to get to the instance document. It seems a bit awkward if you have the instance element, so we have added a...
...This is documented in nsIXFormsNSInstanceElement. ...
...And 2 more matches
Issues Arising From Arbitrary-Element hover - Archive of obsolete content
Bare Pseudo-Classes The second piece of the problem comes when we consider the effects of a "bare" pseudo-class in a selector. For example: :hover {color: red;} This is equivalent to the CSS2 rule: *:hover {color: red;} ..which translates as "any element that is being hovered should have its foreground colored red." Thus, hovering over paragraphs, tables, headings, and any other element in a document will cause text to become red. A common variant is to use a bare class and hover pseudo-class together, like this: .nav:hover {color: red;} In situations where the only instances of the class value nav are applied to hyperlinks, this will work fine. However, rules of this type are usually seen in conjunction with markup like this: <td class="nav"> <a href="one.html" class="nav">one</a> | <a h...
...ou.html" class="nav">four</a> </td> Because the enclosing table cell has a class of nav, the vertical-bar characters will turn red when the user moves the mouse pointer anywhere within the table cell. The links will also turn red when they are hovered. Gecko Behavior In browsers based on Netscape Gecko builds later than 20020410 (Netscape 6.1+), :hover styles can be applied to any element in a document. ...
...ver styles can be applied to any element in a document. Thus authors who have used bare pseudo-classes, or bare class-pseudo-class combinations, are at risk of seeing hover styles applied to more than just their links. The most reliable fix is to add the anchor element to the selectors, like this: a:hover {color: red;} a.nav:hover {color: red;} In an attempt to avoid causing problems for legacy documents, browsers based on Mozilla 1.0 and later (Netscape 7+) include code that causes bare pseudo-classes to be restricted only to links if the document is rendered in "quirks" mode. In browsers based on the engine found in Mozilla 1.3b and later, this quirk is extended to cover selectors that combine a bare class selector with the :hover pseudo-class (see bug 169078 for details). Named Anchor Proble...
...And 2 more matches
RDF in Mozilla FAQ - Archive of obsolete content
General Where do I start? RDF serves two primary purposes in Mozilla. First, it is a simple, cross-platform database for small data stores. Second, and more importantly, the RDF model is used along with XUL templates as an abstract "API" for displaying information. RDF in Fifty Words or Less is a quick, high-level description of what RDF does in Mozilla. The RDF Back-end Architecture document describes in more detail how Mozilla's RDF implementation works, and gives a quick overview of the interfaces that are involved. Where do I find information on Open Directory ("dmoz")? Unfortunately, not here! Well, here's a little... Start at http://www.dmoz.org/ for more information on the Open Directory. The Open Directory dataset is available as a (huge) RDF/XML dump. It describes thousands of...
..., if your datasource already has an object that is an RDF container, you can instantiate an nsIRDFContainer object with the @mozilla.org/rdf/container;1 ContractID and Init() it with the datasource and resource as parameters. Note that this will fail if the resource isn't already a container. XUL Templates XUL templates are created by specifying a datasources attribute on an element in a XUL document. There are two "forms" that XUL templates may be written in. The "simple" form, which is currently the most common form in the Mozilla codebase, and the "extended" form, which allows for sophisticated pattern matching against the RDF graph. See the XUL:Template Guide. (These are bizarrely arranged because the eventual intent is to introduce templates using the extended form -- which in many ways...
...aded using the nsIRDFService's GetDataSource() method, so it will be managed similarly to all other datasources loaded this way. What is the security model for RDF/XML in XUL? XUL that is loaded from a "trusted" URL (currently, any chrome: URL) can specify any datasource URI in the datasources attribute of the XUL template. XUL that is loaded from an "untrusted" URL can only specify an RDF/XML document from the same codebase (in the Java sense of the word) that the XUL document originated from. No "special" (i.e., rdf:) datasources may be loaded from untrusted XUL. How do I add a datasource to a XUL template? Although it's possible to create a XUL template with an "implicit" set of datasources by specifying the datasources attribute, there are often times when you won't know the datasource th...
...And 2 more matches
Building up a basic demo with Three.js - Game development
nother library, such as CopperLicht, GLGE, or PlayCanvas. Environment setup To start developing with Three.js, you don't need much. You should: Make sure you are using a modern browser with good WebGL support, such as the latest Firefox or Chrome. Create a directory to store your experiments in. Save a copy of the latest minimized Three.js library inside your directory. Open the Three.js documentation in a separate tab -- it is useful 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 HEI...
...The first <script> element includes the Three.js library in the page, and we will write our example code inside the second. There are two helper variables already included, which store the window's width and height. Before reading f...
...WebGL implementation will implement differently than the CSS one. Despite the variety of ways they achieve the goal, the experience will look the same for the user. Thanks to this approach, a fallback can be used, if a desired technology is not supported by the browser. var renderer = new THREE.WebGLRenderer({antialias:true}); renderer.setSize(WIDTH, HEIGHT); renderer.setClearColor(0xDDDDDD, 1); document.body.appendChild(renderer.domElement); We are creating a new WebGL renderer, 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 ...
...And 2 more matches
Async scripts for asm.js - Game development
de 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. ...
...ent loads (starting in Firefox 28). To see the difference, toggle javascript.options.parallel_parsing in about:config. ...
...g 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? ...
...And 2 more matches
Accessible multimedia - Learn web development
wd">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. ...
.../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. ...
...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 2 more matches
Type, class, and ID selectors - Learn web development
simplest selectors that are available, which you will probably use the most in your work. Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.) Objective: To learn about the different CSS selectors we can use to apply CSS to a document. Type selectors A type selector is sometimes referred to as a tag name selector or element selector, because it selects an HTML tag/element in your document. In the example below we have used the span, em and strong selectors. All instances of <span>, <em> and <strong> elements are therefore styled accordingly. Try adding a CSS rule to select the <h1> element and change its color to blue...
...In the following example we have used the universal selector to remove the margins on all elements. ...
...iversal selector to the :first-child selector, so it is obvious what the selector is doing. It is selecting any element which is the first-child of any descendant element of <article>: article *:first-child { } Although both do the same thing, the readability is significantly improved. Class selectors The class selector starts with a full stop (.) character and will select everything in the document with that class applied to it. In the live example below we have created a class called .highlight, and have applied it to several places in my document. All of the elements that have the class applied are highlighted. Targeting classes on particular elements You can create a selector that will target specific elements with the class applied. In this next example we will highlight a <span> wi...
...And 2 more matches
Introduction to CSS layout - Learn web development
iting Mode, such as Japanese. The corresponding Inline Direction is the direction in which inline contents (such as a sentence) would run. For many of the elements on your page the normal flow will create exactly the layout you need, however for more complex layouts you will need to alter this default behavior using some of the tools available to you in CSS. Starting with a well-structured HTML document is very important, as you can then work with the way things are laid out by default rather than fighting against it. The methods that can change how elements are laid out in CSS are as follows: The display property -- Standard values such as block, inline or inline-block can change how elements behave in normal flow, for example making a block-level element behave like an inline element (see ...
...h display: block. If you create a link around some text inside a paragraph, that link remains inline with the rest of the text, and doesn't break onto a new line. This is because the <a> element is display: inline by default. You can change this default display behavior. For example, the <li> element is display: block by default, meaning that list items display one below the other in our English document. If we change the display value to inline they now display next to each other, as words would do in a sentence. The fact that you can change the value of display for any element means that you can pick HTML elements for their semantic meaning, without being concerned about how they will look. The way they look is something that you can change. In addition to being able to change the default pres...
...umn. To use flexbox, you apply display: flex to the parent element of the elements you want to lay out; all its direct children then become flex items. We can see this in a simple example. The HTML markup below gives us a containing element, with a class of wrapper, inside which are three <div> elements. By default these would display as block elements, below one another, in our English language document. However, if we add display: flex to the parent, the three items now arrange themselves into columns. This is due to them becoming flex items and being affected by some initial values that flexbox sets on the flex container. They are displayed in a row, because the initial value of flex-direction set on their parent is row. They all appear to stretch to the height of the tallest item, because th...
...And 2 more matches
Responsive design - Learn web development
deemed ready for implementation in browsers. Media Queries allow us to run a series of tests (e.g. whether the user's screen is greater than a certain width, or a certain resolution) and apply CSS selectively to style the page appropriately for the user's needs. For example, the following media query tests to see if the current web page is being displayed as screen media (therefore not a printed document) and the viewport is at least 800 pixels wide. The CSS for the .container selector will only be applied if these two things are true. @media screen and (min-width: 800px) { .container { margin: 1em 2em; } } You can add multiple media queries within a stylesheet, tweaking your whole layout or parts of it to best suit the various screen sizes. The points at which a media query is introd...
...ntroduced, and the layout changed, are known as breakpoints. A common approach when using Media Queries is to create a simple single-column layout for narrow-screen devices (e.g mobile phones), then check for larger screens and implement a multiple-column layout when you know that you have enough screen width to handle it. This is often described as mobile first design. Find out more in the MDN documentation for Media Queries. Flexible grids Responsive sites don't just change their layout between breakpoints, they are built on flexible grids. A flexible grid means that you don't need to target every possible device size that there is, and build a pixel perfect layout for it. That approach would be impossible given the vast number of differently-sized devices that exist, and the fact that on de...
...t into percentages. target / context = result For example, if our target column size is 60 pixels, and the context (or container) it is in is 960 pixels, we divide 60 by 960 to get a value we can use in our CSS, after moving the decimal point two places to the right. .col { width: 6.25%; /* 60 / 960 = 0.0625 */ } This approach will be found in many places across the web today, and it is documented here in the layout section of our Legacy layout methods article. It is likely that you will come across websites using this approach in your work, so it is worth understanding it, even though you would not build a modern site using a float-based flexible grid. The following example demonstrates a simple responsive design using Media Queries and a flexible grid. On narrow screens the layout dis...
...And 2 more matches
Fundamental text and font styling - Learn web development
you have a lot of nested elements with different font sizes set, but it is doable, as you'll see below. Why bother? It is quite natural once you get used to it, and you can use em to size everything, not just text. You can have an entire website sized using em, which makes maintenance easy. ...
...Any paragraph (or another element that doesn't have a different size set by the browser) inside the root element will have a final size of 16 px. Other elements may have different default sizes, for example an <h1> element has a size of 2 em set by default, so it will have a final size of 32 px. ...
...fault, so it will have a final size of 32 px. Things become more tricky when you start altering the font size of nested elements. For example, if you had an <article> element in your page, and set its font-size to 1.5 em (which would compute to 24 px final size), and then wanted the paragraphs inside the <article> elements to have a computed font size of 20 px, what em value would you use? <!-- document base font-size is 16px --> <article> <!-- If my font-size is 1.5em --> <p>My paragraph</p> <!-- How do I compute to 20px font-size? --> </article> You would need to set its em value to 20/24, or 0.83333333 em. The maths can be complicated, so you need to be careful about how you style things. It is best to use rem where you can, to keep things simple, and avoid setting the font-size of contain...
...And 2 more matches
What text editors are available? - Learn web development
Your computer may already be installed with one of the editors suggested above (e.g. Gedit if you use GNOME desktop, Kate if you use KDE etc.), if not then you should try installing one or more text editors of your choosing. Try digging through the s...
...ctive learning section, we would like you to try using and/or installing a text editor of your choice. Your computer may already be installed with one of the editors suggested above (e.g. Gedit if you use GNOME desktop, Kate if you use KDE etc.), if not then you should try installing one or more text editors of your choosing. Try digging through the settings of your editor and read the manual or documentation to see what its capabilities are. In particular (if possible in your editor), try to: Change syntax highlighting settings and colors Play with indentation width, setting it to an appropriate setting for your needs Check autosave and session saving settings Configure any available plugins and investigate how to get new ones Change color schemes Adjust view settings and see how you can...
...king with. Many text editors help you out with features like: Syntax highlighting. Make your file more legible by color-coding keywords based on the technology you're using. Code completion. Save you time by auto-completing recurring structures (for example, automatically close HTML tags, or suggesting valid values for a given CSS property). Code snippets. As you saw when starting a new HTML document, many technologies use 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...
...And 2 more matches
What is the difference between webpage, website, web server, and search engine? - Learn web development
me as you read on. It's easy to confuse these terms sometimes since they refer to related but different functionalities. In fact, you'll sometimes see these terms misused in news reports and elsewhere, so getting them mixed up is understandable! We'll cover these terms and technologies in more detail as we explore further, but these quick definitions will be a great start for you: web page A document which can be displayed in a web browser such as Firefox, Google Chrome, Opera, Microsoft Internet Explorer or Edge, or Apple's Safari. These are also often called just "pages." website A collection of web pages which are grouped together and usually connected together in various ways. Often called a "web site" or simply a "site." web server A computer that hosts a website on the Internet. se...
...arch index is like the search engine. Each book has its own unique location in the library (two books cannot be kept at the same place) which is specified by the catalog number. Active learning There is no active learning available yet. Deeper dive So, let's dig deeper into how those four terms are related and why they are sometimes confused with each other. ...
...ch book has its own unique location in the library (two books cannot be kept at the same place) which is specified by the catalog number. Active learning There is no active learning available yet. Deeper dive So, let's dig deeper into how those four terms are related and why they are sometimes confused with each other. Web page A web page is a simple document displayable by a browser. ...
...And 2 more matches
What is a web server? - Learn web development
e, a web site, a web server, and a search 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...
... accessed through the domain names of the websites it stores, and it delivers the content of these hosted websites to the end user's device. At the most basic level, whenever a browser needs a file that is hosted on a web server, the browser requests the file via HTTP. When the request reaches the correct (hardware) web server, the (software) HTTP server accepts the request, finds the requested document, and sends it back to the browser, also through HTTP. (If the server doesn't find the requested document, it returns a 404 response instead.) To publish a website, you need either a static or a dynamic web server. A static web server, or stack, consists of a computer (hardware) with an HTTP server (software). We call it "static" because the server sends its hosted files as-is to your browser.
...s before sending content to your browser via the HTTP server. For example, to produce the final webpages you see in the browser, the application server might fill an HTML template with content from a database. Sites like MDN or Wikipedia have thousands of webpages. Typically, these kinds of sites are composed of only a few HTML templates and a giant database, rather than thousands of static HTML documents. This setup makes it easier to maintain and deliver the content. Active learning There is no active learning available yet. Deeper dive To review: to fetch a webpage, your browser 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 thos...
...And 2 more matches
How to build custom form controls - Learn web development
ements, but it is still available to screen readers. Now we need a JavaScript switch to determine if the script is running or not. This switch is a couple of lines: if at page load time our script is running, it will remove the no-widget class and add the widget class, thereby swapping the visibility of the <select> element and the custom control. ...
...ders. Now we need a JavaScript switch to determine if the script is running or not. This switch is a couple of lines: if at page load time our script is running, it will remove the no-widget class and add the widget class, thereby swapping the visibility of the <select> element and the custom control. ...
...l('.option'); // We remove the highlight from all options optionList.forEach(function (other) { other.classList.remove('highlight'); }); // We highlight the right option option.classList.add('highlight'); }; You need these in order to handle the various states of the custom control. ...
...And 2 more matches
Adding vector graphics to the Web - Learn web development
Previous Overview: Multimedia and embedding Next Vector graphics are very useful in many circumstances -- they have small file sizes and are highly scalable, so they don't pixelate when zoomed in or blown up to a large size. In this article we'll show you how to include one in your webpage. Prerequisites: You should know the basics of HTML and how to insert an image into your document. Objective: Learn how to embed an SVG (vector) image into a webpage. Note: This article doesn't intend to teach you SVG; just what it is, and how to add it to web pages. What are vector graphics? On the web, you'll work with two types of image -- raster images, and vector images: Raster images are defined using a grid of pixels -- a raster image file contains information...
... 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 putting your SVG inline, or inlining SVG. Make sure your SVG code snippet begins and ends with the <svg></svg> tags (don't include anything outside those.) Here's a very simple example of what you might paste into your document: <svg width="300" height="200"> <rect width="100%" height="100%" fill="green" /> </svg> Pros Putting your SVG inline saves an HTTP request, and therefore can reduce a bit your loading time. You can assign classes and ids to SVG elements and style them with CSS, either within the SVG or wherever you put the CSS style rules for your HTML document. In fact, you can use any SVG presentatio...
...And 2 more matches
A bird's-eye view of the Mozilla framework
ckages. 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 (Application Programming Interface) for accessing and manipulating the content. An application such as the browser may have one or more open documents accessible via DOM APIs. When an HTML, XML, SVG or other type of document is loaded, the NGLayout engine (also known as Gecko) parses the...
...The NGLayout engine also parses XUL UI controls into a DOM tree and handles rendering of the UI. Core Services Modules such as the NGLayout engine comprise the core application services available to other core modules, and XUL packages Core application modules are implemented as a set of one or more XPCOM (Cross-Platform COM) objects. ...
...t information. In this example, we're interested in the RDF sub-graph underlying theContents Panel widget within theHelp Viewer window. Suppose the client already has an nsIRDFDataSource object representing a sub-graph of an RDF graph and calls nsIRDFDataSource.GetTarget(resource, NC_LINK, true) to obtain an nsIRDFNode representing a specific node in the graph, in this case a link to aHelp Viewer document page. The client is completely unaware of which C++ class (or other language) actually implements nsIRDFNode; it only interacts with the IDL interface. The client would like to ask the nsIRDFNode whether its supports nsIRDFLiteral. An nsIRDFNode must be an nsIRDFLiteral or an nsIRDFResource. The link is a literal, so the client wants nsIRDFLiteral. Since all XPCOM interfaces inherit the base int...
...And 2 more matches
Listening to events on all tabs
that implements the callbacks used to provide notifications of progress events. Removing a listener To remove a previously installed progress listener, call removeTabsProgressListener(): gBrowser.removeTabsProgressListener(myProgressListener); Implementing a listener The listener object itself has five methods it can implement to handle various events: onLocationChange Called when the URI of the document displayed in the tab changes. void onLocationChange( nsIDOMXULElement aBrowser, nsIWebProgress aWebProgress, nsIRequest aRequest, nsIURI aLocation [optional] in unsigned long aFlags ); Parameters aBrowser The browser representing the tab whose location changed. aWebProgress The progress instance responsible for handling the events. aRequest The nsIRequest objec...
...nce responsible for handling the events. aRequest The nsIRequest object representing the associated request. aLocation An nsIURI object indicating the tab's new URI. aFlags Optional: This is a value which explains the situation or the reason why the location has changed. Optional from Gecko 10 onProgressChange Called when updated progress information for the download of a document is available. void onProgressChange( nsIDOMXULElement aBrowser, nsIWebProgress aWebProgress, nsIRequest aRequest, PRInt32 aCurSelfProgress, PRInt32 aMaxSelfProgress, PRInt32 aCurTotalProgress, PRInt32 aMaxTotalProgress ); Parameters aBrowser The browser representing the tab for which updated progress information is being provided. aWebProgress The progress instance...
...e request indicated by the request parameter. aCurTotalProgress The current progress for all requests associated with webProgress. aMaxTotalProgress The total progress for all requests associated with webProgress. onSecurityChange Notification called for security progress. This method will be called on security transitions (eg HTTP -> HTTPS, HTTPS -> HTTP, FOO -> HTTPS) and after document load completion. It might also be called if an error occurs during network loading. Note: These notifications will only occur if a security package is installed. void onSecurityChange( nsIDOMXULElement aBrowser, nsIWebProgress aWebProgress, nsIRequest aRequest, unsigned long aState ); Parameters aBrowser The browser that fired the notification. aWebProgress The nsIWebP...
...And 2 more matches
Performance
If each framescript registers a seperate listener then the observed action will trigg...
...If each framescript registers a seperate listener then the observed action will trigger the callbacks in all tabs. Additionally the example above does not clean unregister itself, thus leaking objects each time a tab is closed. Frame message manager message and ...
...cript registers a seperate listener then the observed action will trigger the callbacks in all tabs. Additionally the example above does not clean unregister itself, thus leaking objects each time a tab is closed. Frame message manager message and event listeners are limited in their lifetime to that of the frame itself, this does not apply to observer registrations. ...
...And 2 more matches
mozbrowserasyncscroll
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. ...
...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>. ...
... 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 browser <iframe>. scrollWidth The total content width in CSS pixels of the document within the browser <iframe>. scrollHeight The total content height in CSS pixels of the document within the browser <iframe>. Note: top + height may be larger than scrollHeight. This indicates that ...
...And 2 more matches
An overview of NSS Internals
specific properties, advantages and disadvantages, which is why all of them are still being used (nobody has yet dared to replace the older with the newer ones because of risks for side effects). When using the ASN.1 parser(s), a template definition is passed to the parser, which will analyze the ASN.1 data stream accordingly. The templates are usually closely aligned to definitions found in RFC documents. A data block described as DER is usually in ASN.1 format. You must know which data you are expecting, and use the correct template for parsing, based on the context of your software's interaction. Data described as PEM is a base64 encoded presentation of DER, usually wrapped between human readable BEGIN/END lines. NSS prefers the binary presentation, but is often capable to use base64 or ASC...
... has multiple implementations for the same or similar concepts. For example, there are multiple presentations of certificates, and the NSS internals (and sometimes even the application using NSS) might have to convert between them. Key responsibilites of NSS are verification of signatures and certificates. In order to verify a digital signature, we have to look at the application data (e.g., a document that was signed), the signature data block (the digital signature), and a public key (as found in a certificate that is believed to be the signer, e.g., identified by metadata received together with the signature). The signature is verified if it can be shown that the signature data block must have been produced by the owner of the public key (because only that owner has the associated private ke...
...ioning the Extended Validation (EV) principle, which is an effort by software vendors and CAs to define a stricter set of rules for issuing certificates for web site certificates. Instead of simply verifying that the requester of a certificate is in control of an administrative email address at the desired web site's domain, it's required that the CA performs a verification of real world identity documents (such as a company registration document with the country's authority), and it's also required that a browser software performs a revocation check with the CA, prior to granting validity to the certificate. In order to distinguish an EV certificate, CAs will embed a policy OID in the certificate, and the browser is expected to verify that a trust chain permits the end entity (EE) certificate to ...
...And 2 more matches
NSS 3.12.6 release notes
Network Security Services (NSS) 3.12.6 is a patch release for NSS 3.12. The bug fixes in NSS 3.12.6 are described in the "Bugs Fixed" section below. NSS 3.12.6 is tri-licensed under the MPL 1.1/GPL 2.0/LGPL 2.1. Distribution Information The CVS tag for the NSS 3.12.6 release is NSS_3_12_6_RTM. NSS 3.12.6 requires NSPR 4.8.4. See the Documentation section for the build instructions. NSS 3.12.6 source and binary distributions are also available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_12_6_RTM/src/. You also need to download the NSPR 4.8.4 binary distributions to get the NSPR 4.8.4 header files and shared...
...nt variables SQLITE_FORCE_PROXY_LOCKING 1 means force always use proxy, 0 means never use proxy, NULL means use proxy for non-local files only. SSLKEYLOGFILE Key log file. If set, NSS logs RSA pre-master secrets to this file. This allows packet sniffers to decrypt TLS connections. See documentation. Note: The code must be built with TRACE defined to use this functionality. Bugs Fixed The following bugs have been fixed in NSS 3.12.6. Bug 275744: Support for TLS compression RFC 3749 Bug 494603: Update NSS's copy of sqlite3 to 3.6.22 to get numerous bug fixes ...
...New and revised documents available since the release of NSS 3.11 include the following: Build Instructions NSS Shared DB Compatibility NSS 3.12.6 shared libraries are backward compatible with all older NSS 3.x shared li...
...And 2 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. ...
...ith since being written by the add-on author. Specifically, it focuses on the process of digitally signing update manifests so the applications can verify the integrity of a manifest retrieved over normally insecure channels. Midas Midas is the code name for Gecko's built-in rich text editor. Midas can be enabled via JavaScript on an HTML document. 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 abil...
... Mozinfo Throughout mozmill and other Mozilla python code, checking the underlying platform is done in many different ways. ...
...And 2 more matches
Places Developer Guide
It provides code samples for many common use-cases, such as CRUD operations, searching, and observing. Overview Places is the umbrella term for a set of APIs for managing browsing history and URI metadata first introduced in Firefox 3. It encompasses history, bookmarks, tags, favicons, and annotations. There are two models of identity in the system: URIs, and unique integer identifiers for items in the bookmark system. Some of the APIs are URI-centric, some use item ids. The API signature and context usually make clear which is required. ...
... nsINavBookmarksService.toolbarFolder - The contents of this folder are visible on the Bookmarks toolbar. nsINavBookmarksService.unfiledBookmarksFolder - Items that have been "starred", but not places in any folder. nsINavBookmarksService.tagsFolder - Subfolders of this folder are tags, and their children are URIs that have been tagged with that folder's name. Other Bookmarks APIs Note: This document covers the toolkit Places services. 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 Jav...
...type = childNode.type; // Some type-specific actions. if (type == Ci.nsINavHistoryResultNode.RESULT_TYPE_URI) { var uri = childNode.uri; } else if (type == Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER) { childNode.QueryInterface(Ci.nsINavHistoryContainerResultNode); childNode.containerOpen = true; // now you can iterate over a subfolder's children } } ther available node types are documented in the IDL. Searching Bookmarks Queries are executed through the history service. The example below shows how to search through all bookmarks, and to iterate over the results. var bookmarks = Cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getService(Ci.nsINavBookmarksService); var history = Cc["@mozilla.org/browser/nav-history-service;1"] .getService(Ci.nsINav...
...And 2 more matches
Avoiding leaks in JavaScript XPCOM components
t'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 variables) or a fixed size for the lifetime of a function (stack variables) requires a system for dynamic memory allocation: a sys...
...d access the DOM node again the same way he did the first time, and would then expect the added properties to still be there. We currently implement this by making the wrapper a root in the JavaScript garbage collector once somebody sets a JavaScript property on a DOM node. (This is roughly equivalent to making all the properties roots, but simpler.) Once this happens, it remains a root until the document stops being displayed. This means that neither the element nor any of the properties nor any of the objects reachable from those properties can be freed until the document is no longer displayed. You might think that it's unusual to set arbitrary properties on DOM nodes. And in many cases it is. But in one important case it's not: XBL. XBL fields are implemented as JavaScript properties on the b...
... JavaScript global object for the context in which it was created, and a bunch of associated objects will all leak for the lifetime of the application. It's also worth noting that failing to unregister an observer that's attached to something temporary (such as a controller or event listener) can cause the garbage collector to take an extra cycle to clean up everything that was associated with a document if the temporary object itself is destroyed as a result of garbage collection. See one of the patches in bug 231384 for some examples. Don't create cycles through XPCOM In a garbage-collected system, reference cycles aren't a problem. If A has a pointer to B and B has a pointer to A, but neither is reachable from anything else, they are both freed when garbage collection happens. In a reference...
...And 2 more matches
Using XPCOM Components
ng interfaces you can use. Its nsIWebBrowserFind interface is shown in The nsIWebBrowserFind Interface. To use this component, you access it through the nsIWebBrowserFind interface and call its methods. The nsIWebBrowserFind Interface findNext Find the next occurrence of the search string. findBackwards Boolean attribute that adjusts findNext() to search backwards up the document. searchFrames Boolean attribute that indicates whether to search subframes of current document. matchCase Boolean attribute that indicates whether to match case in the search. entireWord Boolean attribute that specifies whether the entire word should be matched or not. Once you use the interface to get to the component, you can ask the component what oth...
...I added |PR_FALSE| as a fourth parameter because the interface seems to require it: http://lxr.mozilla.org/mozilla/source/netwerk/cookie/public/nsICookieManager.idl#64 This problem also appears in the JavaScript version below, and I've added |false| as a fourth parameter there as well. If your application is written in C++, then M...
...merator.getNext(); nextCookie = nextCookie.QueryInterface(Components.interfaces.nsICookie); /* .... */ } function FinalizeCookieDeletions() { for (var c=0; c<deletedCookies.length; c++) { cmgr.remove(deletedCookies[c].host, deletedCookies[c].name, deletedCookies[c].path, false); } deletedCookies.length = 0; } XXX: In the original document, there were only the first three parameters to the |remove| call. I added |false| as a fourth parameter because the interface seems to require it: http://lxr.mozilla.org/mozilla/source/netwerk/cookie/public/nsICookieManager.idl#64 This problem also appears in the C++ version above, and I've added |PR_FALSE| as a fourth parameter there as well. Beyond the methods that are being called on the Cook...
...And 2 more matches
mozIRegistry
It's not really about any "registry interface" so much as it's about how Mozilla supports a more dynamic binding between interface clients and the code that actually provides the implementation of those interfaces. It happens that this objective requires storing information about which implementation to use in a place distinct from your source code. And it happens that we've chosen, up till now, to store that information in the "Netscape registry" file. ...
...ter-colored boxes near the top of the picture). These are placeholders for the types of components you're designing and implementing. I'll talk about them to provide examples of how you should use the other boxes. These components (indicated by the darker-colored boxes) are the services you'll be using. I'll be explaining the rationale for the design and implementation of these components in this document. Lastly, there's one component (labelled "mozRDFRegistry/nsIRDFDatabase") that potentially will emerge as an improved implementation of one of the mozIRegistry interfaces. I'll be discussing that implementation only briefly (mainly because I'm hoping I can pawn off the chore of implementing it to somebody else). There's another component that turns out to also be real important when you go to h...
...e). There's another component that turns out to also be real important when you go to hook up your code with other Mozilla components. That's the Service Manager. I'm just starting to understand the role it plays in this and it isn't really under my jurisdiction, so there's nothing about it here right now. In the future, I'll either add the information about it or at least put in a link to it's documentation. Higher-Level Application Components This box represents all the potential user's of the core registry/repository interfaces. Your code (most likely) falls in this box. These components will, to various degrees, need to use other components to do their thing. Those other components presumably implement particular XPCOM interfaces. So how do you go about creating an object that can provid...
...And 2 more matches
mozIStorageStatement
storage/public/mozIStorageStatement.idlScriptable This interface lets you create and execute SQL statements on a mozIStorageConnection. Inherits from: mozIStorageValueArray Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) For an introduction on how to use this interface, see the Storage overview document. Method overview void initialize(in mozIStorageConnection aDBConnection, in AUTF8String aSQLStatement); Obsolete since Gecko 1.9.1 void finalize(); mozIStorageStatement clone(); AUTF8String getParameterName(in unsigned long aParamIndex); unsigned long getParameterIndex(in AUTF8String aName); AUTF8String getColumnName(in unsigned long aColumnIndex); unsigned long getColumnIndex(in AUTF8String a...
...String 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 escapeStringForLIKE( in AString aValue, in wchar aEscapeChar ); Parameters aValue String to escape for SQL LIKE. aEscapeChar ...
...ed string that has characters that have special meaning escaped from aValue. Sample Code var statement = dbConn.createStatement( "SELECT * " + "FROM table_name " + "WHERE column_name LIKE :userInput ESCAPE '/'" ); statement.params.userInput = statement.escapeStringForLIKE(someUserInput, "/"); Binding Functions These functions are discussed in more detail with sample code in the overview document. newBindingParamsArray() Creates and returns a new mozIStorageBindingParamsArray object that can be used to bind multiple values to parameters in preparation for calling executeAsync(). mozIStorageBindingParamsArray newBindingParamsArray(); Parameters None. bindParameters() Binds all the parameters in the specified array to the statement in preparation for calling executeAsync(). Note: S...
...And 2 more matches
nsIAccessibleEvent
clients, which can be used to find out how to get accessibility and DOM interfaces for the event and its target. Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Attributes Attribute Type Description accessible nsIAccessible The nsIAccessible associated with the event. May return null if no accessible is available. Read only. accessibleDocument nsIAccessibleDocument The nsIAccessibleDocument that the event target nsIAccessible resides in. This can be used to get the DOM window, the DOM document and the window handler, among other things. Read only. DOMNode nsIDOMNode The nsIDOMNode associated with the event. May return null if accessible for event has been shut down. Read only. eventType unsigned long The type of event, based on th...
..._DIALOG_END 0x0025 0x0022 A dialog box has been closed. EVENT_SCROLLING_START 0x0026 0x0023 Scrolling has started on a scroll bar. EVENT_SCROLLING_END 0x0027 0x0024 Scrolling has ended on a scroll bar. EVENT_MINIMIZE_START 0x0028 0x0025 A window object is about to be minimized or maximized. EVENT_MINIMIZE_END 0x0029 0x0026 A window object has been minimized or maximized. ...
... EVENT_SCROLLING_START 0x0026 0x0023 Scrolling has started on a scroll bar. EVENT_SCROLLING_END 0x0027 0x0024 Scrolling has ended on a scroll bar. EVENT_MINIMIZE_START 0x0028 0x0025 A window object is about to be minimized or maximized. EVENT_MINIMIZE_END 0x0029 0x0026 A window object has been minimized or maximized. EVENT_DOCUMENT_LOAD_COMPLETE 0x002B 0x0027 The loading of the document has completed. EVENT_DOCUMENT_RELOAD 0x002C 0x0028 The document contents are being reloaded. EVENT_DOCUMENT_LOAD_STOPPED 0x002D 0x0029 The loading of the document was interrupted. EVENT_DOCUMENT_ATTRIBUTES_CHANGED 0x002E 0x002A The document wide attributes of the document object have changed. EVENT_DOCUMENT_CONTENT_CHANGED 0x002F 0x002B The contents of the document have changed. ...
...And 2 more matches
getFile
NS_OS_DESKTOP_DIR NS_MAC_TRASH_DIR "Trsh" NS_MAC_STARTUP_DIR "Strt" NS_MAC_SHUTDOWN_DIR "Shdwn" NS_MAC_APPLE_MENU_DIR "ApplMenu" NS_MAC_CONTROL_PANELS_DIR "CntlPnl" NS_MAC_EXTENSIONS_DIR "Exts" NS_MAC_FONTS_DIR "Fnts" NS_MAC_PREFS_DIR "Prfs" NS_MAC_DOCUMENTS_DIR "Docs" NS_MAC_INTERNET_SEARCH_DIR "ISrch" NS_OSX_HOME_DIR NS_OS_HOME_DIR NS_MAC_HOME_DIR NS_OS_HOME_DIR NS_MAC_DEFAULT_DOWNLOAD_DIR "DfltDwnld" NS_MAC_USER_LIB_DIR "ULibDir" // Only available under OS X NS_OSX_DEFAULT_DOWNLOAD_DIR "DfltDwnld" NS_OSX_USER_DESKTOP_DIR "UsrDsk...
...LT_DOWNLOAD_DIR "DfltDwnld" NS_MAC_USER_LIB_DIR "ULibDir" // Only available under OS X NS_OSX_DEFAULT_DOWNLOAD_DIR "DfltDwnld" NS_OSX_USER_DESKTOP_DIR "UsrDsk" NS_OSX_LOCAL_DESKTOP_DIR "LocDsk" NS_OSX_USER_APPLICATIONS_DIR "UsrApp" NS_OSX_LOCAL_APPLICATIONS_DIR "LocApp" NS_OSX_USER_DOCUMENTS_DIR "UsrDocs" NS_OSX_LOCAL_DOCUMENTS_DIR "LocDocs" NS_OSX_USER_INTERNET_PLUGIN_DIR "UsrIntrntPlgn" NS_OSX_LOCAL_INTERNET_PLUGIN_DIR "LoclIntrntPlgn" NS_OSX_USER_FRAMEWORKS_DIR "UsrFrmwrks" NS_OSX_LOCAL_FRAMEWORKS_DIR "LocFrmwrks" NS_OSX_USER_PREFERENCES_DIR "UsrPrfs" NS_OSX_LOCA...
... C constant String value Notes NS_WIN_WINDOWS_DIR "WinD" NS_WIN_PROGRAM_FI...
...And 2 more matches
nsIMacDockSupport
source/browser/base/content/browser.js#1562 This is seen here: If you were to copy and follow that example you would replace the default native menu. ...
...e like this: var dockSupport = Cc['@mozilla.org/widget/macdocksupport;1'].getService(Ci.nsIMacDockSupport); console.log('dockSupport:', dockSupport); var win = Services.wm.getMostRecentWindow('navigator:browser'); var macMenu = win.document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menupopup'); macMenu.setAttribute('id', 'myMacMenu'); var macMenuItem = win.document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem'); macMenuItem.setAttribute('label', 'Show Most Recent Window'); macMenuItem.setAttribute('id', 'myMacMenuItem'); macMenuItem.addEventListener('command', function(){ var dockSupport = Cc['@mozilla.org/widget/macdocksupport;1'].getService(Ci.nsIMacDockSupport); dockSupport.activateApplication(true); Se...
...em.setAttribute('label', 'Show Most Recent Window'); macMenuItem.setAttribute('id', 'myMacMenuItem'); macMenuItem.addEventListener('command', function(){ var dockSupport = Cc['@mozilla.org/widget/macdocksupport;1'].getService(Ci.nsIMacDockSupport); dockSupport.activateApplication(true); Services.wm.getMostRecentWindow(null).focus() }) macMenu.appendChild(macMenuItem); var mainPopupSet = win.document.getElementById('mainPopupSet'); mainPopupSet.appendChild(macMenu); let dockMenuElement = macMenu; //document.getElementById("menu_mac_dockmenu");66 let nativeMenu = Cc["@mozilla.org/widget/standalonenativemenu;1"].createInstance(Ci.nsIStandaloneNativeMenu); console.log('dockMenuElement:', dockMenuElement); nativeMenu.init(dockMenuElement); dockSupport.dockMenu = nativeMenu; This replaces the d...
...And 2 more matches
Address Book examples
} } Note: This method doesn't work with remote address books (e.g. LDAP). Hence the additional !ab.isRemote check How do I add/edit/delete contacts? Note: Not all address books can be written to. ...
...xtend the behavior of the address book. Load and save listeners Edit dialogs for both contacts and mailing lists expose functions for registering load and save listeners. For example, in order to register a load listener for a contact, the following should take place within the scope of the contact editor dialog: /* An example load listener for a contact * aCard the nsIAbCard being loaded * aDocument a reference to the contact editor document */ function foo(aCard, aDocument) { // Do something useful, like disabling // input fields that cards for this // address book type do not support. } RegisterLoadListener(foo); Save listeners are functions that take the same parameters, and can be registered with: RegisterSaveListener(foo); Load and save listeners can be unregistered using U...
...elopers to customize the behavior of the contact editor when loading or saving contact photos. This is useful if, for example, cards within your address book implementation need to save contact photos within a database. A photo handler defines the behavior of the contact editor for a particular photo type. Each photo handler must implement the following interface: /* * onLoad: function(aCard, aDocument): * Called when the editor wants to populate the contact editor * input fields with information about aCard's photo. Note that * this does NOT make aCard's photo appear in the contact editor - * this is left to the onShow function. Returns true on success. * If the function returns false, the generic photo handler onLoad * function will be called. * * onShow: function(aCard,...
...And 2 more matches
Autoconfiguration in Thunderbird
The goal of autoconfiguration is to make it very easy for users to configure the connection of Thunderbird to their email servers. In many cases, people should be able to download and install Thunderbird, enter their real name, email address and password in the Account Setup Wizard and have a fully functioning mail client and get and send their mail as securely as possible. See also: for instructions for users, see Automatic Account Configuration on the Thunderbird Knowledge Base. ...
... in the Account Setup Wizard and have a fully functioning mail client and get and send their mail as securely as possible. See also: for instructions for users, see Automatic Account Configuration on the Thunderbird Knowledge Base. the configuration file description and definition the original project page on the Mozilla wiki for background, design, implementation and project details This document describes how Autoconfiguration in Thunderbird works, and what to do to allow mail servers to be autoconfigured. Mechanisms Thunderbird gets the server settings via different means, each of which is intended for different cases: ISPDB The ISPDB is a central database, currently hosted by the Thunderbird project, but free to use for any client. It contains settings for the world's largest IS...
...the content to any requested domain. You must use a virtual host that match all autoconfig.* domains of your customers. In Apache terms, you can use a "ip-based virtual host". In the Apache configuration files, that means something like: Listen 10.2.3.4:80 (of course, you use a public IP address that you own) <VirtualHost 10.2.3.4:80> #Must be the first and only virtual host with this ip! DocumentRoot /var/www/autoconfig/ ServerName autoconfig.hoster.com <Directory /var/www/autoconfig> Order allow,deny allow from all </Directory> </VirtualHost> Place the configuration file at the URL /mail/config-v1.1.xml on that host. All config files must be served as Content-Type: text/xml (or application/xml), otherwise the file will be ignored. Also, they must use charset UTF-8 (esp. i...
...And 2 more matches
DOM Inspector - Firefox Developer Tools
DOM Inspector FAQ Answers to common questions on DOM Inspector. ...
... Documentation Introduction to DOM Inspector A guided tutorial that will help you get started with DOM Inspector. ...
... Documentation Introduction to DOM Inspector A guided tutorial that will help you get started with DOM Inspector. ...
...And 2 more matches
Index - Firefox Developer Tools
Development, Web Development:Tools Developer tools that are not built into Firefox, but ship as separate add-ons. 6 DOM Inspector DOM, DOM:Tools, DOM_Inspector, Extensions, Extensions:Tools, Themes, Themes:Tools, Tools, Web Development, Web Development:Tools, XUL, XUL:Tools The DOM Inspector (also known as DOMi) is a developer tool used to inspect, browse, and edit the Document Object Model of documents - usually web pages or XUL windows. The DOM hierarchy can be navigated using a two-paned window that allows a variety of different views on the document and all nodes within. 7 DOM Inspector FAQ DOM_Inspector The File menu contains approaches which will allow you to inspect a document. 8 DOM Inspector internals Code, Tools, internals, ...
...d using clip-path and also the CSS shape-outside property and <basic-shape> values. This guide walks you through all of the available options. 60 Edit fonts Fonts, Guide, Inspector, Tools, variable fonts This article provides a tour of the Font tools available in the Firefox DevTools. This tool contains several useful features for viewing and manipulating fonts applied to any document loaded in the browser including inspection of all fonts applied to the page, and precise adjustment of variable font axis values. 61 Examine Event Listeners Guide, Inspector, Tools The inspector shows the word "event" next to elements in the HTML Pane, that have event listeners bound to them: 62 Examine and edit CSS Guide, Inspector, Tools You can examine...
...s the developer tools that are built into Firefox. On OS X and Linux, it's under the "Tools" menu: 141 Tips Dev Tools, Tools, Web Development Screenshots: 142 Toolbox The Toolbox provides a single home for most of the developer tools that are built into Firefox. 143 Validators Tools, Website validator, html5 validator, validator This document lists different resources for developers to validate web pages. 144 View Source DevTools, Firefox, view page source View Source lets you look at the HTML or XML source for the page you're viewing. To activate View Source: 145 Web Audio Editor Firefox, Mozilla, Tools, Web Audio API With the Web Audio API, developers create an audio context. Within that con...
...And 2 more matches
AudioParam.linearRampToValueAtTime() - Web APIs
Time() is used to fade the gain value up to 1.0, and down to 0, respectively. This is pretty useful for fade in/fade out effects, although AudioParam.exponentialRampToValueAtTime() is often said to be a bit more natural. ...
... 1.0, and down to 0, respectively. This is pretty useful for fade in/fade out effects, although AudioParam.exponentialRampToValueAtTime() is often said to be a bit more natural. ...
...tty useful for fade in/fade out effects, although AudioParam.exponentialRampToValueAtTime() is often said to be a bit more natural. ...
...And 2 more matches
AudioParam.setTargetAtTime() - Web APIs
are pressed, setTargetAtTime() is used to fade the gain value up to 1.0, and down to 0, respectively, with the effect starting after 1 second, and the length of time the effect lasts being controlled by the timeConstant. ...
...ade the gain value up to 1.0, and down to 0, respectively, with the effect starting after 1 second, and the length of time the effect lasts being controlled by the timeConstant. ...
...espectively, with the effect starting after 1 second, and the length of time the effect lasts being controlled by the timeConstant. ...
...And 2 more matches
Transformations - Web APIs
ee in the next section. You can call the save() method as many times as you like. Each time the restore() method is called, the last saved state is popped off the stack and all saved settings are restored. A save and restore canvas state example This example tries to illustrate how the stack of drawing states functions by drawing a set of consecutive rectangles. ...
...little easier to understand and use. In the draw() function, we call the fillRect() function nine times using two for loops. In each loop, the canvas is translated, the rectangle is drawn, and the canvas is returned back to its original state. Note how the call to fillRect() uses the same coordinates each time, relying on translate() to adjust the drawing position. ...
...we will need to move the canvas by using the translate() method. A rotate example In this example, we'll use the rotate() method to first rotate a rectangle from the canvas origin and then from the center of the rectangle itself with the help of translate(). Reminder: Angles are in radians, not degrees. To convert, we are using: radians = (Math.PI/180)*degrees. ...
...And 2 more matches
CustomElementRegistry.define() - Web APIs
xamples Autonomous custom element The following code is taken from our popup-info-box-web-component example (see it live also). ...
...component example (see it live also). ...
...() { // Always call super first in constructor super(); // Create a shadow root var shadow = this.attachShadow({mode: 'open'}); // Create spans var wrapper = document.createElement('span'); wrapper.setAttribute('class','wrapper'); var icon = document.createElement('span'); icon.setAttribute('class','icon'); icon.setAttribute('tabindex', 0); var info = document.createElement('span'); info.setAttribute('class','info'); // Take attribute content and put it inside the info span var text = this.getAttribute('text'); info.textContent = text; // Insert icon var imgUrl; if(this.hasAttribute('img')) { imgUrl = this.getAttribute('img'); } else { imgUrl = 'img/default.png'; } var img = document.createElement('...
...And 2 more matches
DeprecationReportBody - Web APIs
Properties id A string representing the deprecated feature that generated the report, for example NavigatorGetUserMedia. This can be used to group reports by deprecated feature. ...
...on specified inside the constructor: observer.observe(); Because of the event handler we set up inside the ReportingObserver() constructor, we can now click the button to display the report details. ...
...erve(); Because of the event handler we set up inside the ReportingObserver() constructor, we can now click the button to display the report details. ...
...And 2 more matches
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
doesn't seem to care at all and just shows the words "Hello World!" as if these characters didn't exist at all: This is so that whitespace characters don't impact the layout of your page. Creating space around and inside elements is the job of CSS. What does happen to whitespace? They don't just disappear, however. ...
...ll: This is so that whitespace characters don't impact the layout of your page. Creating space around and inside elements is the job of CSS. What does happen to whitespace? They don't just disappear, however. Any whitespace characters that are outside of HTML elements in the original document are represented in the DOM. This is needed internally so that the editor can preserve formatting of documents. ...
...hey don't just disappear, however. Any whitespace characters that are outside of HTML elements in the original document are represented in the DOM. This is needed internally so that the editor can preserve formatting of documents. This means that: There will be some text nodes that contain only whitespace, and Some text nodes will have whitespace at the beginning or end. ...
...And 2 more matches
Element.getAttributeNS() - Web APIs
ecified attribute. If the attribute doesn't exist, the result is null. Note: Earlier versions of the DOM specification had this method described as returning an empty string for non-existent attributes, but it was not typically implemented this way since null makes more sense. The DOM4 specification now says this method should return null 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'; ...
...lue 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:test="http://www.example.com/2014/test" width="40" height="40"> <circle id...
...ince 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 requested attribute as being part of a particular namespace, as in the exam...
...And 2 more matches
Element.getElementsByClassName() - Web APIs
Syntax var elements = element.getElementsByClassName(names); Parameters names A DOMString containing one or more class names to match on, separated by whitespace. ...
... Syntax var elements = element.getElementsByClassName(names); Parameters names A DOMString containing one or more class names to match on, separated by whitespace. ...
... Syntax var elements = element.getElementsByClassName(names); Parameters names A DOMString containing one or more class names to match on, separated by whitespace. ...
...And 2 more matches
Element: mouseenter event - Web APIs
th deep hierarchies, the number of mouseenter events sent can be quite huge and cause significant performance problems. In such cases, it is better to listen for mouseover events. Combined with the corresponding mouseleave (which is fired at the element when the mouse exits its content area), the mouseenter event acts in a very similar way to the CSS :hover pseudo-class. Examples The mouseover documentation has an example illustrating the difference between mouseover and mouseenter. mouseenter The following trivial example uses the mouseenter 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> ...
...t. 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. ...
...seenter 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. ...
...And 2 more matches
Element: mouseleave event - Web APIs
each element of the hierarchy when leaving them. Here four events are sent to the four elements of the hierarchy when the pointer moves from the text to an area outside of the most outer div represented here. One single mouseout event is sent to the deepest element of the DOM tree, then it bubbles up the hierarchy until it is canceled by a handler or reaches the root. Examples The mouseout documentation has an example illustrating the difference between mouseout and mouseleave. mouseleave The following trivial example uses the mouseenter 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>...
... 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. ...
...enter 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. ...
...And 2 more matches
Event.target - Web APIs
Web › API › Event › target
rty of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event. Syntax const theTarget = someEvent.target; Value EventTarget Example The event.target property can be used in order to implement event delegation. ...
...a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event. Syntax const theTarget = someEvent.target; Value EventTarget Example The event.target property can be used in order to implement event delegation. ...
...nt was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event. Syntax const theTarget = someEvent.target; Value EventTarget Example The event.target property can be used in order to implement event delegation. ...
...And 2 more matches
GlobalEventHandlers.onanimationend - Web APIs
n reaches the end of its active period (which is calculated as animation-duration * animation-iteration-count) + animation-delay). Syntax var animEndHandler = target.onanimationend; target.onanimationend = Function Value A Function to be called when an animationend event occurs indicating that a CSS animation has begun on the target, where the target object is an HTML element (HTMLElement), document (Document), or window (Window). The function receives as input a single parameter: an AnimationEvent object describing the event which occurred. Example HTML content <div class="main"> <div id="box"> <div id="text">Box</div> </div> </div> <div class="button" id="play"> Play Animation </div> <pre id="log"></pre> CSS content :root { --boxwidth:50px; } .main { width: 300px; ...
...hat. 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. ...
...h occurred. ...
...And 2 more matches
GlobalEventHandlers.onanimationstart - Web APIs
An event handler for the animationstart event. This event is sent when a CSS Animation starts to play. Syntax var animStartHandler = target.onanimationstart; target.onanimationstart = Function Value A Function to be called when an animationstart event occurs indicating that a CSS animation has begun on the target, where the target object is an HTML element (HTMLElement), document (Document), or window (Window). The function receives as input a single parameter: an AnimationEvent object describing the event which occurred. Example HTML content <div class="main"> <div id="box"> <div id="text">Box</div> </div> </div> <div class="button" id="play"> Play Animation </div> <pre id="log"></pre> CSS content :root { --boxwidth:50px; } .main { width: 300px; height:300px; b...
...hat. 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. ...
...h occurred. ...
...And 2 more matches
HTMLCollection - Web APIs
Properties HTMLCollection.length Read only Returns the number of items in the collection. ...
... 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. ...
...lso 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 these. ...
...And 2 more matches
HTMLElement.focus() - Web APIs
element is the element which will receive keyboard and similar events by default. Syntax element.focus(options); // Object parameter Parameters options Optional An optional object providing options to control aspects of the focusing process. ...
... 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. ...
... Examples Focus on a text field JavaScript focusMethod = function getFocus() { document.getElementById("myTextField").focus(); } HTML <input type="text" id="myTextField" value="Text field."> <p></p> <button type="button" onclick="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 g...
...And 2 more matches
HTMLTableElement.insertRow() - Web APIs
The HTMLTableElement.insertRow() method inserts a new row (<tr>) in a given <table>, and returns a reference to the new row. If a table has multiple <tbody> elements, by default, the new row is inserted into the last <tbody>. To insert the row into a specific <tbody>: let specific_tbody = document.getElementById(tbody_id); let row = specific_tbody.insertRow(index) Note: insertRow() inserts the row directly into the table. The row does not need to be appended separately as would be the case if Document.createElement() had been used to create the new <tr> element. Syntax var newRow = HTMLTableElement.insertRow(index); HTMLTableElement is a reference to an HTML <table> element. Parameters index Optional The row index of the new row. If index is -1 or equal to the number of rows, the r...
...tion will result. If index is omitted it defaults to -1. Return value newRow is an HTMLTableRowElement that references the new row. Example This example uses insertRow(-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(). HTML <table id="my-table"> <tr><td>Row 1</td></tr> <tr><td>Row 2</td></tr> <tr><td>Row 3</td></tr> </table> JavaScript function addRow(tableID) { // Get a reference to the table let tableRef = document.getElementById(tableID); // Insert a row at the end of the table let newRow = tableRef.insertRow(-1); // Insert a cell in the row at i...
... Living Standard Document Object Model (DOM) Level 2 HTML SpecificationThe definition...
...And 2 more matches
HTMLTextAreaElement - Web APIs
ault value, which behaves like the Node.textContent property. disabled boolean: Returns / Sets the element's disabled attribute, indicating that the control is not available for interaction. form Read only object: Returns a reference to the parent form element. If this element is not contained in a form element, it can be the id attribute of any <form> element in the same document or the value null. inputMode maxLength long: Returns / Sets the element's maxlength attribute, indicating the maximum number of characters the user can enter. This constraint is evaluated only when the value changes. minLength long: Returns / Sets the element's minlength attribute, indicating the minimum number of characters the user can enter. This constrai...
...index of the beginning of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if setSelectionRange() had been called with this as the first argument, and selectionEnd as the second argument. tabIndex long: Returns / Sets the position of the element in the tabbing navigation order for the current document. textLength Read only long: Returns the codepoint length of the control's value. Same as reading value.length type Read only string: Returns the string textarea. validationMessage Read only string: Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a...
...ieldset> <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. ...
...And 2 more matches
Ajax navigation example - Web APIs
="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(); } function ajaxError () { alert("Unknown error."); } function ajaxLoad () { var vMsg, nStatus = this.status; switch (nStatus) { case 200: vMsg = JSON.parse(t...
... bIsLoading = false; } function abortReq () { if (!bIsLoading) { return; } oReq.abort(); closeReq(); } function ajaxError () { alert("Unknown error."); } function ajaxLoad () { var vMsg, nStatus = this.status; switch (nStatus) { case 200: vMsg = JSON.parse(this.responseText); document.title = oPageInfo.title = vMsg.page; document.getElementById(sTargetId).innerHTML = vMsg.content; if (bUpdateURL) { history.pushState(oPageInfo, oPageInfo.title, oPageInfo.url); bUpdateURL = false; } break; default: vMsg = nStatus + ": " + (oHTTPStatus[nStatus] || "U...
...tMark, ""); } function getPage (sPage) { if (bIsLoading) { return; } oReq = new XMLHttpRequest(); bIsLoading = true; oReq.onload = ajaxLoad; oReq.onerror = ajaxError; if (sPage) { oPageInfo.url = filterURL(sPage, null); } oReq.open("get", filterURL(oPageInfo.url, "json"), true); oReq.send(); oLoadingBox.parentNode || document.body.appendChild(oLoadingBox); } function requestPage (sURL) { if (history.pushState) { bUpdateURL = true; getPage(sURL); } else { /* Ajax navigation is not supported */ location.assign(sURL); } } function processLink () { if (this.className === sAjaxClass) { requestPage(this.href); ...
...And 2 more matches
Working with the History API - Web APIs
HTML5 introduced the pushState() and replaceState() methods for add and modifying history entries, respectively. These methods work in conjunction with the onpopstate 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.h...
...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 history.state will contain the stateObj. The popstate event won't be fired because the page has been reloaded. The page itself will look like bar.html. If the user clicks Back once again, the URL will change to http://mozilla.org/foo.html, and the document will get a popstate event, this time with a null state object. Here too, going back doesn't change the document's contents from what they were in the previous step, although the document might update its contents manually upon receiving the popstate event. Note: Calling history.back() normally behaves the same way as clicking the Back button. But there is one important exception: After using h...
...after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL. Note: In Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) 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. In a sense,...
...And 2 more matches
ImageCapture - Web APIs
shows, roughly, a MediaStreamTrack extracted from a device's MediaStream. The track is then used to create an ImageCapture object so that takePhoto() and grabFrame() can be called. Finally, it shows how to apply the results of these calls to a canvas object. ...
...nClick() { navigator.mediaDevices.getUserMedia({video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; const track = mediaStream.getVideoTracks()[0]; imageCapture = new ImageCapture(track); }) .catch(error => console.log(error)); } function onGrabFrameButtonClick() { imageCapture.grabFrame() .then(imageBitmap => { const canvas = document.querySelector('#grabFrameCanvas'); drawCanvas(canvas, imageBitmap); }) .catch(error => console.log(error)); } function onTakePhotoButtonClick() { imageCapture.takePhoto() .then(blob => createImageBitmap(blob)) .then(imageBitmap => { const canvas = document.querySelector('#takePhotoCanvas'); drawCanvas(canvas, imageBitmap); }) .catch(error => console.log(error)); } /* U...
... Working Draft Initial definition. ...
...And 2 more matches
Location - Web APIs
Web › API › Location
The Location interface represents the location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to. Both the Document and Window interface have such a linked Location, accessible via Document.location and Window.location respectively. Anatomy Of Location HTML <span id="href" title="href"><span id="protocol" title="protocol">http:</span>//<span id="host" title="host"><span id="hostname" title="hostname">example.org</span>:<span id="port" title="port">8888</span></span><span id="pathname" title="pathname">/foo/bar</span><span id="search" title="search">?q=baz</span><span id="hash" title="hash">#bang</span></span> CSS html, body {height:100%;} html {display:table; width:100%;} body {display:table-cell; text-align:center; vertical-align:middle; font-...
...bsolute; 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.stopPropagation(); window.location.h...
... $(this).attr('id'); }); }); [].forEach.call(document.querySelectorAll('[title]'), function (node) { node.addEventListener("click", function(e) { e.preventDefault(); e.stopPropagation(); window.location.hash = ''; }); }); Result Properties Location.ancestorOrigins Is a static DOMStringList containing, in reverse order, the origins of all ancestor browsing contexts of the document associated with the given Location object. Location.href Is a stringifier that returns a USVString containing the entire URL. If changed, the associated document navigates to the new page. It can be set from a different origin than the associated document. Location.protocol Is a USVString containing the protocol scheme of the URL, including the final ':'. Location.host Is a USVString contai...
...And 2 more matches
MouseEvent.initMouseEvent() - Web APIs
This method must be called to set the event before it is dispatched, using EventTarget.dispatchEvent(). Once dispatched, it doesn't do anything anymore. Do not use this method anymore as it is deprecated. Instead use specific event constructors, like MouseEvent(). The page on Creating and triggering events gives more information about the way to use these. ...
...r 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. ...
... button. relatedTarget the event's related EventTarget. Only used with some event types (e.g., mouseover and mouseout). In other cases, pass null. ...
...And 2 more matches
MouseEvent.pageX - Web APIs
Web › API › MouseEvent › pageX
The pageX read-only property of the MouseEvent interface returns the X (horizontal) coordinate (in pixels) at which the mouse was clicked, relative to the left edge of the entire document. This includes any portion of the document not currently visible. Being based on the edge of the document as it is, this property takes into account any horizontal scrolling of the page. For example, if the page is scrolled such that 200 pixels of the left side of the document are scrolled out of view, and the mouse is clicked 100 pixels inward from the left edge of the view, the value returned by pageX will be 300. Originally, this property was defined as a long integer. The CSSOM View Module redefined it as a double float. See the Browser compatibility section for details. See Page in Coordinate systems for...
...y pageX will be 300. Originally, this property was defined as a long integer. The CSSOM View Module redefined it as a double float. See the Browser compatibility section for details. See Page in Coordinate systems for some additional information about coordinates specified in this fashion. Syntax var pageX = MouseEvent.pageX; Value A floating-point number of pixels from the left edge 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...
...re 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. ...
...And 2 more matches
MouseEvent - Web APIs
osition of the last mousemove event. MouseEvent.offsetX Read only The X coordinate of the mouse pointer relative to the position of the padding edge of the target node. MouseEvent.offsetY Read only The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node. MouseEvent.pageX Read only The X coordinate of the mouse pointer relative to the whole document. MouseEvent.pageY Read only The Y coordinate of the mouse pointer relative to the whole document. MouseEvent.region Read only Returns the id of the hit region affected by the event. If no hit region is affected, null is returned. MouseEvent.relatedTarget Read only The secondary target for the event, if there is one. MouseEvent.screenX Read only The X coordinate of the mouse point...
...ple This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods. ...
...lateClick() { var evt = new MouseEvent("click", { bubbles: true, cancelable: true, view: window }); var cb = document.getElementById("checkbox"); //element to click on var canceled = !cb.dispatchEvent(evt); if(canceled) { // A handler called preventDefault alert("canceled"); } else { // None of the handlers called preventDefault alert("not canceled"); } } document.getElementById("button").addEventListener('click', simulateClick); Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'MouseEvent' in that specification. Working Draft Redefines MouseEvent from long to double. This means that a PointerEvent whose pointerType is mouse will be a double. Pointer Loc...
...And 2 more matches
Node.baseURI - Web APIs
Web › API › Node › baseURI
The baseURI read-only property returns the absolute base URL of a Node. The base URL is used to resolve relative URLs when the browser needs to obtain an absolute URL, for example when processing the HTML <img> element's src attribute or XML xlink:href attribute. In most cases the base URL is simply the location of the document, but it can be affected by many factors, including the <base> element in HTML and the xml:base attribute in XML. ...
...nt, but it can be affected by many factors, including the <base> element in HTML and the xml:base attribute in XML. Syntax var nodeBaseURI = node.baseURI; Value A DOMString representing the base URL of the specified Node. It may be null if unable to obtain an absolute URI. Although this property is read-only, its value may change in certain situations (see below). Details The base URL of a document The base URL of a document defaults to the document's address (as displayed by the browser and available in window.location), but it can be changed: When an HTML <base> tag is found in the document When the document is new (created dynamically) See the Base URLs section of the HTML Living standard for details. You can use document.baseURI to obtain the base URL of a document. Note that ob...
...t defaults to the document's address (as displayed by the browser and available in window.location), but it can be changed: When an HTML <base> tag is found in the document When the document is new (created dynamically) See the Base URLs section of the HTML Living standard for details. You can use document.baseURI to obtain the base URL of a document. Note that obtaining the base URL for a document may return different URLs over time if the <base> tags or the document's location change. The base URL of an element The base URL of an element in HTML normally equals the base URL of the document the node is in. ...
...And 2 more matches
Node.cloneNode() - Web APIs
Web › API › Node › cloneNode
deep Optional* If true, then node and its whole subtree--including text that may be in child Text nodes--is also copied. ...
... deep Optional* If true, then node and its whole subtree--including text that may be in child Text nodes--is also copied. ...
...aults to false. You should always provide an explicit value for backward and forward compatibility. With Gecko 28.0 (Firefox 28 / Thunderbird 28 / SeaMonkey 2.25 / Firefox OS 1.3)), the console warned developers not to omit the argument. Starting with Gecko 29.0 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26)), a shallow clone is defaulted instead of a deep clone. Example let p = document.getElementById("para1") let p_prime = p.cloneNode(true) Notes Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties (e.g., node.onclick = someFunction). Additionally, for a <canvas> element, the painted image is not copied. Warning: cloneNode...
...And 2 more matches
Node.getRootNode() - Web APIs
Web › API › Node › getRootNode
g the root node. The available options are: composed: A Boolean that indicates whether the shadow root should be returned (false, the default), or a root node beyond shadow root (true). Returns An object inheriting from Node. This will differ in exact form depending on where you called getRootNode(); for example: Calling it on an element inside a standard web page will return an HTMLDocument object representing the entire page. Calling it on an element inside a shadow DOM will return the associated ShadowRoot. Examples The first simple example returns a reference to the HTML/document node: rootNode = node.getRootNode(); This more complex example shows the difference between returning a normal root, and a root incuding the shadow root. (See the full source code): <!-- source: h...
...complex example shows the difference between returning a normal root, and a root incuding the shadow root. ...
...ng a normal root, and a root incuding the shadow root. ...
...And 2 more matches
Node.isConnected - Web APIs
Web › API › Node › isConnected
Syntax var isItConnected = nodeObjectInstance.isConnected Return value A Boolean that is true if the node is connected to its relevant context object, and false if not. ...
...nnected (directly or indirectly) to the context object, for example the Document object in the case of the normal DOM, or the ShadowRoot in the case of a shadow DOM. Syntax var isItConnected = nodeObjectInstance.isConnected Return value A Boolean that is true if the node is connected to its relevant context object, and false if not. ...
...ent object in the case of the normal DOM, or the ShadowRoot in the case of a shadow DOM. Syntax var isItConnected = nodeObjectInstance.isConnected Return value A Boolean that is true if the node is connected to its relevant context object, and false if not. ...
...And 2 more matches
Node.setUserData() - Web APIs
Web › API › Node › setUserData
e that such data will not be preserved when imported via Node.importNode, as with Node.cloneNode() and Node.renameNode() operations (though Node.adoptNode does preserve the information), and equality tests in Node.isEqualNode() do not consider user data in making the assessment. This method offers the convenience of associating data with specific nodes without needing to alter the structure of a document and in a standard fashion, but it also means that extra steps may need to be taken if one wishes to serialize the information or include the information upon clone, import, or rename operations. The Node.getUserData and Node.setUserData methods are no longer available from Web content. HTMLElement.dataset or WeakMap can be used instead. Syntax var prevUserData = someNode.setUserData(userKey,...
...clone operation), the user key, the data on the node, the source node (null if being deleted), the destination node (the newly created node or null if none).If no handler is desired, one must specify null. userData is the object to associate to userKey on someNode. If null, any previously registered object and UserDataHandler associated to userKey on this node will be removed. ...
..., the data on the node, the source node (null if being deleted), the destination node (the newly created node or null if none).If no handler is desired, one must specify null. userData is the object to associate to userKey on someNode. If null, any previously registered object and UserDataHandler associated to userKey on this node will be removed. ...
...And 2 more matches
PerformanceNavigationTiming.domComplete - Web APIs
Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
...And 2 more matches
PerformanceNavigationTiming.domInteractive - Web APIs
Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
...And 2 more matches
PluginArray - Web APIs
uginArray objects are no longer enumerable in the latest browser versions. Properties PluginArray.lengthRead only The number of plugins in the array. Methods PluginArray.item Returns the Plugin at the specified index into the array. PluginArray.namedItem Returns the Plugin with the specified name. ...
...ay. Methods PluginArray.item Returns the Plugin at the specified index into the array. PluginArray.namedItem Returns the Plugin with the specified name. PluginArray.refresh Refreshes all plugins on the current page, optionally reloading documents. Examples The following example function returns the version of the Shockwave Flash plugin. ...
...ionally reloading documents. Examples The following example function returns the version of the Shockwave Flash plugin. ...
...And 2 more matches
Using Pointer Events - Web APIs
<br> <button onclick="startup()">Initialize</button> <br> Log: <pre id="log" style="border: 1px solid #ccc;"></pre> Setting up the event handlers When the page loads, the startup() function shown below should be called by our <body> element's onload attribute (but in the example we use a button to trigger it, due to limitations of the MDN live example system). ...
...all the event listeners for our <canvas> element so we can handle the touch events as they occur. Tracking new touches We'll keep track of the touches in-progress. var ongoingTouches = new Array(); When a pointerdown event occurs, indicating that a new touch on the surface has occurred, the handleStart() function below is called. ...
...4 pixel radius circle will show up neatly. Drawing as the pointers move Each time one or more pointers moves, a pointermove event is delivered, resulting in our handleMove() function being called. Its responsibility in this example is to update the cached touch information and to draw a line from the previous position to the current position of each touch. ...
...And 2 more matches
Range.createContextualFragment() - Web APIs
In the HTML case, if the context node would be html, for historical reasons the fragment parsing algorithm is invoked with body as the context instead. Syntax documentFragment = range.createContextualFragment(tagString) Parameters tagString Text that contains text and tags to be converted to a document fragment. ...
...g algorithm or the XML fragment parsing algorithm with the start of the range (the parent of the selected node) as the context node. The HTML fragment parsing algorithm is used if the range belongs to a Document whose HTMLness bit is set. In the HTML case, if the context node would be html, for historical reasons the fragment parsing algorithm is invoked with body as the context instead. ...
...fragment parsing algorithm is used if the range belongs to a Document whose HTMLness bit is set. In the HTML case, if the context node would be html, for historical reasons the fragment parsing algorithm is invoked with body as the context instead. Syntax documentFragment = range.createContextualFragment(tagString) Parameters tagString Text that contains text and tags to be converted to a document fragment. ...
...And 2 more matches
Range.setStart() - Web APIs
Web › API › Range › setStart
The Range.setStart() method sets the start position of a Range. If the startNode is a Node of type Text, Comment, or CDataSection, then startOffset is the number of characters from the start of startNode. For other Node types, startOffset is the number of child nodes between the start of the startNode. Setting the start point below (lower in the document) the end point will result in a collapsed range with the start and end points both set to the specified start position. Syntax range.setStart(startNode, startOffset); Parameters startNode The Node where the Range should start. startOffset An integer greater than or equal to zero representing the offset for the start of the Range from the start of startNode. Examples Highlight part of an element This example 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; // End at fifth node: Dodge ...
...s'); 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; // End at fifth node: Dodge City, KS const range = document.createRange(); range.setStart(address, startOffset); 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. HTML ...
...And 2 more matches
Range - Web APIs
Web › API › Range
A range can be created by using the Document.createRange() method. Range objects can also be retrieved by using the getRangeAt() method of the Selection object or the caretRangeFromPoint() method of the Document object. There also is the Range() constructor available. Properties There are no inherited properties. Range.collapsed Read only Returns a Boolean indicating whether the range's start and end points are at the same position. Range.commonAncestorContainer Read only Returns the deepest Node that contains the startContainer and endContainer nodes. Range.endContainer Read only Returns the Node within which the Range ends. ...
...urns the Node within which the Range ends. Range.endOffset Read only Returns a number representing where in the endContainer the Range ends. Range.startContainer Read only Returns the Node within which the Range starts. Range.startOffset Read only Returns a number representing where in the startContainer the Range starts. Constructor Range() Returns a Range object with the global Document as its start and end. Methods There are no inherited methods. Range.setStart() Sets the start position of a Range. Range.setEnd() Sets the end position of a Range. Range.setStartBefore() Sets the start position of a Range relative to another Node. Range.setStartAfter() Sets the start position of a Range relative to another Node. Range.setEndBefore() Sets the end position of a Range...
...) Sets the end position of a Range relative to another Node. Range.setEndAfter() Sets the end position of a Range relative to another Node. Range.selectNode() Sets the Range to contain the Node and its contents. Range.selectNodeContents() Sets the Range to contain the contents of a Node. Range.collapse() Collapses the Range to one of its boundary points. Range.cloneContents() Returns a DocumentFragment copying the nodes of a Range. Range.deleteContents() Removes the contents of a Range from the Document. Range.extractContents() Moves contents of a Range from the document tree into a DocumentFragment. Range.insertNode() Insert a Node at the start of a Range. Range.surroundContents() Moves content of a Range into a new Node. Range.compareBoundaryPoints() Compares the boundary po...
...And 2 more matches
Report - Web APIs
Web › API › Report
ports currently contained in the observer's report queue. By sending requests to the endpoints defined via the Report-To HTTP header. Properties Report.body Read only The body of the report, which is a ReportBody object containing the detailed report information. Report.type Read only The type of report generated, e.g. deprecation or intervention. Report.url Read only The URL of the document that generated the report. Methods This interface has no methods defined on it. Events This interface has no events that fire on it. Examples In our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(report...
...on specified inside the constructor: observer.observe(); Because of the event handler we set up inside the ReportingObserver() constructor, we can now click the button to display the report details. ...
...erve(); Because of the event handler we set up inside the ReportingObserver() constructor, we can now click the button to display the report details. ...
...And 2 more matches
ResizeObserver - Web APIs
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. ...
...sing 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. ...
...is 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. ...
...And 2 more matches
Screen Wake Lock API - Web APIs
ern devices do this to save on battery power. Whilst this is a useful feature, some applications need the screen to stay awake to be their most useful. The Screen Wake Lock API prevents the screen from turning off, dimming or locking. It allows for a simple platform based solution which up until now could only be achieved via workarounds which were potentially power hungry. Only visible (active) documents can acquire the screen wake lock. There are plenty of use cases for keeping a screen on, including reading an ebook, map navigation, following a recipe, presenting to an audience, scanning a QR/barcode or applications that use voice or gesture control, rather than tactile input (the default way to keep a screen awake). You acquire a WakeLockSentinel object by calling the navigator.wakeLock.req...
...e or applications that use voice or gesture control, rather than tactile input (the default way to keep a screen awake). You acquire a WakeLockSentinel object by calling the navigator.wakeLock.request() Promise based method that resolves if the platform allows it. A request may be rejected for a number of reasons, including system settings (such as power save mode or low battery level) or if the document is not active or visible. The sentinel is attached to the underlying system wake lock. It can be released by the system, again if the battery power is too low or the document is not active or visible. It can also be released manually via the WakeLockSentinel.release() method. It is good practice to store a reference to the sentinel object to control release later and also to reacquire the lock i...
...or wake lock release This example updates the UI if the wake lock has been released for any reason (such as navigating away from the active window/tab). wakeLock.addEventListener('release', () => { // the wake lock has been released statusElem.textContent = 'Wake Lock has been released'; }); Reacquiring a wake lock The following code reacquires the wake lock should the visibility of the document change and the wake lock is released. document.addEventListener('visibilitychange', () => { if (wakeLock !== null && document.visibilityState === 'visible') { wakeLock = await navigator.wakeLock.request('screen'); } }); Putting it all together You can find the complete code on github here. The demo uses a button to acquire a wake lock and also release it, which in turn updates the UI. ...
...And 2 more matches
SecurityPolicyViolationEvent - Web APIs
The SecurityPolicyViolationEvent interface inherits from Event, and represents the event object of an event sent on a document or worker when its content security policy is violated. Constructor SecurityPolicyViolationEvent() Creates a new SecurityPolicyViolationEvent object instance. Properties SecurityPolicyViolationEvent.blockedURIRead only A USVString representing the URI of the resource that was blocked because it violates a policy. SecurityPolicyViolationEvent.columnNumberRead only The column number in the document or worker at which the violation occurred. ...
...e URI of the resource that was blocked because it violates a policy. SecurityPolicyViolationEvent.columnNumberRead only The column number in the document or worker at which the violation occurred. SecurityPolicyViolationEvent.dispositionRead only Indicates how the violated policy is configured to be treated by the user agent. This will be "enforce" or "report". SecurityPolicyViolationEvent.documentURIRead only A USVString representing the URI of the document or worker in which the violation was found. SecurityPolicyViolationEvent.effectiveDirectiveRead only A DOMString representing the directive whose enforcement uncovered the violation. SecurityPolicyViolationEvent.lineNumberRead only The line number in the document or worker at which the violation occurred. SecurityPolicyViolatio...
...PolicyViolationEvent.sampleRead only A DOMString representing a sample of the resource that caused the violation, usually the first 40 characters. This will only be populated if the resource is an inline script, event handler, or style -- external resources causing a violation will not generate a sample. ...
...And 2 more matches
Storage - Web APIs
Web › API › Storage
a function called setStyles() that grabs the data items using Storage.getItem() and uses those values to update page styles. If it doesn't, we run another function, populateStorage(), which uses Storage.setItem() to set the item values, then runs setStyles(). ...
...tem() and uses those values to update page styles. If it doesn't, we run another function, populateStorage(), which uses Storage.setItem() to set the item values, then runs setStyles(). ...
... another function, populateStorage(), which uses Storage.setItem() to set the item values, then runs setStyles(). ...
...And 2 more matches
Using the Storage Access API - Web APIs
We'll briefly look at a common storage access scenario. Usage notes The Storage Access API is designed to allow embedded content to request access to storage that would otherwise be blocked when a user's browser is set to block all third-party cookies. Since embedded content won't know which storage policy is in use by the user, it's best to always check whether the embedded frame has storage access before attempting to read or write from storage. ...
...cess API is designed to allow embedded content to request access to storage that would otherwise be blocked when a user's browser is set to block all third-party cookies. Since embedded content won't know which storage policy is in use by the user, it's best to always check whether the embedded frame has storage access before attempting to read or write from storage. This is particularly true for Document.cookie access, as browsers will often return an empty cookie jar when third-party cookies are blocked. Accessing a user's cookies in an embedded cross-origin iframe In this example we show how an embedded cross-origin <iframe> can access a user's cookies under a storage access policy that blocks third-party cookies. First of all, if the <iframe> is sandboxed, the embedding website needs to add...
...-by-user-activation sandbox token to allow storage access requests to be successful, along with allow-scripts and allow-same-origin to allow it to call the API, and execute in an origin that can have cookies: <iframe sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"> ... </iframe> Now on to the code executed inside the embedded document. ...
...And 2 more matches
Storage Access API - Web APIs
entirely. As a consequence, users who wish to continue to interact with embedded content are forced to greatly relax their blocking policy for resources loaded from all embedded origins and possibly across all websites. The Storage Access API is intended to solve this problem; embedded cross-origin content can request unrestricted access to its first-party storage on a site-by-site basis via the Document.requestStorageAccess() method, and check whether it already has access via the Document.hasStorageAccess() method. In addition, sandboxed <iframe>s cannot be granted storage access by default for security reasons. The API therefore also adds the allow-storage-access-by-user-activation sandbox token. The embedding website needs to add this to allow storage access requests to be successful, along ...
..."). The browser may decide to involve the user in the decision of whether to grant an incoming storage access request. Specifics regarding the lifetime of a storage grant and the circumstances under which the browser may decide to inform the user are currently being worked through and will be announced once ready. User prompts When requestStorageAccess() is called by an embedded, cross-origin document, the user agent may choose to involve the user in the decision of whether to grant storage access to the requesting origin. Prompting heuristics currently vary across the two implementers of the Storage Access API -- Safari shows prompts for all embedded tracking content that has not previously received storage access, while Firefox only prompts users after a tracking origin has requested storage...
... decision of whether to grant storage access to the requesting origin. Prompting heuristics currently vary across the two implementers of the Storage Access API -- Safari shows prompts for all embedded tracking content that has not previously received storage access, while Firefox only prompts users after a tracking origin has requested storage access on more than a threshold number of sites. See Document.requestStorageAccess() for more details. Safari implementation differences Although the API surface is the same, websites using the Storage Access API should expect differences in the level and extent of storage access they receive between Firefox and Safari. This is caused by differences in the storage access policies implemented in the two browsers. Design properties unique to Firefox are sum...
...And 2 more matches
A simple RTCDataChannel sample - Web APIs
in 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 simplify syntax. Starting up When the script is run, we set up an load event listener, so that once the page is fully loaded, our startup() function is called. ...
... already read up on this functionality of ECMAScript 2015, you should read up on them. Similarly, this example uses arrow functions to simplify syntax. Starting up When the script is run, we set up an load event listener, so that once the page is fully loaded, our startup() function is called. ...
...ou should read up on them. Similarly, this example uses arrow functions to simplify syntax. Starting up When the script is run, we set up an load event listener, so that once the page is fully loaded, our startup() function is called. ...
...And 2 more matches
Example and tutorial: Simple synth keyboard - Web APIs
oscList is set up to be ready to contain a list of all currently-playing oscillators. It starts off empty, since there are none playing yet. masterGainNode is set to null; during the setup process, it will be configured to contain a GainNode which all playing oscillators will connect to and play through to allow the overall volume to be controlled using a single slider control. let keyboard = document.querySelector(".keyboard"); let wavePicker = document.querySelector("select[name='waveform']"); let volumeControl = document.querySelector("input[name='volume']"); References to elements we'll need access to are obtained: keyboard is the container element into which the keys will be placed. wavePicker is the <select> element used to choose the waveform to use for the notes. volumeControl i...
...nNode = audioContext.createGain(); masterGainNode.connect(audioContext.destination); masterGainNode.gain.value = volumeControl.value; // Create the keys; skip any that are sharp or flat; for // our purposes we don't need them. Each octave is inserted // into a <div> of class "octave". ...
...into a <div> of class "octave". ...
...And 2 more matches
window.location - Web APIs
Web › API › Window › location
The window.location read-only property returns a Location object with information about the current location of the document. Though window.location is a read-only Location object, you can also assign a DOMString to it. This means that you can work with location as if it were a string in most cases: location = 'http://www.example.com' is a synonym of location.href = 'http://www.example.com'. See Location for all available properties. Syntax var oldLocation = location; location = newLocation; Examples Basic Example alert(location); // alerts "/docs/Web/API/Window/location" Example #1: Navigate to a new page Whenever a new value is assigned to the location object, a document will be loaded using the URL as if location.assign() had been called with the modified URL. Note that security sett...
...l: <button onclick="showLoc();">Show location properties</button> Example #5: Send a string of data to the server by modifying the search property: function sendData (sData) { location.search = sData; } // in html: <button onclick="sendData('Some data');">Send data</button> The current URL with "?Some%20data" appended is sent to the server (if no action is taken by the server, the current document is reloaded with the modified search string). Example #6: Using bookmarks without changing the hash property: <!doctype html> <html> <head> <meta charset="UTF-8"/> <title>MDN Example</title> <script> function showNode (oNode) { document.documentElement.scrollTop = oNode.offsetTop; document.documentElement.scrollLeft = oNode.offsetLeft; } function showBookmark (sBookmark, bUseHash) { if (...
...Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Qu...
...And 2 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
e 2: Alternating two colors The following example calls the flashtext() function once a second until the Stop button is pressed. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>setInterval/clearInterval example</title> <script> var nIntervId; function changeColor() { nIntervId = setInterval(flashText, 1000); } function flashText() { var oElem = document.getElementById('my_box'); oElem.style.color = oElem.style.color == 'red' ? 'blue' : 'red'; // oElem.style.color == 'red' ? 'blue' : 'red' is a conditional or ternary operator. } function stopTextColor() { clearInterval(nIntervId); } </script> </head> <body onload="changeColor();"> <div id="my_box"> <p>Hello World</p> </div> <button onclick="stopTextCol...
... nChild < this.parts.length; nChild++) { oNode.removeChild(this.parts[nChild]); this.parts[nChild] = new Sheet(this.parts[nChild]); } } var nIntervId, oCurrent = null, bTyping = false, bStart = true, nIdx = 0, sPart = "", aSheets = [], aMap = []; this.rate = nRate || 100; this.play = function () { if (bTyping) { return; } if (bStart) { var aItems = document.querySelectorAll(sSelector); if (aItems.length === 0) { return; } for (var nItem = 0; nItem < aItems.length; nItem++) { aSheets.push(new Sheet(aItems[nItem])); /* Uncomment the following line if you have previously hidden your elements via CSS: */ // aItems[nItem].style.visibility = "visible"; } bStart = false; } nIntervId = setInterval(t...
...ML5 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); |*| \*/ if (document.all && !window.setTimeout.isPolyfill) { var __nativeST__ = window.setTimeout; window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { var aArgs = Array.prototype.slice.call(arguments, 2); return __nativeST__(vCallback instanceof Function ? function () { vCallback.apply(null, aArgs); } : vCallback, nDelay); }; window.setTimeout.isP...
...And 2 more matches
Using XMLHttpRequest - Web APIs
of requests can be found on the synchronous and asynchronous requests page. Do not use synchronous requests outside Web Workers. Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience. Note: The constructor function XMLHttpRequest isn't limited to only XML documents. It starts with "XML" because when it was created the main format that was originally used for Asynchronous Data Exchange were XML Handling responses There are several types of response attributes defined by the living standard specification for the XMLHttpRequest() constructor. These tell the client making the XMLHttpRequest important information about the status of the response. Some cases w...
...ation for the XMLHttpRequest() constructor. These tell the client making the XMLHttpRequest important information about the status of the response. Some cases where dealing with non-text response types may involve some manipulation and analysis are outlined in the following sections. Analyzing and manipulating the responseXML property If you use XMLHttpRequest to get the content of a remote XML document, the responseXML property will be a DOM object containing a parsed XML document. This could prove difficult to manipulate and analyze. There are four primary ways of analyzing this XML document: Using XPath to address (or point to) parts of it. Manually Parsing and serializing XML to strings or objects. Using XMLSerializer to serialize DOM trees to strings or to files. RegExp can be used if...
...You might want to remove line breaks, if you use RegExp to scan with regard to line breaks. However, this method is a "last resort" since if the XML code changes slightly, the method will likely fail. Note: XMLHttpRequest can now interpret HTML for you using the responseXML property. ...
...And 2 more matches
Generating HTML - Web APIs
Generating HTML One common application of XSLT in the browser is to transform XML into HTML on the client. The second example will transform the input document (example2.xml), which again contains information about an article, into an HTML document. The <body> element of the article now contains HTML elements (a <b> and <u> tag, see figure 2). The XML document contains both HTML elements and XML elements, but only one namespace is needed, namely for the XML elements. Since there is no HTML namespace, and using the XHTML namespace would force the XSL to create an XML document that would not behave like a HTML document, the xsl:output in the XSL Stylesheet will make sure the resulting document will be handled as HTML. For the XML elements, our own namespace is needed, http://devedge.netscape.com/...
...te an XML document that would not behave like a HTML document, the xsl:output in the XSL Stylesheet will make sure the resulting document will be handled as HTML. For the XML elements, our own namespace is needed, http://devedge.netscape.com/2002/de, and it is given the prefix myNS (xmlns:myNS="http://devedge.netscape.com/2002/de"). Figure 2 XML file :(example2.xml)view example | view source XML Document (example2.xml): <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="example2.xsl"?> <myNS:Article xmlns:myNS="http://devedge.netscape.com/2002/de"> <myNS:Title>My Article</myNS:Title> <myNS:Authors> <myNS:Author company="Foopy Corp.">Mr. Foo</myNS:Author> <myNS:Author>Mr. Bar</myNS:Author> </myNS:Authors> <myNS:Body> The <b>rain</b> in <u>Spain</u> st...
...le> <myNS:Authors> <myNS:Author company="Foopy Corp.">Mr. Foo</myNS:Author> <myNS:Author>Mr. Bar</myNS:Author> </myNS:Authors> <myNS:Body> The <b>rain</b> in <u>Spain</u> stays mainly in the plains. </myNS:Body> </myNS:Article> The XSL Stylesheet used will need to have two namespaces - one for the XSLT elements and one for our own XML elements used in the XML document. The output of the XSL Stylesheet is set to HTML by using the xsl:output element. By setting the output to be HTML and not having a namespace on the resulting elements (colored in blue), those elements will be treated as HTML elements. Figure 3 : XSL Stylesheet with 2 namespaces (example2.xsl) XSL Stylesheet (example2.xsl): <?xml version="1.0"?> <xsl:stylesheet version="1.0" ...
...And 2 more matches
XSLTProcessor - Web APIs
An XSLTProcessor applies an XSLT stylesheet transformation to an XML document to produce a new XML document as output. It has methods to load the XSLT stylesheet, to manipulate <xsl:param> parameter values, and to apply the transformation to documents. Syntax The constructor has no parameters. new XSLTProcessor() Methods [Throws] void XSLTProcessor.importStylesheet(Node styleSheet) Imports the XSLT stylesheet. If the given node is a document node, you can pass in a full XSL Transform or a literal result element transform; otherwise, it must be an <xsl:stylesheet> or <xsl:transform> element. [Throws] DocumentFragment XSLTProcessor.transformToFragment(Node source, Document owner) Transforms the node source by applying the stylesheet imported using the XSLTProcessor.importStyles...
... [Throws] Document XSLTProcessor.transformToDocument(Node source) Transforms the node source applying the stylesheet given importing using the XSLTProcessor.importStylesheet() function. ...
...ment node, you can pass in a full XSL Transform or a literal result element transform; otherwise, it must be an <xsl:stylesheet> or <xsl:transform> element. [Throws] DocumentFragment XSLTProcessor.transformToFragment(Node source, Document owner) Transforms the node source by applying the stylesheet imported using the XSLTProcessor.importStylesheet() function. The owner document of the resulting document fragment is the owner node. [Throws] Document XSLTProcessor.transformToDocument(Node source) Transforms the node source applying the stylesheet given importing using the XSLTProcessor.importStylesheet() function. The resultant object depends on the output method of the stylesheet: Output method Result type html HTMLDocument xml XMLDocu...
...And 2 more matches
msCapsLockWarningOff - Web APIs
The msCapsLockWarningOff read/write property turns automatic caps lock warning on or off for validated password input fields. This proprietary property is specific to Internet Explorer and Microsoft Edge. Starting with Internet Explorer 10, input type=password fields will automatically display a warning if the caps lock is on. This property enables this warning to be disabled. ...
...tax document.msCapsLockWarningOff = true; Value Type: boolean False: Default. Automatic caps lock warning is turned on. True: Automatic caps lock warning is turned off. ...
...boolean False: Default. Automatic caps lock warning is turned on. True: Automatic caps lock warning is turned off. ...
...And 2 more matches
ARIA live regions - Accessibility
from the Sun and the only object in the Universe known to harbor life.' }, mars: { title: "Mars", description: 'Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System after Mercury. ...
...e.' }, mars: { title: "Mars", description: 'Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System after Mercury. ...
...escription = document.querySelector('#planetDescription'); if (planet in PLANETS_INFO) { planetTitle.textContent = PLANETS_INFO[planet].title; planetDescription.textContent = PLANETS_INFO[planet].description; } else { planetTitle.textContent = 'No planet selected'; planetDescription.textContent = 'Select a planet to view its description'; } } const renderPlanetInfoButton = document.querySelector('#renderPlanetInfoButton'); renderPlanetInfoButton.addEventListener('click', event => { const planetsSelect = document.querySelector('#planetsSelect'); const selectedPlanet = planetsSelect.options[planetsSelect.selectedIndex].value; renderPlanetInfo(selectedPlanet); }); As the user selects a new planet, the information in the live region will be announced. Because the li...
...And 2 more matches
ARIA: Navigation Role - Accessibility
er service"> <ul> <li><a href="#">Help</a></li> <li><a href="#">Order tracking</li> <li><a href="#">Shipping &amp; Delivery</a></li> <li><a href="#">Returns</a></li> <li><a href="#">Contact us</a></li> <li><a href="#">Find a store</a></li> </ul> </div> Accessibility concerns Landmark roles are intended to be used sparingly, to identify larger overall sections of the document. Using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. Best practices Prefer HTML Using the <nav> element will automatically communicate a section has a role of navigation. If at all possible, prefer using it instead. Labeling landmarks Multiple landmarks If there is more than one navigation landmark role or <na...
... landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. Best practices Prefer HTML Using the <nav> element will automatically communicate a section has a role of navigation. If at all possible, prefer using it instead. ...
...An example of this would be repeating the main navigation at the top and bottom of the page. <header> <nav id="main-nav" aria-label="Main"> <!-- list of links to main website locations --> </nav> </header> ... ...
...And 2 more matches
ARIA: search role - Accessibility
The search landmark role is used to identify a section of the page used to search the page, site, or collection of sites. <form role="search"> <!-- search input --> </form> Description The search role is a landmark. Landmarks can be used by assistive technology to quickly identify and navigate to large sections of the document. The search role is added to the container element that encompasses the items and objects that, as a whole, combine to create search functionality. When a <form> is a search form, use the search role instead of form. If a document includes more than one search, each should have a unique label. While there is a input of type search, there is HTML element that defines a search landmark. Examples <form id="search" role="search"> <label for="search-input">Search this ...
...search, there is HTML element that defines a search landmark. Examples <form id="search" role="search"> <label for="search-input">Search this site</label> <input type="search" id="search-input" name="search" spellcheck="false"> <input value="Submit" type="submit"> </form> Accessibility concerns Landmark roles are intended to be used sparingly, to identify larger overall sections of the document. ...
...This label will allow an assitive technology user to be able to quickly understand the purpose of each landmark. <form id="site-search" role="search" aria-label="Sitewide"> <!-- search input --> </form> ... ...
...And 2 more matches
Accessibility Information for Web Authors - Accessibility
nes as well. Web Content Accessibility Guidelines (WCAG) 1.0 Another important set of guidelines from the W3C Web Accessibility Initiative (WAI). The European Union is looking to base their upcoming accessibility regulations on these guidelines. These guidelines are discussed on the WAI interest group discussion list. How-to's Key-navigable custom DHTML widgets in Mozilla & IE This document discusses how to use tabindex, element.focus() and onkeypress to make custom DHTML widgets such as menus or tree views keyboard accessible. Accessible Web Page Authoring IBM has put together a simple, practical resource for web authors to learn accessibility the fast and painless way. Highly recommended, an excellent resource. Dive Into Accessibility by Mark Pilgrim An excellent, easy-t...
...508 standards and/or the WCAG guidelines. Its purpose is to aid humans in the web accessibility evaluation process. Rather than providing a complex technical report, WAVE 4.0 shows the original web page with embedded icons and indicators that reveal the accessibility information within your page. You can get accessibity report for errors, warnings. You can view the structure and order view of the document. You can see a text-only view and and outline view of the document. You can install a custom WAVE toolbar in Firefox for a quick, easy and convenient evaluation of web pages directly within Firefox. You can also add a WAVE bookmarklet in Firefox or even WAVE direct links for checking a webpage. HTML advanced validator (Firefox extension) by Marc Gueury This HTML Validator (based on W3C Ti...
... within Firefox. You can also add a WAVE bookmarklet in Firefox or even WAVE direct links for checking a webpage. HTML advanced validator (Firefox extension) by Marc Gueury This HTML Validator (based on W3C Tidy and on OpenSP for SGML validation) is a powerful, versatile, extended HTML validator. It's free. It works off-line and that is a major advantage over other accessibility checkers. No document upload needed and no additional application to launch; everything is accessible within the Firefox browser. This HTML advanced validator Firefox extension is very resourceful and highly customizable. It's an extension add-on to Firefox 2.x and Firefox 3.x. It not only checks and reports possible markup errors and warnings (based on W3C Tidy and/or based on true SGML validation) but it can also...
...And 2 more matches
Coordinate systems - CSS: Cascading Style Sheets
vent's offsetX and offsetY properties are given relative to the top-left corner of the node to which the event has been delivered. The origin is inset by the distances specified by padding-left and padding-top. Client The "client" coordinate system uses as its origin the top-left corner of the viewport or browsing context in which the event occurred. ...
...is the entire viewing area in which the document is presented. Scrolling is not a factor. On a desktop computer, for example, the MouseEvent.clientX and MouseEvent.clientY properties indicate the position of the mouse cursor at the moment the event occurred, relative to the top-left corner of the browser window. The top-left corner of the window is always (0, 0), regardless of the content of the document or any scrolling that may have been done. In other words, scrolling the document will change the client coordinates of a given position within the document. Page The "page" coordinate system gives the position of a pixel relative to the top-left corner of the entire Document in which the pixel is located. ...
...less of the content of the document or any scrolling that may have been done. In other words, scrolling the document will change the client coordinates of a given position within the document. Page The "page" coordinate system gives the position of a pixel relative to the top-left corner of the entire Document in which the pixel is located. That means that a given point in an element within the document will keep the same coordinates in the page model unless the element moves (either directly by changing its position or indirectly by adding or resizing other content). Mouse events' pageX and pageY properties provide the position of the mouse at the time the event was generated, given relative to the top-left corner of the document. Screen Finally, we come to the "screen" model. It's probably ...
...And 2 more matches
Ordering Flex Items - CSS: Cascading Style Sheets
ok at ways in which you can change the visual order of your content when using Flexbox. We will also consider the implications of reordering items from an accessibility point of view. Reverse the display of the items the flex-direction property can take one of four values: row column row-reverse column-reverse The first two values keep the items in the same order that they appear in the document source order and display them sequentially from the start line. The second two values reverse the items by switching the start and end lines. Remember that the start line relates to writing modes. The row-related examples above demonstrate how row and row-reverse work in a left-to-right language such as English. If you are working in a right-to-left language like Arabic then row would s...
...der and navigation based on the source order. This allows authors to manipulate the visual presentation while leaving the source order intact for non-CSS UAs and for linear models such as speech and sequential navigation." - Ordering and Orientation If your items were links or some other element that the user could tab to, then the tabbing order would be the order that these items appear in the document source -- not your visual order. If you are using a reverse value, or otherwise reordering your items, you should consider whether you actually need to change the logical order in the source. The specification continues with a warning not to use reordering to fix issues in your source: "Authors must not use order or the *-reverse values of flex-flow/flex-direction as a substitute for correct s...
...rse value, or otherwise reordering your items, you should consider whether you actually need to change the logical order in the source. The specification continues with a warning not to use reordering to fix issues in your source: "Authors must not use order or the *-reverse values of flex-flow/flex-direction as a substitute for correct source ordering, as that can ruin the accessibility of the document." Note: For some years Firefox had a bug whereby it would attempt to follow the visual order and not the source order, making it behave differently to other browsers. This has now been fixed. You should always take the source order as the logical order of the document as all up-to-date user agents will be following the specification and doing so. In the live example below I have added a focu...
...And 2 more matches
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
In this article we will take a look at how Flexbox fits in with all the other CSS modules. We'll find out which specifications you also need to take notice of if you want to learn flexbox, and find out why flexbox is different to some other modules. Note: CSS versions 1 and 2 were a single monolithic specification where all of CSS was defined in one large document. As CSS became a more feature rich language, maintaining one huge specification became problematic, with different parts of CSS moving on at different speeds. CSS was therefore modularised, and the various CSS Specifications are different modules that make up CSS today. These modules relate to each other, and are at different stages of development. The box alignment module For many people the first reason they start to look at flex...
...ing Modes In the Basic concepts of flexbox article, I explained that flexbox is writing mode aware. Writing modes are fully detailed in the CSS Writing Modes specification, which details how CSS supports the various different writing modes that exist internationally. We need to be aware of how this will impact our flex layouts as writing mode changes the direction that blocks are laid out in our document. Understanding block and inline directions is key to new layout methods. It is worth noting that we might want to change the writing mode of our document for reasons other than publishing content in a language that uses a different writing mode. See this article for a full description of writing modes and ways to use them, both for content in other languages and for creative reasons. The writi...
...riting mode. You can change the live example below to these modes in order to see what happens to the flex layout. horizontal-tb vertical-rl vertical-lr sideways-rl sideways-lr Note that sideways-rl and sideways-lr have support only in Firefox currently. There are also some known issues with regard to writing-mode and flexbox. You can see more information on browser support in the MDN documentation for writing-mode. However if you are planning on using writing modes in your layout, carefully testing the results is advisable -- not least because it would be easy to make things hard to read! Note that you would not normally use CSS and the writing-mode property to change an entire document to another writing mode. This would be done via HTML, by adding a dir and lang attribute to the ht...
...And 2 more matches
transition-delay - CSS: Cascading Style Sheets
ty: width height background-color font-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:0.5s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:0.5s; transition-timing-function: linear; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-delay: 1s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height:...
...operty: width height background-color font-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:1s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:1s; transition-timing-function: linear; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-delay: 2s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height:...
...operty: width height background-color font-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:2s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:2s; transition-timing-function: linear; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-delay: 4s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height:...
...And 2 more matches
transition-duration - CSS: Cascading Style Sheets
height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration:0.5s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transformv color; transition-duration:0.5s; transition-timing-function: ease-in-out; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-duration: 1s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; heig...
...width height background-color font-size left top -webkit-transform transform color; -webkit-transition-duration:1s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration:1s; transition-timing-function: ease-in-out; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-duration: 2s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; heig...
...width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration:2s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration:2s; transition-timing-function: ease-in-out; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-duration: 4s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; heig...
...And 2 more matches
Cross-browser audio basics - Developer guides
rk 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"> ... ...
...aScript. 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 element. ...
...="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 loading events Above we have shown how you can create ...
...And 2 more matches
Creating and triggering events - Developer guides
example, the event could be created as follows: const event = new CustomEvent('build', { detail: elem.dataset.time }); This will then allow you to access the additional data in the event listener: function eventHandler(e) { console.log('The time is: ' + e.detail); } The old-fashioned way The older approach to creating events uses APIs inspired by Java. The following shows an example with document.createEvent(): // Create the event. const event = document.createEvent('Event'); // Define that the event name is 'build'. event.initEvent('build', true, true); // Listen for the event. elem.addEventListener('build', function (e) { // e.target matches elem }, false); // target can be any Element or other EventTarget. elem.dispatchEvent(event); Event bubbling It is often desirable to tri...
...ild', true, true); // Listen for the event. elem.addEventListener('build', function (e) { // e.target matches elem }, false); // target can be any Element or other EventTarget. ...
....addEventListener('build', function (e) { // e.target matches elem }, false); // target can be any Element or other EventTarget. ...
...And 2 more matches
<hgroup> - HTML: Hypertext Markup Language
Web › HTML › Element › hgroup
It groups a set of <h1>-<h6> elements. 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. Content categories Flow content, heading content, palpable content. Permitted content One or more <h1>, <h2>, <h3>, <h4>, <h5>, and/or <h6>. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts flow content. ...
...played by the outline algorithm defined in the HTML specification--but the HTML outline algorithm is not implemented in any browsers--then the <hgroup> semantics are in practice only theoretical. So the HTML5 (W3C) specification provides advice on how to mark up Subheadings, subtitles, alternative titles and taglines without using <hgroup>. The <hgroup> element allows the primary heading for a document section to be grouped with any secondary headings--such as subheadings or alternative titles--to form a multi-level heading. In other words, the <hgroup> element prevents any of its secondary <h1>-<h6> children from creating separate sections of their own in the outline--as those <h1>-<h6> elements otherwise normally would if they were not children of any <hgroup>. So in the abstract outline pr...
...n in a rendered outline in with a colon character and space (": ") or other such punctuation after the primary heading and before the first secondary heading (and with the same or similar punctuation before any other secondary headings an <hgroup> might be shown in a rendered outline in with the primary heading followed by parentheses around the secondary heading(s) Consider the following HTML document: <!DOCTYPE html> <title>HTML Standard</title> <body> <hgroup id="document-title"> <h1>HTML</h1> <h2>Living Standard -- Last Updated 12 August 2016</h2> </hgroup> <p>Some intro to the document.</p> <h2>Table of contents</h2> <ol id=toc>...</ol> <h2>First section</h2> <p>Some intro to the first section.</p> </body> A rendered outline for that document might look like the fol...
...And 2 more matches
<input type="color"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › color
or changes. The change event is fired when the user dismisses the color picker. In both cases, you can determine the new value of the element by looking at its value. Here's an example that watches changes over time to the color value: colorPicker.addEventListener("input", updateFirst, false); colorPicker.addEventListener("change", watchColorPicker, false); function watchColorPicker(event) { document.querySelectorAll("p").forEach(function(p) { p.style.color = event.target.value; }); } Selecting the value If the <input> element's implementation of the color type on the user's browser doesn't support a color well, but is instead a text field for entering the color string directly, you can use the select() method to select the text currently in the edit field. If the browser instead use...
...onsidered to be invalid if the user agent is unable to convert the user's input into seven-character lower-case hexadecimal notation. If and when this is the case, the :invalid pseudo-class is applied to the element. Example Let's create an example which does a little more with the color input by tracking the change and input events to take the new color and apply it to every <p> element in the document. HTML The HTML is fairly straightforward -- a couple of paragraphs of descriptive material with an <input> of type color with the ID colorWell, which we'll use to change the color of the paragraphs' text. <p>An example demonstrating the use of the <code>&lt;input type="color"&gt;</code> control.</p> <label for="colorWell">Color:</label> <input type="color" value="#ff0000" id="colorWell"> ...
... 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 load event handler, startup(), is called: function startup() { colorWell = document.querySelector("#colorWell"); colorWell.value = defaultColor; colorWell.addEventListener("input", updateFirst, false); colorWell.addEventListener("change", updateAll, false); colorWell.select(); } This gets a reference to the color <input> element in a variable called colorWell, then sets the color input's value to the value in defaultColor. Then the color input's input event is set up t...
...And 2 more matches
<style>: The Style Information element - HTML: Hypertext Markup Language
Web › HTML › Element › style
The HTML <style> element contains style information for a document, or part of a document. It contains CSS, which is applied to the contents of the document containing the <style> element. 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. The <style> element must be included inside the <head> of the document. In general, it is better to put your styles in external stylesheets and apply them using <link> elements. ...
...pository. 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. The <style> element must be included inside the <head> of the document. In general, it is better to put your styles in external stylesheets and apply them using <link> elements. If you include multiple <style> and <link> elements in your document, they will be applied to the DOM in the order they are included in the document -- make sure you include them in the correct order, to avoid unexpected cascade issues. ...
... Attributes This element includes the global attributes. type This attribute defines the styling language as a MIME type (charset should not be specified). This attribute is optional and defaults to text/css if it is not specified; values other than the empty string or text/css are not used. ...
...And 2 more matches
Global attributes - HTML: Hypertext Markup Language
Global attributes are attributes common to all HTML elements; they can be used on all elements, though they may have no effect on some elements. Global attributes may be specified on all HTML elements, even those not specified in the standard. That means that any non-standard elements must still permit these attributes, even though using those elements means that the document is no longer HTML5-compliant. For example, HTML5-compliant browsers hide content marked as <foo hidden>...</foo>, even though <foo> is not a valid HTML element. In addition to the basic HTML global attributes, the following global attributes also exist: xml:lang and xml:base -- these are inherited from the XHTML specifications and deprecated, but kept for compatibility purposes. The multiple aria-* attributes, used for...
...etter; 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 must be editable; false, which indicates that the element must not be editable. contextmenu ...
...A Boolean attribute indicates that the element is not yet, or is no longer, relevant. For example, it can be used to hide elements of the page that can't be used until the login process has been completed. The browser won't render such elements. This attribute must not be used to hide content that could legitimately be shown. id Defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS). inputmode Provides a hint to browsers as to the type of virtual keyboard configuration to use when editing this element or its contents. Used primarily on <input> elements, but is usable on any element while in contenteditable mode. is Allows you to specify that a standard HTM...
...And 2 more matches
Preloading content with rel="preload" - HTML: Hypertext Markup Language
esource 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 correct Accept request headers for it. What types of content can be preloaded? Many different content types can be preloaded. The possible as attribute values are: 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. w...
...ive preload example</title> <link rel="preload" href="bg-image-narrow.png" as="image" media="(max-width: 600px)"> <link rel="preload" href="bg-image-wide.png" as="image" media="(min-width: 601px)"> <link rel="stylesheet" href="main.css"> </head> <body> <header> <h1>My site</h1> </header> <script> var mediaQueryList = window.matchMedia("(max-width: 600px)"); var header = document.querySelector('header'); if (mediaQueryList.matches) { header.style.backgroundImage = 'url(bg-image-narrow.png)'; } else { header.style.backgroundImage = 'url(bg-image-wide.png)'; } </script> </body> We include media attributes on our <link> elements so that a narrow image is preloaded if the user has a narrow viewport, and a wider image is loaded if they have a wide v...
...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. ...
...And 2 more matches
HTML: Hypertext Markup Language
Web › HTML
p" to annotate text, images, and other content for display in a Web browser. HTML markup includes special "elements" such as <head>, <title>, <body>, <header>, <footer>, <article>, <section>, <p>, <div>, <span>, <img>, <aside>, <audio>, <canvas>, <datalist>, <details>, <embed>, <nav>, <output>, <progress>, <video>, <ul>, <ol>, <li> and many others. An HTML element is set off from other text in a document by "tags", which consist of the element name surrounded by "<" and ">". The name of an element inside a tag is case insensitive. That is, it can be written in uppercase, lowercase, or a mixture. For example, the <title> tag can be written as <Title>, <TITLE>, or in any other way. The articles below can help you learn more about HTML. HTML Introduction If you're new to Web development, be...
...le of a page load, before the browser's main rendering machinery kicks in. This ensures that they are made available earlier and are less likely to block the page's first render, leading to performance improvements. This article provides a basic guide to how preload works. References HTML reference HTML consists of elements, each of which may be modified by some number of attributes. HTML documents are connected to each other with links. HTML element reference Browse a list of all HTML elements. HTML attribute reference Elements in HTML have attributes. These are additional values that configure the elements or adjust their behavior in various ways. Global attributes Global attributes may be specified on all HTML elements, even those not specified in the standard. This means that any...
...ements. HTML attribute reference Elements in HTML have attributes. These are additional values that configure the elements or adjust their behavior in various ways. Global attributes Global attributes may be specified on all HTML elements, even those not specified in the standard. This means that any non-standard elements must still permit these attributes, even though those elements make the document HTML5-noncompliant. Inline elements and block-level elements HTML elements are usually "inline" or "block-level" elements. An inline element occupies only the space bounded by the tags that define it. A block-level element occupies the entire space of its parent element (container), thereby creating a "block." Link types In HTML, various link types can be used to establish and define the rela...
...And 2 more matches
HTTP caching - HTTP
Web › HTTP › Caching
talk about browser and proxy caches, but there are also gateway caches, CDN, reverse proxy caches and load balancers that are deployed on web servers for better reliability, performance and scaling of web sites and web applications. Private browser caches A private cache is dedicated to a single user. You might have seen "caching" in your browser's settings already. A browser cache holds all documents downloaded via HTTP by the user. This cache is used to make visited documents available for back/forward navigation, saving, viewing-as-source, etc. without requiring an additional trip to the server. It likewise improves offline browsing of cached content. Shared proxy caches A shared cache is a cache that stores responses to be reused by more than one user. For example, an ISP or your compan...
...er, common HTTP caches are typically limited to caching responses to GET and may decline other methods. The primary cache key consists of the request method and target URI (oftentimes only the URI is used as only GET requests are caching targets). Common forms of caching entries are: Successful results of a retrieval request: a 200 (OK) response to a GET request containing a resource like HTML documents, images or files. Permanent redirects: a 301 (Moved Permanently) response. Error responses: a 404 (Not Found) result page. Incomplete results: a 206 (Partial Content) response. Responses other than GET if something suitable for use as a cache key is defined. A cache entry might also consist of multiple stored responses differentiated by a secondary key, if the request is target of content ...
...ave CSS stylesheets or JS scripts that have mutual dependencies, i.e., they depend on each other because they refer to the same HTML elements. The revision version added to revved resources doesn't need to be a classical revision string like 1.1.3, or even a monotonously growing suite of number. It can be anything that prevent collisions, like a hash or a date. Cache validation When a cached document's expiration time has been reached, it is either validated or fetched again. Validation can only occur if the server provided either a strong validator or a weak validator. Revalidation is triggered when the user presses the reload button. It is also triggered under normal browsing if the cached response includes the "Cache-Control: must-revalidate" header. Another factor is the cache validation...
...And 2 more matches
Content-Location - HTTP
his distinction may seem abstract without examples. Header type Entity header Forbidden header name no Syntax Content-Location: <url> Directives <url> A relative (to the request URL) or absolute URL. Examples Requesting data from a server in different formats Let's say a site's API can return data in JSON, XML, or CSV formats. ...
...ithout examples. Header type Entity header Forbidden header name no Syntax Content-Location: <url> Directives <url> A relative (to the request URL) or absolute URL. Examples Requesting data from a server in different formats Let's say a site's API can return data in JSON, XML, or CSV formats. ...
...a from a server in different formats Let's say a site's API can return data in JSON, XML, or CSV formats. If the URL for a particular document is at https://example.com/documents/foo, the site could return different URLs for Content-Location depending on the request's Accept header: Request header Response header Accept: application/json, text/json Content-Location: /documents/foo.json Accept: application/xml, text/xml Content-Location: /documents/foo.xml Accept: text/plain, text/* Content-Location: /documents/foo.txt These URLs are examples -- the site could serve the different filetypes with any URL patterns it wishes, such as a query string parameter: /documents/foo?format=json, /documents/foo?format=xml, and so on. Then the client c...
...And 2 more matches
Content-Security-Policy-Report-Only - HTTP
For more information, see also this article on Content Security Policy (CSP). Header type Response header Forbidden header name no This header is not supported inside a <meta> element. ...
...licy, use the Content-Security-Policy header with the report-uri directive. Content-Security-Policy: default-src https:; report-uri /csp-violation-report-endpoint/ Violation report syntax The report JSON object contains the following data: blocked-uri The URI of the resource that was blocked from loading by the Content Security Policy. If the blocked URI is from a different origin than the document-uri, then the blocked URI is truncated to contain just the scheme, host, and port. disposition Either "enforce" or "report" depending on whether the Content-Security-Policy header or the Content-Security-Policy-Report-Only header is used. document-uri The URI of the document in which the violation occurred. effective-directive The directive whose enforcement caused the violation. original-...
... script-sample The first 40 characters of the inline script, event handler, or style that caused the violation. status-code The HTTP status code of the resource on which the global object was instantiated. ...
...And 2 more matches
Content-Security-Policy - HTTP
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 applied to individual DOM elements. worker-src Specifies valid sources for Worker, SharedWorker, or ServiceWorker scripts. Document directives Document directives govern the properties of a document or worker environment to which a policy applies. base-uri Restricts the URLs which can be used in a document's <base> element. plugin-types Restricts the set of plugins that can be embedded into a document by limiting the types of resources which can be loaded. sandbox Enables a sandbox for the requested resource similar ...
... Navigation directives Navigation directives govern to which locations a user can navigate or submit a form, for example. form-action Restricts the URLs which can be used as the target of a form submissions from a given context. frame-ancestors Specifies valid parents that may embed a page using <frame>, <iframe>, <object>, <embed>, or <applet>. navigate-to Restricts the URLs to which a document can initiate navigation by any means, including <form> (if form-action is not specified), <a>, window.location, window.open, etc. Reporting directives Reporting directives control the reporting process of CSP violations. See also the Content-Security-Policy-Report-Only header. report-uri Instructs the user agent to report attempts to violate the Content Security Policy. These violation re...
...on by any means, including <form> (if form-action is not specified), <a>, window.location, window.open, etc. Reporting directives Reporting directives control the reporting process of CSP violations. See also the Content-Security-Policy-Report-Only header. report-uri Instructs the user agent to report attempts to violate the Content Security Policy. These violation reports consist of JSON documents sent via an HTTP POST request to the specified URI. Though the report-to directive is intended to replace the deprecated report-uri directive, report-to is not supported in most browsers yet. So for compatibility with current browsers while also adding forward compatibility when browsers get report-to support, you can specify both report-uri and report-to: Content-Security-Policy: ...; repo...
...And 2 more matches
Regular expression syntax cheatsheet - JavaScript
This page provides an overall cheat sheet of all the capabilities of RegExp syntax by aggregating the content of the articles in the RegExp guide. If you need more information on a specific topic, please follow the link on the corresponding heading to access the full article or head to the guide. Character classes If you are looking to contribute to this document, please also edit the original article Characters Meaning . Has one of the following meanings: Matches any single character except line terminators: \n, \r, \u2028 or \u2029. For example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day". Inside a character set, the dot loses its special meaning and matches a literal dot. Note that the m multiline flag doesn'...
...ons. However, in regular expressions with the unicode flag, these will cause an invalid identity escape error. This is done to ensure backward compatibility with existing code that uses new escape sequences like \p or \k. To match this character literally, escape it with itself. In other words to search for \ use /\\/. Assertions If you are looking to contribute to this document, please also edit the original article Boundary-type assertions Characters Meaning ^ Matches the beginning of input. If the multiline flag is set to true, also matches immediately after a line break character. For example, /^A/ does not match the "A" in "an A", but does match the first "A" in "An A". This character has a different meaning when it appea...
...sults. (?<!y)x Negative lookbehind assertion: Matches "x" only if "x" is not preceded by "y". For example, /(?<!-)\d+/ matches a number only if it is not preceded by a minus sign. /(?<!-)\d+/.exec('3') matches "3". /(?<!-)\d+/.exec('-3') match is not found because the number is preceded by the minus sign. Groups and ranges If you are looking to contribute to this document, please also edit the original article Characters Meaning x|y Matches either "x" or "y". For example, /green|red/ matches "green" in "green apple" and "red" in "red apple". [xyz] [a-c] A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen, but if the hyphen appears as the firs...
...And 2 more matches
JavaScript technologies overview - JavaScript
HTML defines a webpage's structure and content and CSS sets the formatting and appearance, JavaScript adds interactivity to a webpage and creates rich web applications. However, the umbrella term "JavaScript" as understood in a web browser context contains several very different elements. One of them is the core language (ECMAScript), another is the collection of the Web APIs, including the DOM (Document Object Model). JavaScript, the core language (ECMAScript) The core language of JavaScript is standardized by the ECMA TC39 committee as a language named ECMAScript. This core language is also used in non-browser environments, for example in node.js. What falls under the ECMAScript scope? Among other things, ECMAScript defines: Language syntax (parsing rules, keywords, control flow, object...
...uage Specification, also standardized by Ecma TC39. The internationalization API provides collation (string comparison), number formatting, and date-and-time formatting for JavaScript applications, letting the applications choose the language and tailor the functionality to their needs. The initial standard was approved in December 2012; the status of implementations in browsers is tracked in the documentation of the Intl object. The Internationalization specification is nowadays also ratified on a yearly basis and browsers constantly improve their implementation. DOM APIs WebIDL The WebIDL specification provides the glue between the DOM technologies and ECMAScript. The Core of the DOM The Document Object Model (DOM) is a cross-platform, language-independent convention for representing and in...
...tion specification is nowadays also ratified on a yearly basis and browsers constantly improve their implementation. DOM APIs WebIDL The WebIDL specification provides the glue between the DOM technologies and ECMAScript. ...
...And 2 more matches
Image file type and format guide - Web media technologies
tom-left corner toward the right and top, rather than from the top-left corner toward the right and bottom). Theoretically, several compression algorithms are supported, and the image data can also be stored in JPEG or PNG format within the BMP file. ...
...el is. True color with alpha 8 and 16 Each pixel is comprised of four D-pixel color components: red, green, blue, and the alpha sample indicating how opaque the pixel is. Compression Lossless, optionally indexed color like GIF Licensing (C)2003 W3C(R) (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply. No known royalty-bearing patents. SVG (Scalable Vector Graphics) SVG is an XML-based vector graphics format that specifies the contents of an image as a set of drawing commands that create shapes, lines, apply colors, filters, and so forth. SVG files are ideal for diagrams, icons, and other images which can be accurately drawn at any size. As such, ...
... 9 Maximum dimensions Unlimited Supported color modes Colors in SVG are specified using CSS color syntax. Compression SVG source may be compressed during transit using HTTP compression techniques, or on disk as an .svgz file. Licensing (C)2018 W3C(R) (MIT, ERCIM, Keio, Beihang), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply. No known royalty-bearing patents. TIFF (Tagged Image File Format) TIFF is a raster graphics file format which was created to store scanned photos, although it can be any kind of image. It is a somewhat "heavy" format, in that TIFF files have a tendency to be larger than images in other formats. This is because of the metadata often included, as well...
...And 2 more matches
Web Performance
rty 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 possible. If your animations are really complex, you may have to rely on JavaScript-based animations instead.Lazy loadingLazy Loading is a strateg...
...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 detailed network timing measurements regarding the loading of an application's resources.Optimizing startup performanceRegardless of platform, it's always a good idea to start up as quickly as possible. Since that's a universal issue, we won't be focusing on it too much here. Instead, we're going to look at a more important issue when building Web apps: sta...
...ent handler on the app's main thread.Performance budgetsA performance budget is a limit to prevent regressions. It can apply to a file, a file type, all files loaded on a page, a specific metric (e.g. Time to Interactive), a custom metric (e.g. Time to Hero Element), or a threshold over a period of time. Performance fundamentalsPerformance means efficiency. In the context of Open Web Apps, this document explains in general what performance is, how the browser platform helps improve it, and what tools and processes you can use to test and improve it.Performance Monitoring: RUM vs synthetic monitoringSynthetic monitoring and real user monitoring (RUM) are two approaches for monitoring and providing insight into web performance. In this article we define and compare these two performance monitorin...
...And 2 more matches
Privacy, permissions, and information security
hnologies and features used to enforce security and privacy Technology or feature Description Certificate Transparency An open standard for monitoring and auditing certificates, creating a database of public logs that can be used to help identify incorrect or malicious certificates Content Security Policy Provides the ability to define the extent to which a document's content can be accessed by other devices over the web; used in particular to prevent or mitigate attacks on the server Feature Policy Lets web developers selectively enable, disable, and modify the behavior of certain features and APIs both for a document and for subdocuments loaded in <iframe>s <iframe>'s allow attribute Technically part of Feature Policy, the allow att...
...b; used in particular to prevent or mitigate attacks on the server Feature Policy Lets web developers selectively enable, disable, and modify the behavior of certain features and APIs both for a document and for subdocuments loaded in <iframe>s <iframe>'s allow attribute Technically part of Feature Policy, the allow attribute on an <iframe> specifies which web features the document in the frame should be allowed to access HTTP Public Key Pinning (HPKP) HPKP is used by servers to instruct a client to associate a specific public key with the server going forward in order to decrease the likelihood of man-in-the-middle attacks HTTP Strict Transport Security (HSTS) HSTS is used by servers to let them protect themselves from protocol downgrade and cookie ...
...help secure a site and its content. Keeping personal data safe Managing site permissions Bringing it all together <using Feature Policy with permissions and so forth; how to use them together, how they interact, etc> Permission requests in <iframe> elements Things can get tricky when your web app uses the <iframe> element to embed content from another site inside your own, especially if the document you load into the frame has its own permission needs to consider. While specifications for these technologies either state or recommend tactics for handling situations like this, browsers may offer different solutions to improve security even further or to try new features, or try to reduce complexity for users, among other possible reasons. <--- allow attribute, feature policy, and permissions...
...And 2 more matches
target - SVG: Scalable Vector Graphics
Web › SVG › Attribute › target
The target attribute should be used when there are multiple possible targets for the ending resource, such as when the parent document is embedded within an HTML or XHTML document, or is viewed with a tabbed browser. ...
... The target attribute should be used when there are multiple possible targets for the ending resource, such as when the parent document is embedded within an HTML or XHTML document, or is viewed with a tabbed browser. ...
... _self Animatable Yes _replace The current SVG image is replaced by the linked content in the same rectangular area in the same frame as the current SVG image. Note: This value was never well implemented, and the distinction between _replace and _self has been made redundant by changes in the HTML definition of browsing contexts. Use _self to replace the current SVG document. _self The current SVG image is replaced by the linked content in the same browsing context as the current SVG image. _parent The immediate parent browsing context of the SVG image is replaced by the linked content, if it exists and can be securely accessed from this document. _top The content of the full active window or tab is replaced by the linked content, if it exists and can be se...
...And 2 more matches
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
tElement and SVGElement.ownerSVGElement nullable Implementation status unknown SVGElement.getPresentationAttribute() removed Never implemented (prototype removed in bug 921456) SVGColor and SVGICCColor removed Never implemented SVGElement.focus(), SVGElement.blur() Not implemented (bug 778654) SVGElement.tabIndex Implemented (bug 778654) Document.activeElement Implementation status unknown GlobalEventHandlers on SVGElement Implementation status unknown options dictionary attribute for SVGGraphicsElement.getBBox() Implemented behind the preference svg.new-getBBox.enabled (bug 999964, bug 1019326) Allow leading and trailing whitespace in <length>, <angle>, <number> and <integer> Implementation status u...
...raphicsElement.getCTM() on the outermost element Implementation status unknown animVal attribute alias of baseVal Implementation status unknown dataset attribute for SVGElement Implementation status unknown Moved pathLength attribute and getTotalLength() and getPointAtLength() methods from SVGPathElement to SVGGeometryElement Implemented (bug 1239100) Document Structure Change Notes SVGSVGElement.suspendRedraw(), SVGSVGElement.unsuspendRedraw(), and SVGSVGElement.unsuspendRedrawAll() deprecated Turned into no-ops (bug 734079) externalResourcesRequired attribute removed Implementation status unknown auto value for width and height in <image> Implementation status unknown referencing entire do...
...nknown 0 0 as default value of transform-origin except root <svg> and <svg> children of <foreign> Implementation status unknown Use of white-space instead of deprecated xml:space attribute in UA style sheet Implementation status unknown @font-face, ::first-letter and ::first-line on <text> Implementation status unknown SVG and HTML style sheets in HTML document with inline SVG applying to whole document content Implementation status unknown Presentation attributes on any SVG namespaced element Implementation status unknown Display behavior of <style> defined via UA style sheet Implementation status unknown !important user agent style rules controlling never-rendered elements Implementation status unknown :...
...And 2 more matches
SVG and CSS - SVG: Scalable Vector Graphics
This page illustrates the application of CSS to the specialized language for creating graphics: SVG. Below you'll create a simple demonstration that runs in your SVG-enabled browser. Note: Elements referenced by <use> elements inherit the styles from that element. So to apply different styles to them you should use CSS custom properties. Example Make a new SVG document as a plain text file, doc8.svg. Copy and paste the content from here, making sure that you scroll to get all of it: <svg width="600px" height="600px" viewBox="-300 -300 600 600" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <title>SVG demonstration</title> <desc>Mozilla CSS Getting Started - SVG demonstration</desc> <defs> <radialGradient id="fade" cx="0" cy="0" r="200"...
... SVG has its own CSS properties and values. Some of them are similar to CSS properties for HTML. Challenge Change the stylesheet so that the inner petals all turn pink when the mouse pointer is ...
... SVG has its own CSS properties and values. Some of them are similar to CSS properties for HTML. ...
...And 2 more matches
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes An Overview The separation of content and presentation is a key design feature of XML. The structure of an XML document is designed to reflect and clarify important relationships among the individual aspects of the content itself, unhindered by a need to provide any indication about how this data should eventually be presented. This intelligent structuring is particularly important as more and more data transfers are automated and take place between highly heterogeneous machines linked by a network. Yet eventually much of the content stored in XML documents will need to be presented to human readers. Because a browser provides a familiar and highly flexible interface, it is an ideal mechanism for del...
... At present, Gecko (the layout engine behind Firefox) supports two forms of XML stylesheets. For basic control of appearance -- fonts, colors, position, and so forth -- Gecko uses CSS. ...
...es CSS. CSS1 and CSS2 are well supported and support for the emerging CSS3 standard is under development. For further information about CSS, see Eric Meyer's CSS pages. Our focus here is on the second type of stylesheet that Gecko supports: the XSLT stylesheet. XSLT stands for eXtensible Stylesheet Language/Transform and the name is apt. 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 (and in the case of Firefox, the focus is on converting it on the fly into HTML which can then be displayed by the browser). XSLT/XPath reference Elements xsl:apply-imports (supported) xsl:apply-templates (supported) xsl:a...
...And 2 more matches
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
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 the parameter using $myOrder. However, the value needs to be an XPATH expression and not a string, so {$myOrder} is used. Using {} evaluates the content as an XPath expression. Once the transformation is complete, the result is appended to the document, as shown in this example. Figure 7: Sorting based on div contentview example // XHTML Fragment: <div id="example"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>10</div> </div> // JavaScript var xslRef; var xslloaded = false; var xsltProcessor = new XSLTProcessor(); var myDOM; var xmlRef = docum...
...e. ...
...slRef; var xslloaded = false; var xsltProcessor = new XSLTProcessor(); var myDOM; var xmlRef = document.implementation.createDocument("", "", null); function sort() { if (!xslloaded){ p = new XMLHttpRequest(); p.open("GET", "example2.xsl", false); p.send(null); xslRef = p.responseXML; xsltProcessor.importStylesheet(xslRef); xslloaded = true; } // create a new XML document in memory xmlRef = document.implementation.createDocument("", "", null); // we want to move a part of the DOM from an HTML document to an XML document. ...
...And 2 more matches
Compiling an Existing C Module to WebAssembly - WebAssembly
ibraries and allow developers to use them on the web. These libraries often rely on C's standard library, an operating system, a file system and other things. Emscripten provides 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 t...
...NTIME_METHODS='["cwrap"]' \ -I libwebp \ 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...
...s an array of bytes in RGB, RGBA, BGR or BGRA. Luckily, the Canvas API has CanvasRenderingContext2D.getImageData -- that gives you an Uint8ClampedArray containing the image data in RGBA: async function loadImage(src) { // Load image const imgBlob = await fetch(src).then(resp => resp.blob()); const img = await createImageBitmap(imgBlob); // Make canvas same size as image const canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; // Draw image onto canvas const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); return ctx.getImageData(0, 0, img.width, img.height); } Now it's "only" a matter of copying the data from JavaScript into wasm. For that, you need to expose two additional functions -- one that allocates memory for the...
...And 2 more matches
port - Archive of obsolete content
The port object provides message sending and receiving API enabling conversations between a content script and the main add-on code. Each end of the conversation has access to a port: the content script via the global self property, and the main add-on code via a worker object associated with the SDK module you've used to attach the content script, such as page-mod or page-worker. For an overview of content scripts, see the main article. port Methods emit() The port.emit() function sends a message from one side to the other. It may be called with any number of parameters, but is most likely to be called with a name for the message and an optional payload. ...
...yMessage", function handleMyMessage(myMessagePayload) { // Handle the message }); once() Often you'll want to receive a message just once, then stop listening. The port object offers a shortcut to do this: the once() method. This example rewrites the content script in the port.removeListener() example so that it uses once(): // content-script.js function getFirstParagraph() { var paras = document.getElementsByTagName('p'); console.log(paras[0].textContent); } self.port.once("get-first-para", getFirstParagraph); removeListener() You can use port.on() to listen for messages. To stop listening for a particular message, use port.removeListener(). This takes the same two parameters as port.on(): the name of the message, and the name of the listener function. For example, here's an add-on...
....wikipedia.org/wiki/Chalk" }); require("sdk/ui/button/action").ActionButton({ id: "get-first-para", label: "get-first-para", icon: "./icon-16.png", onClick: function() { console.log("sending 'get-first-para'"); pageWorker.port.emit("get-first-para"); } }); The content script listens for "get-first-para". When it receives this message, the script logs the first paragraph of the document and then calls removeListener() to stop listening. // content-script.js function getFirstParagraph() { var paras = document.getElementsByTagName('p'); console.log(paras[0].textContent); self.port.removeListener("get-first-para", getFirstParagraph); } self.port.on("get-first-para", getFirstParagraph); The result is that the paragraph is only logged the first time the button is clicked. ...
...); var self = require("sdk/self"); var pageMod = pageMods.PageMod({ include: ['*'], contentScriptFile: self.data.url("content-script.js"), onAttach: setupListener }); function setupListener(worker) { worker.port.on('loaded', function(pageInfo) { console.log(pageInfo[0]); console.log(pageInfo[1]); }); } //content-script.js self.port.emit('loaded', [ document.location.toString(), document.title ]); ...
Communicating using "port" - Archive of obsolete content
wiki/Chalk" }); require("sdk/ui/button/action").ActionButton({ id: "get-first-para", label: "get-first-para", icon: "./icon-16.png", onClick: function() { console.log("sending 'get-first-para'"); pageWorker.port.emit("get-first-para"); } }); The content script "listener.js" listens for "get-first-para". When it receives this message, the script logs the first paragraph of the document and then calls removeListener() to stop listening. function getFirstParagraph() { var paras = document.getElementsByTagName('p'); console.log(paras[0].textContent); self.port.removeListener("get-first-para", getFirstParagraph); } self.port.on("get-first-para", getFirstParagraph); The result is that the paragraph is only logged the first time the button is clicked. Due to bug 816272 the...
...t receives the first message, then the listener will still receive the second message. port.once() Often you'll want to receive a message just once, then stop listening. The port object offers a shortcut to do this: the once() method. This example rewrites the "listener.js" content script in the port.removeListener() example so that it uses once(): function getFirstParagraph() { var paras = document.getElementsByTagName('p'); console.log(paras[0].textContent); } self.port.once("get-first-para", getFirstParagraph); JSON-Serializable Values The payload for an message can be any JSON-serializable value. When messages are sent their payloads are automatically serialized, and when messages are received their payloads are automatically deserialized, so you don't need to worry about serializa...
...to be a string, number, boolean, null, array of JSON-serializable values, or an object whose property values are themselves JSON-serializable. This means you can't send functions, and if the object contains methods they won't be encoded. ...
...ializable values, or an object whose property values are themselves JSON-serializable. This means you can't send functions, and if the object contains methods they won't be encoded. ...
indexed-db - Archive of obsolete content
st.onerror = function(event) { console.log("failure"); }; request.onsuccess = function(event) { console.log("success"); }; Most of the objects that implement the IndexedDB API, such as IDBTransaction, IDBOpenDBRequest, and IDBObjectStore, are accessible through the indexedDB object itself. The API exposed by indexed-db is almost identical to the DOM IndexedDB API, so we haven't repeated its documentation here, but refer you to the IndexedDB API documentation for all the details. The database created will be unique and private per add-on, and is not linked to any website database. The module cannot be used to interact with a given website database. See bug 778197 and bug 786688. Example This example uses the action button API, which is only available from Firefox 29 onwards. Here's a co...
... ...
... ...
...hat to run this add-on you'll need to provide icons named "add.png" and "list.png" in the add-on's "data" directory. Globals Properties indexedDB Enables you to create, open, and delete databases. See the IDBFactory documentation. IDBKeyRange Defines a range of keys. See the IDBKeyRange documentation. DOMException Provides more detailed information about an exception. See the DOMException documentation. ...
private-browsing - Archive of obsolete content
e tabs module will not list any tabs that belong to private browser windows, and the add-on won't receive any events for such tabs any ui components will not be displayed in private browser windows any menus or menu items created using the context-menu will not be shown in context menus that belong to private browser windows the page-mod module will not attach content scripts to documents belonging to private browser windows any panel objects will not be shown if the active window is a private browser window the selection module will not include any selections made in private browser windows Add-ons that have opted in will see private windows, so they will need to use the private-browsing module to check whether objects are private, so as to avoid storing data der...
...certain functions, even if they have not explicitly opted into private browsing. Respecting private browsing The private-browsing module exports a single function isPrivate() that takes an object, which may be a BrowserWindow, tab, or worker, as an argument. It returns true only if the object is: a private window, or a tab belonging to a private window, or a worker that's associated with a document hosted in a private window any window, tab, or worker if the browser has been configured to never remember history (Options->Privacy->History) Add-ons can use this API to decide whether or not to store user data. For example, here's an add-on that stores the titles of tabs the user loads, and uses isPrivate() to exclude the titles of tabs that were loaded into private windows: var simpleStora...
...; Here's an add-on that uses a page-mod to log the content of pages loaded by the user, unless the page is private. ...
...This may be a BrowserWindow, tab, or worker. ...
tabs/utils - Archive of obsolete content
w) Returns the tabs for the specified window. If you omit window, this function will return tabs across all the browser's windows. However, if your add-on has not opted into private browsing, then the function will exclude all tabs that are hosted by private browser windows. To learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module. Parameters window : nsIWindow Optional. Returns Array : An array of tab elements. getActiveTab(window) Given a browser window, get the active, or selected, tab. Parameters window : window A browser window. Returns tab : The currently selected tab. getOwnerWindow(tab) Get the browser window that owns the specified tab. Parameters tab : tab A b...
...ndow A browser window. Returns tab : The currently selected tab. getOwnerWindow(tab) Get the browser window that owns the specified tab. Parameters tab : tab A browser tab. Returns window : A browser window. openTab(window, url, options) Open a new tab in the specified browser window. Parameters window : window The browser window in which to open the tab. url : String URL for the document to load. options : object Optional options: Name Type inBackground boolean If true, open the new tab, but keep the currently selected tab selected. If false, make the new tab the selected tab. Optional, defaults to false. pinned boolean Pin this tab. Optional, defaults to false. Returns tab : The new tab. isTabOpen(t...
...Returns browser : getTabId(tab) Get the specified tab's ID. On Firefox it's derived from its linkedPanel property. Parameters tab : tab A XUL tab element. Returns id : the ID for this tab. getTabForId(id) Get the tab identified by id. Parameters id : On Firefox it's derived from its linkedPanel property. Returns tab : tab A XUL tab element. getTabTitle(tab) Get the title of the document hosted by the specified tab, or the tab's label if the tab doesn't host a document. Parameters tab : tab A XUL tab element. Returns String : setTabTitle(tab, title) Set the title of the document hosted by the specified tab, or the tab's label if the tab doesn't host a document. Parameters tab : tab A XUL tab element. title : String The new title. getTabContentWindow(tab) Get the spe...
...window) Get the tab element that hosts the specified content window. Parameters window : window Returns tab : getTabURL(tab) Get the specified tab's URL. Parameters tab : tab A XUL tab element. Returns String : The current URI. setTabURL(tab, url) Set the specified tab's URL. Parameters tab : tab A XUL tab element. url : String getTabContentType(tab) Get the contentType of the document hosted by the specified tab. Parameters tab : tab A XUL tab element. Returns String : getSelectedTab(window) Get the selected tab for the specified browser window. Parameters window : window Returns tab : A XUL tab element. getTabForBrowser(browser) Get the tab linked to the specified browser. Parameters browser : browser the browser whose tab element we want to find. Returns ta...
cfx - Archive of obsolete content
pted for add-on submission, jpm should now be used instead. cfx usage is: cfx [options] command [command-specific options] "Options" are global options applicable to the tool itself or to all commands (for example --help). cfx supports the following global options: -h, --help - show a help message and exit -v, --verbose - enable lots of output "Command-specific options" are documented alongside the commands. There are four supported cfx commands: cfx init Create a skeleton add-on as a starting point for your own add-on. cfx run Launch an instance of Firefox with your add-on installed. cfx test Runs your add-on's unit tests. cfx xpi Package your add-on as an XPI file, which is the install file format for Firefox add-ons. ...
...f package.json exists, cfx will load the corresponding add-on, load from the tests directory any modules that start with the word test- and run the unit tests they contain. Note the hyphen after "test" in the module name. cfx test will include a module called "test-myCode.js", but will exclude modules called "test_myCode.js" or "testMyCode.js". See the tutorial on unit testing and the reference documentation for the assert module for details. Supported Options As with cfx run you can use options to control which host application binary version to use, and to select a profile. You can also control which tests are run: you can test dependent packages, filter the tests by name and run tests multiple times. -b BINARY, --binary=BINARY Use the host application binary specified in BINAR...
... points to the updated XPI itself. The --update-link and --update-url options simplify this process. Both options take a URL as an argument. The --update-link option builds an update RDF alongside the XPI, and embeds the supplied URL in the update RDF as the value of updateLink. The --update-url option embeds the supplied URL in the XPI file, as the value of updateURL. Note that as the add-on documentation explains, you should make sure the update procedure for your add-on is secure, and this usually involves using HTTPS for the links. So if we run the following command: cfx xpi --update-link https://example.com/addon/latest/pluginName.xpi --update-url https://example.com/addon/update_rdf/pluginName.update.rdf cfx will create two files: an XPI file which embeds https://example.com/add...
.... TEMPLATEDIR may be specified as a full path or as a path relative to the current directory. Internal Options --keydir=KEYDIR Supply a different location for signing keys. KEYDIR may be specified as a full path or as a path relative to the current directory. Internal Commands cfx testcfx This will run a number of tests on the cfx tool, including tests against the documentation. Use cfx testcfx -v for the specific list of tests. This accepts the same options as cfx test. cfx testaddons This will run a number of test add-ons that are packaged with the SDK. This accepts the same options as cfx test. cfx testpkgs This will test all of the available CommonJS packages. Note that the number of tests run and their success depends on what application they are run wit...
package.json - Archive of obsolete content
n64.png. If you don't provide an icon here, the same icon as specified by icon will be used. This value will be used as the add-on's em:icon64URL element in its install.rdf. The icon may be up to 64x64 pixels in size. id A globally unique identifier for the add-on. This value will be used as the add-on's em:id element in its install.rdf. See the Program ID documentation. lib String representing the top-level module directory provided in this add-on. Defaults to "lib". Note: This is deprecated along with cfx and is not available when using jpm. license The name of the license under which the add-on is distributed, with an optional URL in parentheses. Defaults to "MPL-2.0". Note: It is recomme...
...an optional URL in parentheses. Defaults to "MPL-2.0". Note: It is recommended that you use an SPDX license ID. locales An object holding JSON objects referenced by a locale name that use the following keys: title, description and homepage. These JSON objects will be used to localizations for the add-on's meta data shown within the Add-ons Manager. See the documentation for how to localize the add-on's meta data. main A string representing the name of a program module that is located in one of the top-level module directories specified by lib. Defaults to "index.js". name The add-on's name. This name cannot contain spaces or periods, and defaults to the name of the parent directory. When the add-on is built as ...
...al packages. Defaults to "packages". permissions An object describing the set of permissions that the add-on needs. private-browsing: a boolean indicating whether or not the add-on supports private browsing. If this value is not true or is omitted, then the add-on will not see any private windows or objects, such as tabs, that are associated with private windows. See the documentation for the private-browsing module. cross-domain-content: a list of domains for which content scripts are given cross-domain privileges to access content in iframes or to make XMLHTTPRequests. See the documentation for enabling cross-domain content scripts. multiprocess: a Boolean value declaring whether this add-on is, or is not, compatible with multiprocess Firefox. Note t...
...patible with multiprocess Firefox. Note the multiprocess permission is not supported by cfx. preferences An array of JSON objects that use the following keys: name,type, value, title, and description. These JSON objects will be used to create a preferences interface for the add-on in the Add-ons Manager unless the preferencesURL field is specified. See the documentation for the simple-prefs module. preferencesURL The URL where the "Preferences" button of your add-on in the Add-ons Manager will point to. Use this to specify a custom preferences page instead of the built-in UI provided by the Add-on Manager. preferences-branch Use this to specify an alternative branch for your add-on's simple-prefs. See "Simple-prefs in the prefere...
File I/O - Archive of obsolete content
e application's installation directory). DefProfLRt d Location of user profile temporary directories live. DefProfRt d The root of the default profile directory (for example /root/.mozilla). DefRt d %CurProcD%/defaults - The root directory of all defaults directories. The user's desktop directory (for example ~/Desktop on Linux or Mac OS X, C:\Documents and Settings\username\Desktop on Windows). Desk f DfltDwnld f The default Downloads directory (for example, ~/Downloads on Mac OS X). Home f The user's home directory (for example, /home/username). PrefD f Directory containing user prefs PrfDef d %installation%/defaults/pref ProfD f The profile directory. ...
... of the "current" locale. Should be the first choice. ProfDefNoLoc d %installation%/defaults/profile - The profile defaults of the "default" installed locale. Second choice when profDef is not available. ProfLD f Local Settings on Windows; where the network cache and fastload files are stored. Progs d User Start menu programs directory (for example, C:\Documents and Settings\username\Start Menu\Programs). This is a Windows-specific value. TmpD d The operating system's temporary files directory (for example, /tmp on Mac OS X and Linux). UChrm f The user chrome directory in their profile: %profile%/chrome. resource:app d The application directory in an XULRunner application. Look in the source for other ...
...oStream.write(data, data.length) directly var converter = Components.classes["@mozilla.org/intl/converter-output-stream;1"]. createInstance(Components.interfaces.nsIConverterOutputStream); converter.init(foStream, "UTF-8", 0, 0); converter.writeString(data); converter.close(); // this closes foStream Note: The file status flags used in the nsIFileOutputStream.init() function are documented in PR_Open. For more information refer directly to nsprpub/pr/include/prio.h Writing a Binary File For example, here we can write PNG data to a file. // pngBinary already exists var aFile = Components.classes["@mozilla.org/file/local;1"]. createInstance(Components.interfaces.nsILocalFile); aFile.initWithPath( "/tmp/mypicture.png" ); aFile.createUnique(Components.interfaces.nsIFi...
...Those methods/properties are mostly self-explanatory, so we haven't included examples of using them here. ...
Progress Listeners - Archive of obsolete content
Progress listeners implement the nsIWebProgressListener interface. Note that if you just want to execute your code each time a page loads, you can use an an easier method, onPageLoad(). Note that onPageLoad does not fire for back button clicks. In the examples below the progress listener is attached to the tabbrowser, which means you don't get any notifications for inactive tabs. Firefox 3.5 includes a way to set up a listener for all tabs, selected and not: Listening to events on all tabs. ...
... onLocationChange: function(aProgress, aRequest, aURI) { // This fires when the location bar changes; that is load event is confirmed // or when the user switches tabs. If you use myListener for more than one tab/window, // use aProgress.DOMWindow to obtain the tab/window which triggered the change. ...
...anges" fires multiple times, one of which is when the tab is changed. In some cases you want to catch only a location change when the anchor changes. To do this the optional aFlags parameter of the onLocationChange listener is used. ...
...ange when the anchor changes. To do this the optional aFlags parameter of the onLocationChange listener is used. ...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
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. ...
...js file in the user profile folder. Opening test.xul will show the local file URL in the location bar. Copy and paste this into the appropriate spot in Listing 3. Note: The location of the user profile will vary depending on your system. On Windows Vista, it will be located at C:\Users\username\AppData\Roaming\Mozilla\Firefox\Profiles\random number.default\ ; On Windows XP or 2000, it will be C:\Documents and Settings\username\Application Data\Mozilla\Firefox\Profiles\random number.default\ ; On Linux, it will be ~/.mozilla/firefox/random number.default/ ; On Mac OS X, it will be ~/Library/Application Support/Firefox/Profiles/random number.default/ In the interests of security, delete these lines from prefs.js after finishing these tests. Note that Firefox itself and its extensions have privile...
... nsILocalFile.isFile() Determines whether or not the reference is to a file. nsILocalFile.isSymlink() Determines whether or not the reference is to a symlink. Traversing directories Moving into a directory Use the nsILocalFile.append() method to drill down into a directory (or file). See Listing 8. Listing 8: Traversing directories file.initWithPath('C:\\'); file.append('Documents and Settings'); file.append('All Users'); file.append('Documents'); List files in specified directory Use the directoryEntries property to perform operations on all the files or folders in a given folder. This property returns a nsISimpleEnumerator-type object similar to the window overview, so you can get each element using similar techniques. Listing 9 shows how to list the contents of a fol...
... gives you access to sophisticated functions in XUL elements. For example, using the loadURI() method on the browser element introduced in Chapter 3 can open a page specified using HTTP_REFERER, as shown in Listing 21; Listing 22 shows how to open a page using the loadURIWithFlags() method, with data transmitted via the POST method. ...
Adding windows and dialogs - Archive of obsolete content
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 they interrupt the user's browsing a...
...at deal of options that cover most common dialog cases. Using the Prompt Service will save you a lot of XUL coding, and you'll be at ease knowing that you're using Mozilla's tried and tested code. The Dialog Element When the Prompt Service is not enough, you'll have to create you own XUL dialogs. Luckily, you still get a great deal of help from the platform if you use the dialog element as the document root instead of the more generic window element. You may be asking yourself what's the big deal about defining a simple XUL window with an OK and maybe a Cancel button. The dialogs we have covered in this section are very simple and shouldn't be too hard to implement manually using XUL. Well, it's more complicated than that. Different operating systems order and position their buttons differentl...
...pace-separated list of attribute names, indicating which attribute values must be persisted across window "sessions". <checkbox id="xulschoolhello-some-checkbox" label="&xulschoolhello.someText.label;" checked="false" persist="checked" /> Setting the id attribute of the element is mandatory if you want the persist attribute to work. You can also set persistence programatically using the document.persist function: document.persist("xulschoolhello-some-checkbox", "checked"); Persistent data is stored in the user profile, in the file localstore.rdf. You may need to modify or delete this file often when testing persistent data in your extension. Focus and Tabbing Moving through all input controls in a window using only the keyboard is an accessibility requirement. You can do this in ...
...ibility requirement. You can do this in most Firefox windows by pressing the Tab key. Each Tab key press moves you to the next control in the window, giving it focus. In general, there's nothing you need to do in order to have good keyboard focus management. Firefox will automatically focus the first input control in your window, and tab focus advances in the order the items are found in the XUL document. If you have a very complex layout, or need customized tabbing behavior, you can set the tabindex attribute in the controls. You can also use the focus function to focus an element depending on events such as window load. You should do this carefully, to avoid having inaccessible controls. You can also use the -moz-user-focus CSS property to enable focusing of elements that typically wouldn't re...
Appendix D: Loading Scripts - Archive of obsolete content
ume that you're previously imported the Services.jsm module. As this module only exists on Firefox 4 and other Gecko 2-based platforms, the services in question will have to be manually loaded on other platforms. <script> tags XUL script tags are traditionally the primary means of loading scripts for extension developers. These tags are generally inserted into XUL overlay files or other XUL documents, after which they are automatically loaded into the context of the XUL window in question and executed immediately and synchronously. Advantages Familiarity: These tags are very similar to the HTML script tags familiar to most web developers. Simplicity: 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 load...
...se tags provide no means to load scripts into a private or otherwise specific scope. Speed: Even if these scripts are loaded from a cache, only read and compile time are reduced. The scripts still need to execute all of their initialization code and allocate and initialize all of their data structures each time the script is loaded. Loading: Script loaded via script tags run in partially loaded documents. Problems can ensue if the script immediately attempts to access DOM nodes. This is easily resolved by deferring the work to a dynamically added onload hander. (A standalone XUL window can use an onload attribute.) Example The following overlay will load the script "overlay.js" from the same directory as the overlay file into the window which it overlays. The script will be read with the UTF-...
...s global namespace, along with as any properties of the global associated with the target object. These scripts execute with the same privileges and restrictions of the global associated with the target object, and this method can therefore also be used when with Sandbox objects with the same effect as evalInSandbox and into content windows with the same effect as injecting script tags into their documents. Advantages Namespacing: Global namespace contamination and the resultant extension compatibility issues can often be avoided by loading sub-scripts into private namespaces. Flexibility: The sub-script loader can load scripts into a variety of different namespaces for a wide variety of uses, and as of Gecko 2 allows the character set of the script to be specified. Performance: As of Gecko ...
...xt or window it was imported from. JavaScript modules can therefor be used for communication and data sharing between otherwise isolated contexts. Debugging: Chromebug (at least) can list Component.utils modules and single step through them. Disadvantages Namespacing: As modules always execute with their own namespace, they have no direct access to the DOM or window properties of windows or documents, and therefore must often pass around references to these objects and any document-specific state data that they require. Examples The following code will import a module into the current global scope. All variables named in the target script's EXPORTED_SYMBOLS global array will be copied into the current execution context. Components.utils.import("resource://my-package/my-module.jsm"); Th...
The Box Model - Archive of obsolete content
It is important to know how it works in order to make interfaces that are easy to localize, skin and use in different types of operating systems, screen sizes and resolutions. The XUL box model is a significant improvement over the HTML layout model, which is mostly vertical. ...
... like an inner margin. Sometimes you also need to define flexible spaces between elements. In this case you should use a spacer element with a flex value. A spacer element is completely invisible and doesn't do more than take space. You should only use it when you need flexible space. If you need fix-sized space it's best to use margins and paddings and avoid adding unnecessary nodes to your XUL document. Alignment XUL, unlike HTML, provides an easy way to align elements both horizontally and vertically. You can either use the align and pack attributes, or the -moz-box-align and -moz-box-pack CSS properties. Packing determines the positioning of the child elements in the direction of the container's orientation. Alignment determines the positioning in the other direction. So, in a flexed hbox, ...
...reak the string using regular expressions and generate 3 different labels, one with the text-link class. You'll also need to do some CSS work on the labels so that the inner spacing in the text looks right. Another option is to take it up a notch and really use HTML. xulschoolhello.linkedText.label = Go to <html:a onclick="%S">our site</html:a> for more information To include HTML in a XUL document, you need to add the namespace for it in the document root: <overlay id="xulschoolhello-browser-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml"> Then you can have an html:p (paragraph) element where you insert the result of parsing the property string. You can easily parse XML using the DOMParser object. Since XUL...
... Exercise Use the DOM Inspector extension to look into the Firefox chrome. Select toolbar buttons, menu items, textboxes, etc. and look into the Box Model, CSS Style Rules and Computed Style views. ...
Signing an XPI - Archive of obsolete content
air must be together. Hint: When applying for a certificate ensure that the Organisation (O) contains your name and not the Issuer's default text, because this is what is displayed to users. For this guide I applied for a free certificate from Unizeto Certum. After completing the application process where I entered my details into the online application, I received an automated email requesting documentary evidence of my ID in the form of a photo-ID or similar. I have hi-resolution scanned images of my passport and drivers license for these situations so I placed them on my web-server temporarily in a hidden location and emailed Unizeto Certum with the details and location of the files. Within a few hours I received a confirmation email from a human accepting the ID images and giving me a hyperl...
...------------------------------ For a list including CA's, use "signtool -L" Now you must export the new key/certificate pair from the Mozilla Firefox certificate database and into the NSS certificate database. The hardest part is locating Mozilla's key database. It consists of two files named key3.db and cert8.db. They usually live in the Mozilla Firefox user profile folder. I found mine in C:\Documents and Settings\TJ\Application Data\Mozilla\Firefox\Profiles\xxxxxxxx.default\ where xxxxxxxx is a random string of characters. This procedure assumes you installed the new certificate into Mozilla Firefox Here's the commands required to export it to a file, import it to the Code Signing database, and verify the signing attributes (u,u,u). Ensure you use the nickname of your certificate in place ...
... into Mozilla Firefox Here's the commands required to export it to a file, import it to the Code Signing database, and verify the signing attributes (u,u,u). Ensure you use the nickname of your certificate in place of mine, and the directory where your Mozilla Firefox key database files are: C:\Projects\CodeSigning> pk12util -o "Certum Code Signing.pkcs12" -n "TJ's Unizeto Sp. z o.o. ID" -d "C:\Documents and Settings\TJ\Application Data\Mozilla\Firefox\Profiles\xxxxxxxx.default" Enter password for PKCS12 file: Re-enter password: pk12util: PKCS12 EXPORT SUCCESSFUL C:\Projects\CodeSigning> pk12util -i "Certum Code Signing.pkcs12" -d . Enter Password or Pin for "NSS Certificate DB": Enter password for PKCS12 file: pk12util: PKCS12 IMPORT SUCCESSFUL C:\Projects\CodeSigning> certutil -L -d . myTest...
...assword with your NSS Certificate database password. Alternatives to NSS/signtool There are several alternatives to using signtool that might suit your needs better, however please note that these alternatives are unofficial third party products. Key Manager XUL Extension Wladimir Palant's Python Script (blog post) xpisign.py Python Script XPISigner Java Tool References The NSS Tools documentation ...
CSS3 - Archive of obsolete content
of the Selectors specification is already in progress, though it still hasn't reached the First Public Working Draft stage. Media Queries Recommendation since June 19th, 2012 Extends the former media type ( print, screen, ... ) to a full language allowing queries on the device media capabilities like only screen and (color) . Media queries are not only used in CSS document but also in some attributes of HTML Elements, like the media attribute of the <link> element. The next iteration of this specification is in the work, allowing to tailor a Web site regarding the input methods available on the user agent, with new media features like hover or pointer. Detection of EcmaScript support, using the script media features is also proposed. CSS Style ...
... border-clip, border-clip-top, border-clip-right, border-clip-bottom, and border-clip-left properties) or to control the shape of the border in a corner (using the CSS border-corner-shape property). CSS Conditional Rules Module Level 3 Candidate Recommendation Adds features for conditional processing of parts of style sheets, conditioned on capabilities of the browser or the document the style sheet is being applied to. It consists mainly in allowing nested at-rules inside @media and the adding of a new CSS at-rule, @supports, and a new DOM method CSS.supports(). CSS Multi-column Layout Module Working Draft Adds support for easy multi-column layouts using the CSS columns, column-count, column-fill, column-gap, column-rule, column-rule-color, column...
...e, and animation-timing-function properties, as well as the @keyframes at-rule. Web Animations Working Draft CSS Text Module Level 3 Working Draft Extends: the CSS text-transform property with the value full-width. the CSS text-align property with the value start, end, start end, and match-parent for a better support of documents with multiple directionalities of text. the CSS text-align property with a <string> value to align on that character. This is useful to align number on the decimal point. the CSS word-spacing and letter-spacing properties with range constraints to control flexibility in justification. Adds: Control on how whitespaces are displayed using the CSS text-space-collapse ...
...Exclusions Module Level 1 Working Draft Extends the floats mechanism to define exclusion regions in any positioning scheme. Adds the notion of shapes, in which content must flows. Filter Effects Module Level 1 Working Draft CSS Generated Content for Paged Media Module Working Draft Adds the ability to tailor printed version of a document by allowing to control header, footer but also references tables like indexes or tables of content. CSS Page Floats Working Draft CSS Grid Layout Unknown CSS Line Grid Module Level 1 Working Draft CSS Positioned Layout Module Level 3 Working Draft CSS Regions Module ...
Case Sensitivity in class and id Names - Archive of obsolete content
g 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 class="warning">WARNING!</p> In Netscape 6, the paragraph in question will have neither red text nor a yellow background. As far as Netscape 6 is concerned, Warning and warning are two different identifiers, because HTML 4.01 defines clas...
...ground. As far as Netscape 6 is concerned, 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 sam...
...identifiers, unless they are designing solely for a truly standards-compliant browser such as Netscape 6. Why So Case-Sensitive? Netscape 6's unusual sensitivity to case is based on a close reading of the HTML 4.01 specification. In section 7.5.2, which defines class and IDs, we find the following text: id = name [CS] This attribute assigns a name to an element. This name must be unique in a document. class = cdata-list [CS] This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters. The marker "[CS]" means "case sensitive," as defined in section 6.1 of the specification. Thus, the Mozilla team, committed to following open standards as closely a...
... space (see section 12.2.3). Thus, even though class and id values are defined to be case-sensitive, there is an aspect of case-insensitivity to the use of id values. Recommendation Because of the flaws which are present in some existing implementations and the restrictions defined in HTML 4.01, it is doubly important to ensure that your class and id names are of a consistent case throughout a document, and that you do not attempt to define names which are case-insensitive matches. Related Links HTML 4.01, section 7.5.2 HTML 4.01, section 12.2.3 Original Document Information Author(s): Eric A. Meyer, Netscape Communications Last Updated Date: Published 05 Mar 2001 Copyright Information: Copyright (C) 2001-2003 Netscape. Note: This reprinted article was originally part of the DevEdg...
List of Mozilla-Based Applications - Archive of obsolete content
ions is also available. Name Description Additional Information 389 Directory Server LDAP server Uses NSS A380 seatback entertainment system media software This blog post mentions a reference to Mozilla being used but I couldn't find more information about it. ...
...emotely on servers that people access through device Conkeror keyboard-oriented browser Convertigo Enterprise Mashup Server server tool for transactional web scraping and for web clipping CometBird another Firefox mod Modified version of Firefox Correo email Couac (fr) web-based email and jabber app CouchDB document-oriented database Uses Spidermonkey Courtanet Benefit (fr) underwriting software for French insurance brokers Crosscheck browserless testing framework Uses Mozilla Rhino Crowbar server tool Cycloctopus screen scraping console Cyclone3 content management system Danger mobile platform Uses Gecko on the ...
... JavaScript extensible tooling framework Uses NSPR and SpiderMonkey Jaxer Ajax server jslibs JavaScript development runtime environment Uses SpiderMonkey (Note: this is separate from the Javascript library jsLib) JoyBidder eBay auction tool Standalone version uses XULRunner jUST (fr) audio A tool for setting temporal tags in audio documents JsDoc Toolkit documentation tool Uses Mozilla Rhino K-Meleon Gecko-based web browser for Windows Embeds Gecko in MFC KaiRo.at Mandelbrot creates images of Mandelbrot sets XULRUnner application Kazehakase Gecko-based web browser for Unix Kirix Strata data browser Kiwix offline version of Wikipedia ...
... applications My Internet Browser localized browser Uses Gecko Myna Application Server JavaScript application server for Java Uses Mozilla Rhino NextCMS (fr) CMS Nightingale music player Community run effort to continue Songbird support for Linux OLPC Web Browser browser OneTeam Jabber client OpenDocument Viewer viewer OpenGate's tools CD burner, file browser, and hardware diagnostic softwares OpenGate is the OpenSource side of the EasyNeuf project, "A Free Software Computer, Easy and Preinstalled" Open Mashups development tool OpenOffice.org office suite Uses NSS Openswan implementation of IPsec for Linux Uses NSS Orca B...
Editor Embedding Guide - Archive of obsolete content
indow call. Then simply call nsIWebBrowser->do_GetInterface on the nsIWebBrowser to retrieve the nsIEditingSession from it. From there you call editingSession->MakeWindowEditable(domWindow, editortype, PR_TRUE). The first parameter is the nsIDOMWindow you just retrieved, the second is the editor type you want to create, and the third is whether you want the window editable immediately or when the document is done loading. In calling this method, the editor is created underneath and the event listeners are all prepa if (NS_FAILED(rv)) return NS_ERROR_FAILURE; // we are not setup??!! nsCOMPtr<nsIEditingSession> editingSession; nsIWebBrowser->do_GetInterface(getter_AddRefs(editingSession)); if (editingSession) editingSession->MakeWindowEditable(domWindow, "html", PR_TRUE); The valid editor types are...
...n) DoCommand no parameters Note Only available if txmgr.dll is present. cmd_fontColor Acts upon the current selection to set the font color. GetCommandState "state_attribute" (cstring) DoCommand "state_attribute" (cstring) Note For color values, use the cstring representation of RRGGBB, e.g., RED="#FF0000" and BLACK="#000000". cmd_backgroundColor Sets the background color of the document. GetCommandState "state_attribute" (cstring) DoCommand "state_attribute" (cstring) Note For color values, use the cstring representation of RRGGBB, e.g., RED="#FF0000" and BLACK="#000000". cmd_fontFace Sets the font face for the current selection. GetCommandState "state_attribute" (cstring) DoCommand "state_attribute" (cstring or string) "Helvetica, Arial, sans-serif" ...
...se functionality and in no way imply that this command won't handle other fonts. cmd_align Sets the alignment for the lines contained in the current selection. GetCommandState "state_attribute" (cstring) DoCommand "state_attribute" (cstring) "left", "right", "center", "justify" cmd_insertHTML cmd_insertLinkNoUI cmd_insertImageNoUI cmd_insertHR cmd_charSet Sets the charset for the document. GetCommandState "state_attribute" (cstring) DoCommand "state_attribute" (cstring) Note There must be a clear undo stack or this will not work. cmd_copy Copies current selection. GetCommandState "state_enabled" (boolean) DoCommand no parameter Note GetCommandState in these cases will return whether or not it is possible to call DoCommand. This will not really give you any concr...
.../value pair is known or it was obtained using the methods described above, it is possible to call the following methods: GetBooleanValue GetLongValue GetDoubleValue GetStringValue GetCStringValue GetISupportsValue All of these take pointers to values except for GetStringValue which demands a reference to an nsAString. commandParam->GetBooleanValue("state_enabled",&boolval); Original Document Information Authors: Michael Judge (mjudge@netscape.com) Contributor: Kathleen Brade (brade@netscape.com) Last Updated Date: March 27, 2003 Original Document: A Guide to Embedding The Gecko Editor ...
Introducing the Audio API extension - Archive of obsolete content
efox 22 / Thunderbird 22 / SeaMonkey 2.19)This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. Please note that this document describes a non-standard experimental API. This API has been deprecated since Gecko 22, disabled since Gecko 28, and removed from Gecko 31. You should use the Web Audio API instead. Reading audio streams The loadedmetadata event When the metadata of the media element is available, it triggers a loadedmetadata event. This event has the following attributes: mozChannels: Number of channels m...
...Once the buffer is full, the event MozAudioAvailable is triggered. ...
...zChannels; rate = audio.mozSampleRate; frameBufferLength = audio.mozFrameBufferLength; } function audioAvailable(event) { var frameBuffer = event.frameBuffer; var t = event.time; var text = "Samples at: " + t + "\n"; text += frameBuffer[0] + " " + frameBuffer[1]; raw.innerHTML = text; } var raw = document.getElementById('raw'); var audio = document.getElementById('audio-element'); audio.addEventListener('MozAudioAvailable', audioAvailable, false); audio.addEventListener('loadedmetadata', loadedMetadata, false); </script> </body> </html> Creating an audio stream It is also possible to create and setup an <audio> element for raw writing from script (i.e., without a src at...
...udio stream Since the MozAudioAvailable event and the mozWriteAudio() method both use Float32Array values, it is possible to take the output of one audio stream and pass it directly (or process first and then pass) to a second. The first audio stream needs to be muted so that only the second audio element is heard. <audio id="a1" src="song.ogg" controls> </audio> <script> var a1 = document.getElementById('a1'), a2 = new Audio(), buffers = []; function loadedMetadata() { // Mute a1 audio. a1.volume = 0; // Setup a2 to be identical to a1, and play through there. a2.mozSetup(a1.mozChannels, a1.mozSampleRate); } function audioAvailable(event) { // Write the current framebuffer var frameBuffer = event.frameBuffer; writeAudio(frameBuffer); } a1.addEventListener('...
New Security Model for Web Services - Archive of obsolete content
ss.xml which contains the "delegate" keyword delegates to http://www.example.com/foo/web-scripts-access.xml. If the URI is in a subdirectory, and the root directory's access file delegated but no access file exists in the subdirectory, then no access is granted. If the root's access file did not delegate, then that access file also handles all resources in subdirectories. Any syntax error in the document will result in the rest of the file to be ignored. Since the commands only allow access, the order of processing the "allow" commands that were successfully parsed is never significant. Allowing Web Script Access To permit scripts to access the resources of this server, use the following command: <wsa:allow type="<request-type>" from ="<uri-prefix>"/> The type of request, if specified, will ...
... found in the cache creates one by loading the declaration file (web-scripts-access.xml) and extracting information from it (declaration file); requested type and subject princple's prefix are compared to the allowed type and prefix in order to determine access. An entry is created if and only if the declaration file is considered valid (validation based on the syntax described above); an invalid document will result in access denial. Denies script access in the event of an xml-wellformedness error, or validation error, or if the declaration file does not grant access. Reports errors (validation, wellformedness, file not found, etc.) to the console via nsIConsoleService. Note: Script access is checked via declaration file only if the script security manager denies access. Summary Advantages ...
...a server spans multiple owners, the alternative would be to scan all directories in the path looking for a web scripts access file, which seems undesirable. On the other hand, perhaps it is not so bad, since it permits independent management in domains where the top level owner may not care about providing access to web services. ...
...access to web services. Adjustments As this new model is applied to SOAP, and potentially document.load or xml-request, it may be desirable to eliminate the same source security bypass, because it is not clear that this is always secure. Other security adjustments may be desired as well. ...
RDF Datasource How-To - Archive of obsolete content
This article is at least partially outdated. Help bring it up to date, if you can. The XPCOM registration parts and the "As of this writing, it is not currently possible to implement JavaScript XPCOM components" comment seem outdated didn't check the whole article. This document is a cookbook that describes how to create a native, client-side datasource that works with Mozilla's RDF implementation. It supersedes (and borrows from) the original document put together by Robert Churchill. What is a datasource? The "RDF universe" consists of a set of statements about Internet resources; for example, "my home page was last modified April 2nd", or "that news article was sent by Bob". In the most abstract sense, a datasource is a collection of such statements. More concretely, a datasource is a transl...
...ch, it must (currently, see [1]) have: An XPCOM CLSID to identify the data source implementation An implementation class (that corresponds to the CLSID) whose code lives in a DLL. The DLL must be located in the XPCOM components directory A factory that is registered to an XPCOM ProgID in order to be instantiated from the repository. Constructing a DLL for a component is beyond the scope of this document; the reader is referred to the RDF factory as a guideline. Registering an RDF datasource is fairly simple: in the DLL's NSRegisterSelf() method, you simply call the component manager's RegisterComponent() method: extern "C" PR_IMPLEMENT(nsresult) NSRegisterSelf(nsISupports* aServiceManager, const char* aPath) { nsresult rv; ... // Assume compMgr refers to the component manager rv = co...
...ell>Name</treecell> <treecell>URL</treecell> </treeitem> </treehead> <!-- treechildren built _here_ --> </tree> </window> The important "magic attributes" have been called out in bold, above: datasources="rdf:my-datasource". This is a space-separated list that may include internal XPCOM datasource "identifiers" (as described above) and URIs for local or remote RDF/XML documents. Each datasource that is listed will be loaded, and the assertions contained in the datasource will be made available to the tree control for display. ref="http://foo.bar.com/". This roots the graph in your content model. The tree tag will be treated as if it has the ID attribute with a value http://foo.bar.com/. <template>...</template>. The XUL template that is used to build content from t...
... the pattern specified within the template tags. For a complete description of how content is built from RDF, see the XUL:Template Guide. ...
Extensions - Archive of obsolete content
Firefox context menu. Showing and hiding context menu items To have a menuitem you have added be shown or hidden based on the context, you can use an event handler that listens for the popupshowing event. For instance, if an image was context clicked, you may wish to hide the menu item you have added if the operation it performed wouldn't apply to images. ...
...r instance, if an image was context clicked, you may wish to hide the menu item you have added if the operation it performed wouldn't apply to images. function init() { var contextMenu = document.getElementById("contentAreaContextMenu"); if (contextMenu) contextMenu.addEventListener("popupshowing", ThumbnailsShowHideItems, false); } function ThumbnailsShowHideItems(event) { var show = document.getElementById("thumbnail-show"); show.hidden = (document.popupNode.localName != "IMG"); } The init function should be called within the handler for the load event so that the popupshowing event handler is hooked up before it would be opened by the user. In this example, the ThumbnailsShowHideItems function will be called when the popup is about to be shown. This function retrieves the menuit...
...oad event so that the popupshowing event handler is hooked up before it would be opened by the user. In this example, the ThumbnailsShowHideItems function will be called when the popup is about to be shown. This function retrieves the menuitem with the id 'thumbnail-show' that was added by the extension and hides it if an image was not the target of the context menu. The popupNode property of the document holds the target of the context menu. For more details about hiding and showing items on a context menu, see Hiding and Showing Menu Items based on Context. Determining what element was context clicked For general information about how to determine which element was the target of the context menu, that is, the element that was context clicked, see Determining what was Context Clicked Firefox ...
...text click occured from within a frame. isTextSelected True if text is selected. ...
Property - Archive of obsolete content
alwaysOpenPopup amIndicator appLocale autoCheck autoFill autoFillAfterMatch boxObject browsers builder builderView buttons canAdvance canGoBack canGoForward canRewind checked checkState child children className clickSelectsAll clientHeight clientWidth collapsed color columns command commandManager completeDefaultIndex container contentDocument contentPrincipal contentTitle contentView contentViewerEdit contentViewerFile contentWindow contextMenu control controller controllers crop current currentIndex currentItem currentNotification currentPage currentPane currentSet currentURI customToolbarCount database datasources date dateLeadingZero dateValue decimalPlaces decimalSymbol defau...
...current currentIndex currentItem currentNotification currentPage currentPane currentSet currentURI customToolbarCount database datasources date dateLeadingZero dateValue decimalPlaces decimalSymbol defaultButton defaultValue description dir disableAutocomplete disableAutoComplete disableautoselect disabled disableKeyNavigation dlgType docShell documentCharsetInfo editable editingColumn editingRow editingSession editor editortype emptyText Deprecated since Gecko 2 enableColumnDrag eventNode firstOrdinalColumn firstPermanentChild flex focused focusedItem forceComplete group handleCtrlPageUpDown handleCtrlTab hasUserValue height hidden hideSeconds highlightNonMatches homePage hour hourLeadingZe...
...roup handleCtrlPageUpDown handleCtrlTab hasUserValue height hidden hideSeconds highlightNonMatches homePage hour hourLeadingZero id ignoreBlurWhileSearching image increment inputField inverted is24HourClock isPM isSearching isWaiting itemCount label labelElement lastPermanentChild lastSelected left linkedPanel listBoxObject locked markupDocumentViewer max maxHeight maxLength maxRows maxWidth menu menuBoxObject menupopup min minHeight minResultsForPopup minWidth minute minuteLeadingZero mode month monthLeadingZero name next noMatch notificationsHidden object observes onFirstPage onLastPage open ordinal orient pack pageCount pageid pageIncrement pageIndex pageStep parent...
...ent.clientLeft DOM:element.clientTop DOM:element.clientWidth DOM:element.cloneNode DOM:element.firstChild DOM:element.firstElementChild DOM:element.lastChild DOM:element.lastElementChild DOM:element.localName DOM:element.namespaceURI DOM:element.nextElementSibling DOM:element.nextSibling DOM:element.nodeName DOM:element.nodeType DOM:element.nodeValue DOM:element.ownerDocument DOM:element.parentNode DOM:element.prefix DOM:element.previousElementSibling DOM:element.previousSibling DOM:element.scrollHeight DOM:element.scrollLeft DOM:element.scrollTop DOM:element.scrollWidth DOM:element.tagName DOM:element.textContent ...
Filtering - Archive of obsolete content
st, and the template results should be filtered based on that value. This can be done by modifying the DOM nodes inside the query and rebuilding the template. For instance, to apply a filter, you might add a new <triple> element. To remove the filter, the <triple> should be removed again. Let's assume that we've given an id of 'cond' to the query tag. ...
...based on that value. This can be done by modifying the DOM nodes inside the query and rebuilding the template. For instance, to apply a filter, you might add a new <triple> element. To remove the filter, the <triple> should be removed again. Let's assume that we've given an id of 'cond' to the query tag. ...
...ding the template. For instance, to apply a filter, you might add a new <triple> element. To remove the filter, the <triple> should be removed again. Let's assume that we've given an id of 'cond' to the query tag. ...
...If this is set, we add a filter, otherwise we remove it. The code is fairly straightforward. A new <triple> element is created and the object attribute is set to the value to filter by. ...
XML Templates - Archive of obsolete content
<< PreviousNext >> Mozilla also supports the use of XML datasources. An XML document will be loaded and XPath expressions may be used to take portions of the XML document and generate content from these. When an XML source is desired, specify a querytype attribute on the root node of the template to the value xml. This indicates to the template builder that an XML source is being used as that the queries use syntax that is specific to XML. The datasources attribute should be set to the URL of an XML document, either a local file or a remote web site. The ref attribute isn't currently used for XML sources, as the root of the document is always the starting point for XML queries; you should just set the ref attribute to a dummy value, for example '*' which is typically used. An ex...
...solute URL. Note: If you want to have the state of the disclosure triangles ("twisties") be persistent, be sure to give each node a unique "id" attribute. These are used to track the current state of the disclosure triangles. Support for this was introduced in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4). For this and the following examples, we are going to use the following XML document containing a list of people: <people> <person name="Napoleon Bonaparte" gender="male"/> <person name="Cleopatra" gender="female"/> <person name="Julius Caesar" gender="male"/> <person name="Ferdinand Magellan" gender="male"/> <person name="Laura Secord" gender="female"/> </people> XML Query Syntax The query syntax is fairly simple for XML datasources. Just place an expr attribute on ...
...rns the set of results to output. Here is an example: <listbox datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="person"/> <action> <listitem uri="?" label="?name"/> </action> </template> </listbox> The expr attribute is a very simple XPath expression which simply retrieves the person elements from within the datasource. As there are five in the XML document, five results will be generated. The action element defines the content to generate for each result. The content of the action element will be generated and repeated for each result, which in this case, is a listitem. The child of the action element has to have a uri attribute, although it does not have to be a direct child. The element with the uri attribute and its children will be copied once...
...abel. The query does not have to be as simple as the one used here. Any XPath expression may be used. For instance, the following query returns only those results for female people. <query expr="person[@gender='female']"/> As long as the expression returns one or more nodes, it can be used in an query expression. Using Inline XML It's also possible to embed the XML data directly within the XUL document if desired. Instead of using a URL for the datasources attribute, you can use an anchor reference to refer to a node within the same document. The effect is the same, but the data isn't stored in a separate file. <people id="famouspeople" xmlns=""> <person name="Napoleon Bonaparte" gender="male"/> <person name="Cleopatra" gender="female"/> <person name="Julius Caesar" gender="male"/> <pe...
Things I've tried to do with XUL - Archive of obsolete content
invisible HTML-Element in order to access its "clientWidth" method: <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml"> ... <html:body id="invisible_element" flex="1" > <svg xmlns="http://www.w3.org/2000/svg" version="1.1"><!-- ...or _visible_ XUL content or whatever... --></svg> </html:body> ... var available_width = document.getElementById("invisible_element").clientWidth; ... XBL in listboxes Using XBL bindings in listboxes is not easy because there is a big bug there: if you create from JS an element you want to bind, and if it is hidden when the listbox is first rendered, the listbox does not create a frame for it, and the xbl doesn't get attached... A workaround for that is to create the element, insert it in ...
...ElementById("invisible_element").clientWidth; ... XBL in listboxes Using XBL bindings in listboxes is not easy because there is a big bug there: if you create from JS an element you want to bind, and if it is hidden when the listbox is first rendered, the listbox does not create a frame for it, and the xbl doesn't get attached... ...
... While this works at first, after a number of rows have been added it breaks and stops displaying the first cell (the one specified by the appendItem call). ...
...bute('label', label2 ); cell.setAttribute('value', value2 ); row.appendChild( cell ); // etc // ... While this works at first, after a number of rows have been added it breaks and stops displaying the first cell (the one specified by the appendItem call). Instead, you must build up your own listitem full of listcells, and then add that listitem to the listbox, using generic DOM calls: var row = document.createElement('listitem'); // Create and attach 1st cell var cell = document.createElement('listcell'); cell.setAttribute('label', label ); cell.setAttribute('value', value ); row.appendChild( cell ); // Create and attach 2nd cell cell = document.createElement('listcell'); cell.setAttribute('label', label2 ); cell.setAttribute('value', value2 ); row.appendChild( cell ); // etc // ... // Attach ro...
Adding Event Handlers - Archive of obsolete content
y DOM Events. When an action occurs that would trigger an event, such as the user moving the mouse, an event object is created corresponding to that event type. Various properties are set on the event object such as the mouse position, the key that was pressed, and so forth. The event is then sent to the XUL in phases. In the capturing phase, the event is first sent to the window, then to the document, followed by each ancestor of the XUL element where the event occured downwards until it reaches that element. In the target phase, the event is sent to the target XUL element. In the bubbling phase, the event is sent to each element back upwards until it reaches the window again. You can respond to an event during either the capturing or bubbling phase. Once the event has finished propagatin...
... back upwards until it reaches the window again. You can respond to an event during either the capturing or bubbling phase. Once the event has finished propagating, any default action will occur, which is the built in behaviour of the element. For example, when the mouse is moved over a button that is inside a box, a 'mousemove' event is generated, and sent first to the window, followed by the document, and then the box. That completes the capturing phase. Next, the 'mousemove' event is sent to the button. Finally, the bubbling phase causes the event to be sent to the box, document and window. The bubbling phase is essentially the reverse of the capturing phase. Note that some events don't do the bubbling phase. You can attach listeners to each element to listen to the events during each step ...
...y used property is the 'target' property of the event, which holds the element where the event actually occured. In the example we display an alert containing the target's tag name. The target is useful when using a bubbling event so that you could have a set of buttons which are all handled by a single script. You might notice that the attribute syntax is similar to that used for events in HTML documents. In fact, both HTML and XUL share the same event mechanism. One important difference is that while the 'click' event (or the onclick attribute) is used in HTML to respond to buttons, in XUL the command event should be used instead. XUL does have a click event, but it only responds to mouse clicks, not to keyboard usage. Thus, the click event should be avoided in XUL, unless you have a reason to ...
...utton. DOM Event Listeners The second way to add an event handler is to call an element's addEventListener method. This allows you to attach an event listener dynamically and listen for events during the capturing phase. The syntax is as follows: Example 3 : Source View <button id="okbutton" label="OK"/> <script> function buttonPressed(event){ alert('Button was pressed!'); } var button = document.getElementById("okbutton"); button.addEventListener('command', buttonPressed, true); </script> The getElementById() function returns the element with a given id, in this case the button. The addEventListener() function is called to add a new capturing event listener. The first argument is the name of the event to listen to. The second argument is the event listener function which will be called...
Commands - Archive of obsolete content
uttons and menu items hooked up to it will be disabled automatically. If you re-enable the command, the buttons will become enabled again. Example: Toggling command disabled Example 2 : Source View <command id="cmd_openhelp" oncommand="alert('Help');"/> <button label="Help" command="cmd_openhelp"/> <button label="More Help" command="cmd_openhelp"/> <button label="Disable" oncommand="document.getElementById('cmd_openhelp').setAttribute('disabled','true');"/> <button label="Enable" oncommand="document.getElementById('cmd_openhelp').removeAttribute('disabled');"/> In this example, both buttons use the same command. When the Disable button is pressed, the command is disabled by setting its disabled attribute, and both buttons will be disabled as well. It is normal to put a gro...
...r, since editing commands invoked from the main menu will work inside the content area. Note that HTML also has a commands and controller system although you can't use it on unprivileged web pages, but you may use it from, for example, a browser extension. If the window doesn't provide a controller capable of handling the command, nothing will happen. You can get the command dispatcher using the document's commandDispatcher property, or you can retrieve it from the controllers list on an element or a window. The command dispatcher contains methods for retrieving controllers for commands and for retrieving and modifying the focus. Adding Controllers You can implement your own controllers to respond to commands. You could even override the default handling of a command with careful placement of t...
... delete a row. (See Discussion about opening this example). The example below isn't completely polished. Really, we should ensure that the selection and focus is adjusted appropriately after a deletion. ...
...llerAt method which inserts a controller into an element before other ones. This might be useful to override commands. For example, the following example will disable pasting into a textbox. var tboxController = { supportsCommand : function(cmd){ return (cmd == "cmd_paste"); }, isCommandEnabled : function(cmd){ return false; }, doCommand : function(cmd){ }, onEvent : function(evt){ } }; document.getElementById("tbox").controllers.insertControllerAt(0,tboxController); In this example, we insert the controller at index 0, which means before any others. The new controller supports the 'cmd_paste' command and always indicates that the command is disabled. The default textbox controller never gets called because the command dispatcher found the controller above to handle the command first. ...
Creating Dialogs - Archive of obsolete content
ending on the platform the application is running on. In addition, the openDialog() function can take additional arguments beyond the first three. These arguments are passed to the new dialog and placed in an array stored in the new window's arguments property. You can pass as many arguments as you wish. This is a convenient way to supply default values to the fields in the dialog. var somefile=document.getElementById('enterfile').value; window.openDialog("chrome://findfile/content/showdetails.xul","showmore", "chrome",somefile); In this example the dialog showdetails.xul is displayed. It's passed one argument, somefile, which was taken from the value of an element with the ID enterfile. In a script used by the dialog, we can then refer to the argument using the window's arg...
...://findfile/content/showdetails.xul","showmore", "chrome",somefile); In this example the dialog showdetails.xul is displayed. It's passed one argument, somefile, which was taken from the value of an element with the ID enterfile. In a script used by the dialog, we can then refer to the argument using the window's arguments property. For example: var fl = window.arguments[0]; document.getElementById('thefile').value = fl; This is an effective way to pass values to the new window. You can pass values back from the opened window to the original window in one of two ways. First, you could use the window.opener property which holds the window that opened the dialog. Second, you could pass a function or object as one of the arguments when creating the dialog, then call that funct...
... Next, we'll see how to open file dialogs. << PreviousNext >> ...
... Next, we'll see how to open file dialogs. << PreviousNext >> ...
More Event Handlers - Archive of obsolete content
on about the events. To manually stop event propagation, call the event object's stopPropagation method, as in the following example. Example 2 : Source View <hbox id="outerbox"> <button id="okbutton" label="OK"/> </hbox> <script> function buttonPressed(event){ alert('Button was pressed!'); } function boxPressed(event){ alert('Box was pressed!'); event.stopPropagation(); } var button = document.getElementById("okbutton"); button.addEventListener('command',buttonPressed,true); var outerbox = document.getElementById("outerbox"); outerbox.addEventListener('command',boxPressed,true); </script> Here, an event listener has been added to the button and another event listener has been added to the box. The stopPropagation method has been called in the box's listener, so the button's listener ...
...ill be set to 0. Mouse Position Event Properties However, all mouse events will be supplied with properties that hold the coordinates of the mouse position where the event occurred. There are two sets of coordinates. The first is the screenX and screenY properties and are relative to the top left corner of the screen. The second set, clientX and clientY, are relative to the top left corner of the document. ...
...ts of coordinates. The first is the screenX and screenY properties and are relative to the top left corner of the screen. The second set, clientX and clientY, are relative to the top left corner of the document. Here is an example which displays the current mouse coordinates: Example 4 : Source View <script> function updateMouseCoordinates(e){ var text = "X:" + e.clientX + " Y:" + e.clientY; document.getElementById("xy").value = text; } </script> <label id="xy"/> <hbox width="400" height="400" onmousemove="updateMouseCoordinates(event);"/> In this example, the size of the box has been set explicitly so the effect is easier to see. The event handler gets the clientX and clientY properties and creates a string from them. This string is then assigned to the value property of the label. Note th...
...hat can be retrieved using the boxObject property. We'll learn more about the box object in a later section, but it holds information pertaining to how the element is displayed, including the x and y position of the element. In this example code, these coordinates are subtracted from the event coordinates to get the event position relative to the element. Load Events The load event is sent to the document (the window tag) once the XUL file has finished loading and just before the content is displayed. This event is commonly used to initialize fields and perform other tasks that need to be done before the user can use the window. You should use a load event to do these kinds of things as opposed to adding a script at the top level outside of a function. This is because the XUL elements may not have...
XUL Event Propagation - Archive of obsolete content
in the target itself or any of the intervening nodes. In the diagram above, the alert dialog invoked by the menuitem itself is not displayed, since the root window element has used event capture to handle the event itself. In another example, an onload event handler for a XUL window can register a box element to capture all the click events that are raised from its child elements: var bbox = document.getElementById("bigbox"); if (bbox) bbox.addEventListener("click", function() { alert('captured'); }, true); ... <box id="bigbox"> <menu value="File"> <menupopup> <menuitem value="New" onclick="alert('not captured')" /> ... <menupopup> </menu> </box> Adding an Event Listener In order to take advantage of event capturing (or event bubbling with elements that do not...
...x> Adding an Event Listener In order to take advantage of event capturing (or event bubbling with elements that do not already have event listeners), you must add an event listener to the element that wants to capture events taking place below it. Any XUL element may use the DOM addEventListener method to register itself to capture events. The syntax for this in XUL is as follows: element = document.getElementById("id of the element"); element.addEventListener(event name, event handler function, whether to register a capturing listener); The event handler code argument can be in-line code or a function. The last boolean parameter specifies whether the event listener wants to use event capturing, or be registered to listen for events that bubble up the hiearchy normally. Note: The DOM prov...
... nodes that do not otherwise supply them. But in XUL, almost every element includes an "oncommand" event listener attribute for getting events. ...
...ost every element includes an "oncommand" event listener attribute for getting events. ...
tree - Archive of obsolete content
Archive › Mozilla › XUL › tree
s property. Trees built from RDF or those which use treeitems directly will already have a view. Functions available in the view allow one to retrieve the data within the cells, and determine which rows are nested within others. For a complete list of view functions, see the nsITreeView interface. ...
... XUL for the tree: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <?xml-stylesheet href="file://C:/main.css" type="text/css"?> <window xmlns="http://ww...
... XUL for the tree: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <?xml-stylesheet href="file://C:/main.css" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/...
... ...
Getting started with XULRunner - Archive of obsolete content
ming that it doesn't need to hook into my Windows system and that's a good thing. It also means that the XULRunner is portable so, if you develop your applications to be portable you could carry them around on a flash drive or sync them in the cloud. The Mac version of XULRunner is distributed as an tar.bz2 archive. You can extract this to any location you like, but there are many places in the documentation that will assume that you have this installed in /Library/Frameworks. In Ubuntu desktop and its variants (Xubuntu, Kubuntu, ...), from version 11.10 (Oneiric Ocelot), XULRunner is not longer maintained and doesn't exist in Ubuntu repository. Therefore, either you need to compile XULRunner manually or download a binary release from Mozilla's FTP server. One way to achieve this is to run the ...
...en use your normal filesystem's decompression tool to open it up. The contents of omni.ja are available to XULRunner applications and are what make it possible to build amazing applications easily! Step 3: Create the application folder structure Time to start a simple, bare bones application shell. Call it a XUL "Hello World" if you want. All of what you see below can be found in the XULRunner documentation here on MDN in much more detail. Hint: Skip ahead and download the sample application, you can experiment with it while following this tutorial. You can download the sample application from https://github.com/matthewkastor/XULRunner-Examples. Please continue reading to learn the "what", "why" and "how" parts of building a XULRunner application. On Windows, I created the root in a new c:\...
... 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 application The moment of truth. We need to get XULRunner to launch the bare-bones application. Windows From a Windows command prompt opened to the myapp folder, we should be able to execute this: C:\p...
...ou might want to read the XULRunner tips article. ...
2006-10-06 - Archive of obsolete content
06, 2006 Announcements Mac user needed Scott MacGregor announced that .mac support and a dynamically add ISP account feature has been added to the Thunderbird account manager, however, testing is required before release can be issued. Hence, they are looking for a Mac user to test out the new features by building a mac.rdf file with all of the various .mac account properties mentioned in the document here. Discussions Is Thunderbird using a valid W3C coding? Peter Lairo requested someone who are knowledgeable in W3C standards to confirm if the use of <blockquote type="cite"> is valid W3C code. Q & A Q: Walt experienced an unusual behaviour in his build and wanted to perform an experiment to figure out the problem, but he couldn't find the mozilla.org's config file. A: Robert Helmer...
...Q: Walt experienced an unusual behaviour in his build and wanted to perform an experiment to figure out the problem, but he couldn't find the mozilla.org's config file. A: Robert Helmer pointed out the mozilla.org's config file could be found here and to look for -->mozconfig<---------------------------------------- -->end mozconfig<---------------------------------------- Updated: Developer documentation issues for Thunderbird 2 Eric Shepherd has requested feedback for any developer documentation issues that might need dealing with for Thunderbird 2. Discussion highlights: Ziga Sancin suggests writing an introductory article for potential developers containing basic project information (history, list of main developers, project goals, roadmap and available communication channels, etc), to...
...s requested feedback for any developer documentation issues that might need dealing with for Thunderbird 2. Discussion highlights: Ziga Sancin suggests writing an introductory article for potential developers containing basic project information (history, list of main developers, project goals, roadmap and available communication channels, etc), tools needed to start developing and building TB, documentation on source structure as well as links to help one get started on the project. David Bienvenu suggests a top down architectural description of TB's data structures along with documentation about extracting them. Brian King also mentions that documentation on handling message headers on the UI side would be helpful. ...
... Updated : Need UI to Rearrange Tags Peter Lairo suggested some UI should be available for rearranging tags. Related: bug 342065 Meetings None for this week. ...
NPEvent - Archive of obsolete content
wParam 32 bit field for the Windows event parameter; parameter value depends upon event type. lParam 32 bit field for the Windows event parameter; parameter value depends upon event type. EventRecord NPEvent on Mac OS NPEvent is defined as an EventRecord data structure, which has the following fields: what Integer representing an event type. Both windowed and windowless plug-ins receive ...
...ng fields: what Integer representing an event type. Both windowed and windowless plug-ins receive the same events. Values: 0 nullEvent 1 mouseDown 2 mouseUp 3 keyDown 4 keyUp 5 autoKey 6 updateEvt 7 diskEvt 8 activateEvt 15 osEvt 23 kHighLevelEvent getFocusEvent 0, 1 (true, false) loseFocusEvent adjustCursorEvent 0, 1 (true, false) For information about these events, see the Mac OS developer documentation. message LongInt. Additional information about the event. Type of information depends on the event type. Undefined for null, mouseUp, and mouseDown events. when LongInt. Ticks since start-up. where Point. Cursor location. modifiers Integer. Flags. XEvent NPEvent on Unix/X11 NPEvent is defined as an XEvent data structure, which is a union of a number of different X11 event structures. ty...
...ating which structure is relevant. The event type may be any of the ollowing: GraphicsExpose FocusIn FocusOut EnterNotify LeaveNotify MotionNotify ButtonPress ButtonRelease KeyPress KeyRelease Description Microsoft Windows Description The type NPEvent represents an event passed by NPP_HandleEvent() to a windowless plug-in. For information about these events, see your Microsoft Windows documentation. Mac OS Description The NPEvent object represents an event passed by NPP_HandleEvent() to a windowless plug-in. This structure is defined as EventRecord, the event type used by Mac OS. On Mac OS, plug-ins receive the same events for both windowed and windowless plug-ins, as follows. Mouse events: Sent if the mouse is within the bounds of the instance. Key events: Sent if the instance has...
...ou don't want a special cursor, return false and the browser will use the standard arrow cursor. XWindows Description The NPEvent object represents an event passed by NPP_HandleEvent() to a windowless plug-in. The NPEvent structure is defined as XEvent, the definition of the event type used by the XWindows platform. For information about the XEvent structure and XWindows events, see the XWindows documentation. As the XEvents sent to the plug-in are synthesized and there is not a native window corresponding to the plug-in rectangle, some of the members of the XEvent structures are not set to their normal Xserver values. e.g. Key events don't have a position. Mouse events have x and y coordinates relative to the top-left corner of the plugin rectangle. See Also NPP_HandleEvent() ...
The First Install Problem - Archive of obsolete content
Problem Definition The First Install Problem is the name given to the conditions arising when a plugin or embeddable software installs itself on a system first, before any other Gecko-based browser. If this happens, Gecko-based browsers often won't be able to discover the plugin, and will prompt the user to download the plugin again if the affiliated MIME type is encountered on the Web. ...
...d will prompt the user to download the plugin again if the affiliated MIME type is encountered on the Web. Unless Gecko does a pre-emptive scan upon startup for desirable plugins that are not in the browser's plugins directory first, the best way to solve this problem is to encourage plugin vendors to leave DLLs (and XPT files, if applicable) in a location that Gecko can discover at runtime. This document presents a consistent way to do that. Proposed Solution On Mac OS X, the System's Plugins Folder will probably suffice as an install location in which browsers installed later can find their plugins. On Linux, a per-profile installation of plugins seems unavoidable. This document presents Windows solutions for plugin vendors. The solution suggests that plugin vendors ought to leave DLLs on a Win...
... of plugins seems unavoidable. This document presents Windows solutions for plugin vendors. The solution suggests that plugin vendors ought to leave DLLs on a Windows desktop whether or not a Netscape Gecko browser is detected, and then write keys in the Windows registry giving future Netscape Gecko browsers the path where the plugin resides and meta-information about how to load the plugin. This document supplements the key parsing methodology suggested for installers. The solution is to encourage plugin vendors to write registry keys to the Win32 System Registry, like the example application. ...
...browser is detected, and then write keys in the Windows registry giving future Netscape Gecko browsers the path where the plugin resides and meta-information about how to load the plugin. This document supplements the key parsing methodology suggested for installers. The solution is to encourage plugin vendors to write registry keys to the Win32 System Registry, like the example application. This document proposes a meta-information model in the Win32 Registry similar to the one used by Microsoft's HKEY_CLASSES_ROOT\CLSID\ where a new ActiveX control (OCX) on the system presents its UUID as a registry key (identifying the ActiveX control) as well as information about where to find the OCX (e.g. under the InprocServer32 subkey). For Mozilla-based browsers, this system would be on a per-module basis...
Introduction to SSL - Archive of obsolete content
Introduction This document introduces the Secure Sockets Layer (SSL) protocol. SSL has been universally accepted on the World Wide Web for authenticated and encrypted communication between clients and servers. The SSL Protocol Ciphers Used with SSL The SSL Handshake The new Internet Engineering Task Force (IETF) standard protocol called Transport Layer Security (TLS) is based on SSL. The details of the protocol are available in Request For Comments (RFC): 2246,The TLS Protocol Version 1.0. Some Red Hat products already support TLS. Most other Red Hat products plan to support the protocol in future versions. This document is primarily intended for administrators of Red Hat server products, but the information it contains may also be useful for developers of applications that support SSL. ...
...he protocol are available in Request For Comments (RFC): 2246,The TLS Protocol Version 1.0. Some Red Hat products already support TLS. Most other Red Hat products plan to support the protocol in future versions. This document is primarily intended for administrators of Red Hat server products, but the information it contains may also be useful for developers of applications that support SSL. The document assumes that you are familiar with the basic concepts of public-key cryptography, as summarized in "Introduction to Public-Key Cryptography." The SSL Protocol The Transmission Control Protocol/Internet Protocol (TCP/IP) governs the transport and routing of data over the Internet. Other protocols, such as the HyperText Transport Protocol (HTTP), Lightweight Directory Access Protocol (LDAP), or I...
...public-key techniques, then allows the client and the server to cooperate in the creation of symmetric keys used for rapid encryption, decryption, and tamper detection during the session that follows. Optionally, the handshake also allows the client to authenticate itself to the server. The exact programmatic details of the messages exchanged during the SSL handshake are beyond the scope of this document. However, the steps involved can be summarized as follows (assuming the use of the cipher suites listed in "Cipher Suites With RSA Key Exchange"): The client sends the server the client's SSL version number, cipher settings, randomly generated data, and other information the server needs to communicate with the client using SSL. The server sends the client the server's SSL version number, cip...
...sources? The server checks what resources the client is permitted to access according to the server's access control lists (ACLs) and establishes a connection with appropriate access. If the server doesn't get to step 6 for any reason, the user identified by the certificate cannot be authenticated, and the user is not allowed to access any server resources that require authentication. Original Document Information Author(s): [Author Names] Other Contributors: Giacomo Magnini Last Updated Date: September 26, 2005 Copyright Information: (C) 2001 Sun Microsystems, Inc. Used by permission. (C) 2005 Red Hat, Inc. All rights reserved. ...
Threats - Archive of obsolete content
ate but they are used to obtain personal information. For example, a mail which appears to be to be sent from a bank, asking to verify your identity by giving away your private information. DDOS Network attack. The volume and strength of DDoS attacks are growing as hackers try to bring organizations offline or steal their data by flooding websites and networks with spurious traffic. ...
...attacks are growing as hackers try to bring organizations offline or steal their data by flooding websites and networks with spurious traffic. Original Document Information Author(s): Ella Deon Lackey Last Updated Date: 2012 Copyright Information: (C) 2012 Red Hat, Inc. ...
... ...
...tification 8.1: Deployment, Planning, and Installation Original Document Information Author(s): Joint Task Force Transformation Initiative Title: National Institute of Standards and Technology (NIST) Special Publication 800-30 Revision 1, Guide for Conducting Risk Assessments Last Updated Date: September 2012 Copyright Information: This document is not subject to copyright. Original Document Information Author(s): Karen Scarfone, Wayne Jansen, and Miles Tracy Title: National Institute of Standards and Technology (NIST) Special Publication 800-123, Guide to General Server Security Last Updated Date: July 2008 Copyright Information: This document is not subject to copyright. ...
VBArray.getItem - Archive of obsolete content
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. ...
...ment. 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. ...
...Not suppo...
...Not supported in Windows 8.x Store apps. See Version Information. Applies To: VBArray Object ...
VBArray.toArray - Archive of obsolete content
t 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. ...
...rray. 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. ...
...Not supported in Windows 8.x...
...Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
VBArray - Archive of obsolete content
t 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. ...
...rray. 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. ...
... Methods VBArray.dimensions Returns the number of dimensions in a VBArray. ...
...imensions 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. ...
Implementation Status - Archive of obsolete content
Mozilla XForms Specials page. Specification Chapter Index Here we give an overview of XForms 1.1 specification chapters and the current status of the Mozilla support. The sections are marked with their current status: Supported, partial support, in progress, and not currently supported. We have listed the most relevant bugs here, but check out the Bugzilla XForms buglist for the complete list. 3. ...
... in XForms unsupported 4.7.1 References to Elements within a repeat Element unsupported 4.7.2 References to Elements within a bind Element unsupported 4.8 DOM Interface for Access to Instance Data supported 4.8.1 getInstanceDocument() supported 4.8.2 rebuild() supported 4.8.3 recalculate() supported 4.8.4 revalidate() supported 4.8.5 refresh() supported 4.9 Feature string for the hasFeature method call ...
...ype supported 8.3.3 label partial Labels for items inside a choices element has bind problems. We'd like to expand how we render labels bound to different, unique types. 297083; 343443; 8.3.4 help supported 8.3.5 hint partial problems with hints in XUL-hosted documents and ephemeral message positioning 349667; 8.3.6 alert supported 9. Container Form Controls Section Title Status Notes Bugs 9.1.1 group supported 9.2.1 switch partial @selected not working inside repeats 339937; ...
...on Title Status Notes Bugs 11.1 submission partial From 1.1 we do not yet support @mode, @indent, @replace='text', @separator, @serialize, @target, header or method child elements 11.2 xforms-submit partial We currently limit (for security reasons) submission only back to the server that served the document. But the user can choose to remove this restriction on a site by site basis via a preference. Click for more details. 330557; 11.3 xforms-submit-serialize supported 11.4 xforms-submit-done supported 11.5 xforms-submit-error supported 11.6.1 ...
GLSL Shaders - Game development
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 thi...
...th one is the alpha transparency (ranging from 0.0 -- fully transparent -- to 1.0 -- fully opaque). Applying the shaders To actually apply the newly created shaders to the cube, comment out the basicMaterial definition first: // var basicMaterial = new THREE.MeshBasicMaterial({color: 0x0095DD}); Then, create the shaderMaterial: var shaderMaterial = new THREE.ShaderMaterial( { vertexShader: document.getElementById( 'vertexShader' ).textContent, fragmentShader: document.getElementById( 'fragmentShader' ).textContent }); This shader material takes the code from the scripts and applies it to the object the material is assigned to. Then, in the line that defines the cube we need to replace the basicMaterial: var cube = new THREE.Mesh(boxGeometry, basicMaterial); ...with the newly created ...
...+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; scene.add(camera); var boxGeometry = new THREE.BoxGeometry(10, 10, 10); var shaderMaterial = new THREE.ShaderMaterial( { vertexShader: document.getElementById( 'vertexShader' ).textContent, fragmentSha...
....appendChild(renderer.domElement); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(70, WIDTH/HEIGHT); camera.position.z = 50; scene.add(camera); var boxGeometry = new THREE.BoxGeometry(10, 10, 10); var shaderMaterial = new THREE.ShaderMaterial( { vertexShader: document.getElementById( 'vertexShader' ).textContent, fragmentShader: document.getElementById( 'fragmentShader' ).textContent }); var cube = new THREE.Mesh(boxGeometry, shaderMaterial); scene.add(cube); cube.rotation.set(0.4, 0.2, 0); function render() { requestAnimationFrame(render); renderer.render(scene, camera); } render(); CSS body { margin: 0; padding: 0; font-size: 0; } canvas { width: 100%; height: 100%; } Result ...
3D games on the Web - Game development
For rich gaming experiences on the web, the weapon of choice is WebGL, which is rendered on HTML <canvas>. WebGL is basically an OpenGL ES 2.0 for the Web -- it's a JavaScript API providing tools to build rich interactive animations and of course, also games. You can generate and render dynamic 3D graphics with JavaScript that is hardware accelerated. 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. The main browsers are all supporting WebGL and all you need to focus on is optimizing the performance on the devices you use. There's an ongoing effort on releasing WebGL 2.0 (based o...
...Script 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 documentation to get started.) For real-world projects you'll probably also make use of a framework to speed up development and help you manage the project you're working on. Using a framework for 3D games also helps optimize the performance as a lot is taken care of by the tools you use, so you can focus on building the game itself. The most popular JavaScript 3D library is Three.js, a multi-purpose too...
...rformance as a lot is taken care of by the tools you use, so you can focus on building the game itself. The most popular JavaScript 3D library is Three.js, a multi-purpose tool that makes common 3D techniques simpler to implement. There are other popular game development libraries and frameworks worth checking too; A-Frame, PlayCanvas and Babylon.js are among the most recognizable ones with rich documentation, online editors and active communities. Building up a basic demo with A-Frame A-Frame is a web framework for building 3D and VR experiences. Under the hood, it is a Three.js framework with a declarative entity-component pattern, meaning we can build scenes with just HTML. See the Building up a basic demo with A-Frame subpage for the step-by-step process of creating the demo. Building up a...
...nt common 3D functionality more quickly. See the Building up a basic demo with Babylon.js subpage for the basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML, and writing the JavaScript code. Building up a basic demo with PlayCanvas PlayCanvas is a popular 3D WebGL game engine open-sourced on GitHub, with an editor available online and good documentation. See the Building up a basic demo with PlayCanvas subpage for higher-level details, and further articles showing how to create demos using the PlayCanvas library, and the online editor. Building up a basic demo with Three.js Three.js, like any other library, gives you a huge advantage: instead of writing hundreds of lines of WebGL code to build anything interesting you can use built-in hel...
Audio for Web games - Game development
ining all the smaller audio snippets we need. To play a specific sound from the file, we just use the known start and stop times for each audio sprite. The advantage is that we can prime one piece of audio and have our sprites ready to go. To do this we can just play and instantly pause the larger piece of audio. You'll also reduce the number of server requests and save bandwidth. var myAudio = document.createElement("audio"); myAudio.src = "mysprite.mp3"; myAudio.play(); myAudio.pause(); You'll need to sample the current time to know when to stop. If you space your individual sounds by at least 500ms then using the timeUpdate event (which fires every 250ms) should be sufficient. Your files may be slightly longer than they strictly need to be, but silence compresses well. Here's an example of ...
..."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. ...
...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. ...
...t 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 can harness these elements to give us access to the track file path and each individual play button. ...
Stylesheet - MDN Web Docs Glossary: Definitions of Web-related terms
External stylesheets are generally preferred because they allow you to control the styling of multiple pages from a single place, rather than having to repeat the CSS across each page. ...
... External stylesheets are generally preferred because they allow you to control the styling of multiple pages from a single place, rather than having to repeat the CSS across each page. ...
... External stylesheets are generally preferred because they allow you to control the styling of multiple pages from a single place, rather than having to repeat the CSS across each page. ...
... External stylesheets are generally preferred because they allow you to control the styling of multiple pages from a single place, rather than having to repeat the CSS across each page. ...
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
XML Inclusions (XInclude) is a W3C Recommendation to allow inclusion of XML more different sources in a more convenient fashion than XML external entities. When used in conjunction with XPointer (Firefox supports a subset of it, and is used in the code sample below), XInclude can also target just specific portions of a document for inclusion. Firefox does not support it natively, but the following function aims to allow its use with documents passed into it. Code sample The following code aims to let <xi:include> and <xi:fallback> tags (the two elements in the language) with all of the attributes of <xi:include> be included in an XML document so as to be resolvable into a single XML document. (Note that this has not been thoroughly tested for all circumstances and may not necessarily re...
...UTF-8) var accept = xinclude.getAttribute('accept'); // header "Accept: "+x var acceptLanguage = xinclude.getAttribute('accept-language'); // "Accept-Language: "+x var xiFallback = xinclude.getElementsByTagNameNS('http://www.w3.org/2001/XInclude', 'fallback')[0]; // Only one such child is allowed if (href === '' || href === null) { // Points to same document if empty (null is equivalent to empty string) href = null; // Set for uniformity in testing below if (parse === 'xml' && xpointer === null) { alert('There must be an XPointer attribute present if "href" is empty an parse is "xml"'); return false; } } else if (href.match(/#$/, '') || hre...
... // Let the request be processed below } else { if (encoding === '' || encoding === null) { // Encoding has no effect on XML encoding = 'utf-8'; } request.overrideMimeType('...
... var a = []; for(var k = 0; k < xpathResult.snapshotLength; k++) { a[k] = xpathResult.snapshotItem(k); } responseNodes = a; } else { // Otherwise, the response must be a single well-formed document response responseNodes = [response.documentElement]; // Put in array so can be treated the same way as the above } // PREPEND ANY NODE(S) (AS XML) THEN REMOVE XINCLUDE for (j=0; j < responseNodes.length ; j++) { xincludeParent.insertBefore(responseNod...
jQuery - MDN Web Docs Glossary: Definitions of Web-related terms
jQuery is a JavaScript Library that focuses on simplifying DOM manipulation, AJAX calls, and Event handling. jQuery uses a format, $(selector).action() to assign an element(s) to an event. To explain it in detail, $(selector) will call jQuery to select selector element(s), and assign it to an event API called .action(). ...
...selector).action() to assign an element(s) to an event. To explain it in detail, $(selector) will call jQuery to select selector element(s), and assign it to an event API called .action(). ...
...(s), and assign it to an event API called .action(). ...
...ollowing code: window.onload = function() { alert("Hello World!"); document.getElementById("blackBox").style.display = "none"; }; Or: window.addEventListener("load", () => { alert("Hello World!"); document.getElementById("blackBox").style.display = "none"; }); Learn more General knowledge jQuery on Wikipedia jQuery Official Website Technical information Offical API reference documentation ...
Speculative parsing - MDN Web Docs Glossary: Definitions of Web-related terms
r starts speculative loads for scripts, style sheets and images it finds ahead in the stream and runs the HTML tree construction algorithm speculatively. The upside is that when a speculation succeeds, there's no need to reparse the part of the incoming file that was already scanned for scripts, style sheets and images. The downside is that there's more work lost when the speculation fails. This document helps you avoid the kind of things that make speculation fail and slow down the loading of your page. To make speculative loads of linked scripts, style sheets and images successful, avoid document.write. If you use a <base> element to override the base URI of your page, put the element in the non-scripted part of the document. Don't add it via document.write() or document.createElement. Avoi...
...w down the loading of your page. To make speculative loads of linked scripts, style sheets and images successful, avoid document.write. If you use a <base> element to override the base URI of your page, put the element in the non-scripted part of the document. Don't add it via document.write() or document.createElement. Avoiding losing tree builder output Speculative tree building fails when document.write() changes the tree builder state such that the speculative state after the </script> tag no longer holds when all the content inserted by document.write() has been parsed. However, only unusual uses of document.write() cause trouble. ...
...t. Avoiding losing tree builder output Speculative tree building fails when document.write() changes the tree builder state such that the speculative state after the </script> tag no longer holds when all the content inserted by document.write() has been parsed. However, only unusual uses of document.write() cause trouble. Here are the things to avoid: Don't write unbalanced trees. <script>document.write("<div>");</script> is bad. <script>document.write("<div></div>");</script> is OK. Don't write an unfinished token. <script>document.write("<div></div");</script> is bad. Don't finish your writing with a carriage return. <script>document.write("Hello World!\r");</script> is bad. <script>document.write("Hello World!\n");</script> is OK. Note that writing balanced tags may cause other tags ...
...);</script> is OK. Don't write an unfinished token. <script>document.write("<div></div");</script> is bad. Don't finish your writing with a carriage return. <script>document.write("Hello World!\r");</script> is bad. <script>document.write("Hello World!\n");</script> is OK. Note that writing balanced tags may cause other tags to be inferred in a way that makes the write unbalanced. E.g. <script>document.write("<div></div>");</script> inside the head element will be interpreted as <script>document.write("</head><body><div></div>");</script> which is unbalanced. Don't format part of a table. <table><script>document.write("<tr><td>Hello World!</td></tr>");</script></table> is bad. ...
CSS and JavaScript accessibility best practices - Learn web development
ed. 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. 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 JavaScr...
... from it. CSS and JavaScript are accessible? CSS and JavaScript don't have the same immediate importance for accessibility as HTML, but they are still able to help or damage accessibility, depending on how they are used. To put it another way, it is important that you consider some best practice advice to make sure that your use of CSS and JavaScript doesn't ruin the accessibility of your documents. CSS Let's start off by looking at CSS. Correct semantics and user expectation It is possible to use CSS to make any HTML element look like anything, but this doesn't mean that you should. As we frequently mentioned in our HTML: A good basis for accessibility article, you should use the appropriate semantic element for the job, whenever possible. If you don't, it can cause confusion and usab...
... (using preventDefault()), and display any error messages that have been created (see below). This mechanism means that the errors will only be shown if there are errors, which is better for usability. For each input that doesn't have a value filled in when the form is submitted, we create a list item with a link and insert it in the errorList. ...
...r messages that have been created (see below). This mechanism means that the errors will only be shown if there are errors, which is better for usability. For each input that doesn't have a value filled in when the form is submitted, we create a list item with a link and insert it in the errorList. ...
Combinators - Learn web development
Previous Overview: Building blocks Next The final selectors we will look at are called combinators, because they combine other selectors in a way that gives them a useful relationship to each other and the location of content in the document. Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.) Objective: To learn about the different combinator selectors that can be used in CSS. Descendant combinator The descendant combinator -- typically represented by a single space ( ) character -- combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, ...
...ment is adjacent. General sibling combinator If you want to select siblings of an element even if they are not directly adjacent, then you can use the general sibling combinator (~). To select all <img> elements that come anywhere after <p> elements, we'd do this: p ~ img In the example below we are selecting all <p> elements that come after the <h1>, and even though there is a <div> in the document as well, the <p> that comes after it is selected. Using combinators You can combine any of the selectors that we discovered in previous lessons with combinators in order to pick out part of your document. For example if we want to select list items with a class of "a", which are direct children of a <ul>, I could use the following. ul > li[class="a"] { } Take care however when creating bi...
...ombinators You can combine any of the selectors that we discovered in previous lessons with combinators in order to pick out part of your document. For example if we want to select list items with a class of "a", which are direct children of a <ul>, I could use the following. ul > li[class="a"] { } Take care however when creating big lists of selectors that select very specific parts of your document. It will be hard to reuse the CSS rules as you have made the selector very specific to the location of that element in the markup. It is often better to create a simple class and apply that to the element in question. ...
... Test your skills! We have covered a lot in 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: Selectors. ...
Beginner's guide to media queries - Learn web development
this example in the browser, or view the source. In practice, using minimum or maximum values is much more useful for responsive design so you will rarely see width or height used alone. There are a number of other media features that you can test for, although some of the newer features introduced in Level 4 and 5 of the media queries specification have limited browser support. Each feature is documented on MDN along with browser support information, and you can find a full list at Using Media Queries: Media Features. Orientation One well-supported media feature is orientation, which allows us to test for portrait or landscape mode. To change the body text color if the device is in landscape orientation, use the following media query. @media (orientation: landscape) { body { colo...
... of layout for small devices -- order your source well and you will have a readable layout by default. The below walkthrough takes you through this approach with a very simple layout. In a production site you are likely to have more things to adjust within your media queries, however the approach would be exactly the same. Walkthrough: a simple mobile-first layout Our starting point is an HTML document with some CSS applied to add background colors to the various parts of the layout. * { box-sizing: border-box; } body { width: 90%; margin: 2em auto; font: 1em/1.3 Arial, Helvetica, sans-serif; } a:link, a:visited { color: #333; } nav ul, aside ul { list-style: none; padding: 0; } nav a:link, nav a:visited { background-color: rgba(207, 232, 220, 0.2); bord...
...This is an important first step and one which ensures that if the content were to be read out by a screen reader, it would be understandable. <body> <div class="wrapper"> <header> <nav> <ul> <li><a href="">About</a></li> <li><a href="">Contact</a></li> <li><a href="">Meet the team...
...e source. If you look at the final example at different widths you can see how the design responds and works as a single column, two columns, or three columns, depending on the available width. This is a very simple example of a mobile first responsive design. The viewport meta tag If you look at the HTML source in the above example, you'll see the following element included in the head of the document: <meta name="viewport" content="width=device-width,initial-scale=1"> This is the viewport meta tag -- it exists as a way control how mobile browsers render content. This is needed because by default, most mobile browsers lie about their viewport width. Non-responsive sites commonly look really bad when rendered in a narrow viewport, so mobile browsers usually render the site with a viewport wid...
How CSS works - Learn web development
ebpage. Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, and HTML basics (study Introduction to HTML.) Objective: To understand the basics of how CSS and HTML are parsed by the browser, and what happens when a browser encounters CSS it does not understand. How does CSS actually work? When a browser displays a document, it must combine the document's content with its style information. It processes the document in a number of stages, which we've listed below. Bear in mind that this is a very simplified version of what happens when a browser loads a webpage, and that different browsers will handle the process in different ways. But this is roughly what happens. The browser loads the HTML (e.g. receives it fro...
...style information. It processes the document in a number of stages, which we've listed below. Bear in mind that this is a very simplified version of what happens when a browser loads a webpage, and that different browsers will handle the process in different ways. But this is roughly what 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 brows...
...t the DOM A DOM has a tree-like structure. Each element, attribute, and piece of text in the markup language becomes a DOM node in the tree structure. The nodes are defined by their relationship to other DOM nodes. Some elements are parents of child nodes, and child nodes have siblings. Understanding the DOM helps you design, debug and maintain your CSS because the DOM is where your CSS and the document's content meet up. When you start working with browser DevTools you will be navigating the DOM as you select items in order to see which rules apply. A real DOM representation Rather than a long, boring explanation, let's look at an example to see how a real HTML snippet is converted into a DOM. Take the following HTML code: <p> Let's use: <span>Cascading</span> <span>Style</span> <sp...
... to our <span> elements. The SPAN nodes are also parents, with text nodes as their children: P +- "Let's use:" +- SPAN | +- "Cascading" +- SPAN | +- "Style" +- SPAN +- "Sheets" This is how a browser interprets the previous HTML snippet --it renders the above DOM tree and then outputs it in the browser like so: p {margin:0;} Applying CSS to the DOM Let's say we added some CSS to our document, to style it. Again, the HTML is as follows: <p> Let's use: <span>Cascading</span> <span>Style</span> <span>Sheets</span> </p> Let's suppose we apply the following CSS to it: span { border: 1px solid black; background-color: lime; } The browser will parse the HTML and create a DOM from it, then parse the CSS. Since the only rule available in the CSS has a span selector, the browse...
What are hyperlinks? - Learn web development
Objective: Learn about links on the web and why they matter. Summary Hyperlinks, usually called links, are a foundational concept behind the Web. To explain what links are, we need to step back to the very basics of Web architecture. Back in 1989, Tim Berners-Lee, the Web's inventor, spoke of the three pillars on which the Web stands: URL, an address system that keeps track of Web documents HTTP, a transfer protocol to find documents when given their URLs HTML, a document format allowing for embedded hyperlinks As you can see in the three pillars, everything on the Web revolves around documents and how to access them. The Web's original purpose was to provide an easy way to reach, read, and navigate through text documents. Since then, the Web has evolved to provide access to im...
...n see in the three pillars, everything on the Web revolves around documents and how to access them. The Web's original purpose was to provide an easy way to reach, read, and navigate through text documents. Since then, the Web has evolved to provide access to images, videos, and binary data, but these improvements have hardly changed the three pillars. Before the Web, it was quite hard to access documents and move from one to another. Being human-readable, URLs already made things easier, but it's hard to type a long URL whenever you want to access a document. This is where hyperlinks revolutionized everything. Links can correlate any text string with a URL, such that the user can instantly reach the target document by activating the link. Links stand out from the surrounding text by being under...
...activate it, or if you use a keyboard, press Tab until the link is in focus and hit Enter or Spacebar. Links are the breakthrough that made the Web so useful and successful. In the rest of this article, we discuss the various types of links and their importance to modern Web design. Deeper dive As we said, a link is a text string tied to a URL, and we use links to allow easy jumping from one document to another. That said, there are some nuances worth considering: Types of links Internal link A link between two webpages, where both webpages belong to the same website, is called an internal link. Without internal links, there's no such thing as a website (unless, of course, it's a one-page website). External link A link from your webpage to someone else's webpage. Without external links...
...her hand, if your site has more than about ten pages, it's counter-productive to link to every page from every other page. When you're starting out, you don't have to worry about external and incoming links as much, but they are very important if you want search engines to find your site (see below for more details). Anchors Most links tie two webpages together. Anchors tie two sections of one document together. When you follow a link pointing to an anchor, your browser jumps to another part of the current document instead of loading a new document. However, you make and use anchors the same way as other links. Links and Search Engines Links matter both to users and search engines. Every time search engines crawl a webpage, they index the website by following the links available on the webp...
Client-side form validation - Learn web development
followed by c. ( ac or abc) ab*c--Matches a, optionally followed by any number of bs, followed by c. ( ac , abc, abbbbbc, and so on). a|b -- Matches one character that is a or b. abc|xyz -- Matches exactly abc or exactly xyz (but not abcxyz or a or y, and so on). There are many more possibilities that we don't cover here. For a complete list and many examples, consult our Regular expressions documentation. Let's implement an example. Update your HTML to add a pattern attribute like this: <form> <label for="choose">Would you prefer a banana or a cherry?</label> <input id="choose" name="i_like" required pattern="[Bb]anana|[Cc]herry"> <button>Submit</button> </form> input:invalid { border: 2px dashed red; } input:valid { border: 2px solid black; } This gives us the following up...
...ample of how to do this. We'll start with some simple HTML (feel free to put this in a blank HTML file; use a fresh copy of fruit-start.html as a basis, if you like): <form> <label for="mail">I would like you to provide me with an e-mail address:</label> <input type="email" id="mail" name="mail"> <button>Submit</button> </form> And add the following JavaScript to the page: const email = document.getElementById("mail"); email.addEventListener("input", function (event) { if (email.validity.typeMismatch) { email.setCustomValidity("I am expecting an e-mail address!"); } else { email.setCustomValidity(""); } }); Here we store a reference to the email input, then add an event listener to it that runs the contained code each time the value inside the input is changed. Inside th...
...color: white; background-color: #900; border-radius: 0 0 5px 5px; box-sizing: border-box; } .error.active { padding: 0.3em; } Now lets look at the JavaScript that implements the custom error validation. // There are many ways to pick a DOM node; here we get the form itself and the email // input box, as well as the span element into which we will place the error message. const form = document.getElementsByTagName('form')[0]; const email = document.getElementById('mail'); const emailError = document.querySelector('#mail + span.error'); email.addEventListener('input', function (event) { // Each time the user types something, we check if the // form fields are valid. if (email.validity.valid) { // In case there is an error message visible, if the field // is valid, we re...
...s the style of our error messages */ .error { width : 100%; padding: 0; font-size: 80%; color: white; background-color: #900; border-radius: 0 0 5px 5px; box-sizing: border-box; } .error.active { padding: 0.3em; } The big changes are in the JavaScript code, which needs to do much more heavy lifting. // There are fewer ways to pick a DOM node with legacy browsers const form = document.getElementsByTagName('form')[0]; const email = document.getElementById('mail'); // The following is a trick to reach the next sibling Element node in the DOM // This is dangerous because you can easily build an infinite loop. // In modern browsers, you should prefer using element.nextElementSibling let error = email; while ((error = error.nextSibling).nodeType != 1); // As per the HTML5 Specifi...
HTML forms in legacy browsers - Learn web development
s, the stock browsers that don't update are also legacy browsers. Dealing with this wilderness is part of the job. Fortunately, there are a few tricks to know that can help you to solve most of the problems caused by legacy browsers. And HTML5 <input> types don't fail when not supported: they fall back to type=text. ...
... The WebKit blog and Planet WebKit aggregate the best articles by WebKit core developers. ...
...he right place to start. Just check the support of the elements (or DOM interface) you want to use. MDN has compatibility tables available for most elements, properties and APIs that can be used in a web page. There are other resources that can be amazingly helpful: Browser vendor documentation Mozilla: You're in the right place, just browse MDN Microsoft: Internet Explorer Standards Support Documentation WebKit: Because there are several different editions of this engine, things are a little trickier. The WebKit blog and Planet WebKit aggregate the best articles by WebKit core developers. Chrome platform status site is also important. As well as the Apple web site. Make things simple Because HTML forms involves complex interaction, there is one rule of thumb: keep it sim...
...s, // Once both files are loaded, this function is called in order to initialize the App. complete : function () { app.init(); } }); The Modernizr team conveniently maintains a list of great polyfills. Just pick what you need. Note: Modernizr has other awesome features to help you in dealing with unobstructive JavaScript and graceful degradation techniques. Please read the Modernizr documentation. Pay attention to performance Even though scripts like Modernizr are very aware of performance, loading a 200 kilobyte polyfill can affect the performance of your application. This is especially critical with legacy browsers; many of them have a very slow JavaScript engine that can make the execution of all your polyfills painful for the user. Performance is a subject on its own, but lega...
UI pseudo-classes - Learn web development
cles, we've seen the usage of generated content, but we thought now would be a good time to talk about it in a bit more detail. The idea is that we can use the ::before and ::after pseudo-elements along with the content property to make a chunk of content appear before or after the affected element. The chunk of content is not added to the DOM, so is invisible to screenreaders; it is part of the document's styles. Because it is a pseudo element, it can be targetted with styles in the same way that any actual DOM node can. This is really useful when you want to add a visual indicator to an element, such as a label or icon, but don't want it to be picked up by assistive technologies. For example, in our custom radio buttons example, we use generated content to handle the placement and animation of...
... 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. ...
...e 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. ...
...JavaScript to toggle the disabling of the billing address fields: // Wait for the page to finish loading document.addEventListener('DOMContentLoaded', function () { // Attach `change` event listener to checkbox document.getElementById('billing-checkbox').addEventListener('change', toggleBilling); }, false); function toggleBilling() { // Select the billing text fields let billingItems = document.querySelectorAll('#billing input[type="text"]'); // Select the billing text labels let billingLabels = document.querySelectorAll('.billing-label'); // Toggle the billing text fields and labels for (let i = 0; i < billingItems.length; i++) { billingItems[i].disabled = !billingItems[i].disabled; if(billingLabels[i].getAttribute('class') === 'billing-label disabled-label') { ...
HTML basics - Learn web development
nd are called empty elements. Take the <img> element that we already have in our HTML page: <img src="images/firefox-icon.png" alt="My test image"> This contains two attributes, but there is no closing </img> tag and no inner content. This is because an image element doesn't wrap content to affect it. Its purpose is to embed an image in the HTML page in the place it appears. Anatomy of an HTML document That wraps up the basics of individual HTML elements, but they aren't handy on their own. Now we'll look at how individual elements are combined to form an entire HTML page. Let's revisit the code we put into our index.html example (which we first met in the Dealing with files article): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My test page</title> </head> <body>...
...ollowing: <!DOCTYPE html> -- the doctype. It is required preamble. In the mists of time, when HTML was young (around 1991/92), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML, which could mean automatic error checking and other useful things. However these days, they don't do much, and are basically just needed to make sure your document behaves correctly. That's all you need to know for now. <html></html> -- the <html> element. This element wraps all the content on the entire page and is sometimes known as the root element. <head></head> -- the <head> element. This element acts as a container for all the stuff you want to include on the HTML page that isn't the content you are showing to your page's viewers. This includes thin...
... <head> element. This element acts as a container for all the stuff you want to include on the HTML page that isn't the content you are showing to your page's viewers. This includes things like keywords and a page description that you want to appear in search results, CSS to style our content, character set declarations and more. <meta charset="utf-8"> -- This element sets the character set your document should use to UTF-8 which includes most characters from the vast majority of written languages. Essentially, it can now handle any textual content you might put on it. There is no reason not to set this and it can help avoid some problems later on. <title></title> -- the <title> element. This sets the title of your page, which is the title that appears in the browser tab the page is loaded in. I...
...age now. Find out more about accessibility in our accessibility learning module. Marking up text This section will cover some of the essential HTML elements you'll use for marking up the text. Headings Heading elements allow you to specify that certain parts of your content are headings -- or subheadings. In the same way that a book has the main title, chapter titles and subtitles, an HTML document can too. HTML contains 6 heading levels, <h1>-<h6>, although you'll commonly only use 3 to 4 at most: <h1>My main title</h1> <h2>My top level heading</h2> <h3>My subheading</h3> <h4>My sub-subheading</h4> Now try adding a suitable title to your HTML page just above your <img> element. Note: You'll see that your heading level 1 has an implicit style. Don't use heading elements to make text big...
Marking up a letter - Learn web development
f you get stuck, then ask us for help. See the Assessment or further help section at the bottom of this page. Project brief For this project, your task is to mark up a letter that needs to be hosted on a university intranet. The letter is a response from a research fellow to a prospective PhD student concerning their application to the university. Block/structural semantics Use appropriate document structure including doctype, and <html>, <head> and <body> elements. In general, the letter should be marked up as an organization of headings and paragraphs, with the following exception. There is one top level heading (the "Re:" line) and three second level headings. Use an appropriate list type to mark up the semester start dates, study subjects, and exotic dances. Put the two addresses in...
...ond level headings. Use an appropriate list type to mark up the semester start dates, study subjects, and exotic dances. Put the two addresses inside <address> elements. Each line of the address should sit on a new line, but not be in a new paragraph. Inline semantics The names of the sender and receiver (and Tel and Email) should be marked up with strong importance. The four dates in the document should be have appropriate elements containing machine-readable dates. The first address and first date in the letter should have a class attribute value of sender-column. The CSS you'll add later will cause these to be right aligned, as it should be in the case in a classic letter layout. Mark up the five acronyms/abbreviations in the main text of the letter to provide expansions of each acron...
...er of 3 and 4, respectively). Try to mark up at least two appropriate words in the text with strong importance/emphasis. There are two places where the letter should have a hyperlink. Add appropriate links with titles. For the location that the links point to, you may use http://example.com as the URL. Mark up the university motto quote and citation with appropriate elements. The head of the document The character set of the document should be set as utf-8 using the appropriate meta tag. The author of the letter should be specified in an appropriate meta tag. The provided CSS should be included inside an appropriate tag. Hints and tips Use the W3C HTML validator to validate your HTML. Award yourself bonus points if it validates. You don't need to know any CSS to do this assignment.
...ery hard to help someone with a coding problem without seeing their code. ...
Introduction to HTML - Learn web development
This module will introduce the first two of these and introduce fundamental concepts and syntax you need to know to understand HTML. ...
...This module will introduce the first two of these and introduce fundamental concepts and syntax you need to know to understand HTML. ...
...cs of HTML, to get you started -- we define elements, attributes, and other important terms, and show where they fit in the language. We also show how a typical HTML page is structured and how an HTML element is structured, and explain other important basic language features. Along the way, we'll play with some HTML to get you interested! What's in the head? Metadata in HTML The head of an HTML document is the part that is not displayed in the web browser when the page is loaded. It contains information such as the page <title>, links to CSS (if you want to style your HTML content with CSS), links to custom favicons, and metadata (data about the HTML, such as who wrote it, and important keywords that describe the document). HTML text fundamentals One of HTML's main jobs is to give text meaning...
... links. Advanced text formatting There are many other elements in HTML for formatting text that we didn't get to in the HTML text fundamentals article. The elements here are less well-known, but still useful to know about. In this article, you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more. Document and website structure As well as defining individual parts of your page (such as "a paragraph" or "an image"), HTML is also used to define areas of your website (such as "the header," "the navigation menu," or "the main content column.") This article looks into how to plan a basic website structure and how to write the HTML to represent this structure. Debugging HTML Writing HTML is fine, but ...
What is web performance? - Learn web development
r can significantly affect performance. The download of additional assets linked to from the index file is generally sequential, based on source order, but this can be manipulated and should definitely be optimized, realizing that some resources block additional downloads until their content is parsed and executed. The critical path. ...
...This includes all the HTML attributes and the relationships between the nodes. ...
...This includes all the HTML attributes and the relationships between the nodes. ...
..., is a tree structure that represents the content and elements of your HTML as a tree of nodes. This includes all the HTML attributes and the relationships between the nodes. Extensive DOM manipulation after the pages has loaded (e.g., adding, deleting, or moving of nodes) can affect performance, so it is worth understanding how to DOM works, and how such issues can be mitigated. Find out more at Document Object Model. Latency. We mention this briefly earlier on, but in brief, latency is the time it takes for your website assets to travel from the server to a user's computer. There is overhead involved in establishing TCP and HTTP connections, and some unavoidable latency in pushing the request and response bytes back and forth across the network, but there are certain ways to reduce latency (e.g...
Client-Server Overview - Learn web development
e format of HTTP messages is defined in a "web standard" (RFC7230). You don't need to know this level of detail, but at least now you know where this all came from! The request Each line of the request contains information about it. ...
... The remainder of the response header includes information about the response (e.g. when it was generated), the server, and how it expects the browser to handle the page (e.g. the X-Frame-Options: DENY line tells the browser not to allow this page to be embedded in an <iframe> in another site). POST request/response example An HTTP POST is made when you submit ...
... The remainder of the response header includes information about the response (e.g. when it was generated), the server, and how it expects the browser to handle the page (e.g. the X-Frame-Options: DENY line tells the browser not to allow this page to be embedded in an <iframe> in another site). POST request/response example An HTTP POST is made when you submit a form co...
...e same content to every user. However they can have a significant cost to maintain as the number of pages becomes larger. Let's recap on how this works, by looking again at the static site architecture diagram we looked at in the last article. When a user wants to navigate to a page, the browser sends an HTTP GET request specifying the URL of its HTML page. The server retrieves the requested document from its file system and returns an HTTP response containing the document and an HTTP Response status code of "200 OK" (indicating success). The server might return a different status code, for example "404 Not Found" if the file is not present on the server, or "301 Moved Permanently" if the file exists but has been redirected to a different location. The server for a static site will only ever...
Getting started with React - Learn web development
neral. Also bear in mind that React and ReactDOM produce apps that only work on a fairly modern set of browsers -- IE9+ by way of some polyfills. It is recommended that you use a modern browser like Firefox, Safari, or Chrome when working through these tutorials. Also, see the following for more information: "What is npm" on nodejs.org "Introducing npx" on the npm blog The create-react-app documentation Initializing your app create-react-app takes one argument: the name you'd like to give your app. create-react-app uses this name to make a new directory, then creates the necessary files inside it. Make sure you cd to the place you'd like your app to live on your hard drive, then run the following in your terminal: npx create-react-app moz-todo-react This creates a moz-todo-react direct...
...onent available to other modules. Interrogating the index Let's open src/index.js, because that's where the App component is being used. This file is the entry point for our app, and it initially looks like this: import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister(); As with App.js, the file starts by importing all the JS modules and other assets it needs to run. src/index.css holds global styles that ar...
...eresting pieces of code that help application performance and allow features of your web applications to work offline, but they're not in scope for this article. You can delete line 5, as well as lines 9 through 12. Your final index.js file should look like this: import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root')); Variables and props Next, we'll use a few of our JavaScript skills to get a bit more comfortable editing components and working with data in React. We'll talk about how variables are used inside JSX, and introduce props, which are a way of passing data into a component (which can then be accessed using variables). Variables in JSX Back in App.js, let's focus on line 9...
...s A prop is any data passed into a React component. Props are written inside component calls, and use the same syntax as HTML attributes -- prop="value". Let's open index.js and give our <App/> call its first prop. Add a prop of subject to the <App/> component call, with a value of Clarice. When you are done, your code should look something like this: ReactDOM.render(<App subject="Clarice" />, document.getElementById('root')); Back in App.js, let's revisit the App function itself, which reads like this (with the return statement shortened for brevity): function App() { const subject = "React"; return ( // return statement ); } Change the signature of the App function so that it accepts props as a parameter, and delete the subject const. Just like any other function parameter, you c...
Handling common JavaScript problems - Learn web development
e libraries will serve more than one of these purposes): Utility libraries: Provide a bunch of functions to make mundane tasks easier and less boring to manage. jQuery for example provides its own fully-featured selectors and DOM manipuation libraries, to allow CSS-selector type selecting of elements in JavaScript and easier DOM building. It is not so important now we have modern features like Document.querySelector()/Document.querySelectorAll()/Node methods available across browsers, but it can still be useful when older browsers need supporting. Convenience libraries: Make difficult things easier to do. For example, the WebGL API is really complex and challenging to use when you write it directly, so the Three.js library (and others) is built on top of WebGL and provides a much easier API fo...
...romises polyfill in the same directory as the HTML. ...
...w if you load it in a browser that doesn't support Fetch (Safari and IE are obvious candidates), you should still see the flower image appear -- cool! Note: You can find our finished version at fetch-polyfill-finished.html (see also the source code). Note: Again, there are many different ways to make use of the different polyfills you will encounter -- consult each polyfill's individual documentation. One thing you might be thinking is "why should we always load the polyfill code, even if we don't need it?" This is a good point -- as your sites get more complex and you start to use more libraries, polyfills, etc., you can start to load a lot of extra code, which can start to affect performance, especially on less-powerful devices. It makes sense to only load files as needed. Doing thi...
...ise object and fetch() function exist in the browser. If both do, the function returns true. If the function returns false, then we run the code inside the second part of the conditional -- this runs a function called loadScript(), which loads the polyfills into the page, then runs main() after the loading has finished. loadScript() looks like this: function loadScript(src, done) { const js = document.createElement('script'); js.src = src; js.onload = function() { done(); }; js.onerror = function() { done(new Error('Failed to load script ' + src)); }; document.head.appendChild(js); } This function creates a new <script> element, then sets its src attribute to the path we specified as the first argument ('polyfills.js' when we called it in the code above). When it has load...
Accessibility/LiveRegionDevGuide
ed during the development of FireVox, an AT using IAccessible2. Sometimes the very best guide for some developers is the code itself. Please refer to the liveregions and Gecko Python modules in Orca for a real world example. For more information about Live Regions, please read the ARIA properties spec or the live region report to learn about ARIA Live Region markup and the Live Region API Support document for the latest Firefox API with regards to Live Regions. As always, we're open to questions and suggestions for changes in community forums. Priority Queue The heart of any live region support module is the priority queue. It is responsible for queuing messages derived from live region events, where priority is determined by chronological order and the live politeness properties. In addition...
...gnificant difference between AT-SPI and IAccessible2 is that AT-SPI is an inter-process communication service while IAccessible2 runs in process. As a result, care must be taken in an AT-SPI based application to minimize performance degradation by only acting on events that are truly live regions. These "non-live" events may be events originating from the chrome, user interaction in the chrome or document, document loading events, or real live region events from hidden tabs. With the goal of eliminating the "non-live" events, some sort of event filtering logic must be employed. The following is a list of potential filtering techniques: The "event-from-input" object attribute can be used to filter events that were triggered by user action. The ":system" (or lack thereof) can be used to filter ev...
...goal of eliminating the "non-live" events, some sort of event filtering logic must be employed. The following is a list of potential filtering techniques: The "event-from-input" object attribute can be used to filter events that were triggered by user action. The ":system" (or lack thereof) can be used to filter events that are system generated. (AT-SPI only) A global variable can be set in a document:load:complete event listener and reset in a object:state-changed:busy listener. This variable can then be used to quickly determine if an event was triggered by the document being loaded. An event containing an object that does not have state VISIBLE is probably from a hidden tab. An event containing an object that has state SELECTABLE is not a live region. An event containing an object that h...
...event containing an object that has state SELECTABLE is not a live region. An event containing an object that has the attribute "container-live" is a live region. However, many web sites do not have proper ARIA markup so this cannot be used by itself. An event containing an object that has an attribute "tag:xul*" is not a live region. An event that has an object that is not a descendant of the document frame is not a live region. Live Properties This table describe the object attributes associated with a live region event. The following are guidelines on how to implement each container-live This property determines the interruption policy or politeness level for the event and can have values of "off", "polite", "assertive" and "rude". This property, along with an event's time stamp, det...
CSUN Firefox Materials
esired link by pressing 2 letter keys rather than tabbing through many links to get there. Browse with caret allows users to select arbitrary content with the keyboard and move through content as if inside a read-only editor. This allows copying arbitrary pieces of text to the clipboard. The F7 key toggles this feature on/off. Tabbed browsing helps keyboard users by putting all of the browsed documents in one Firefox application window rather than cluttering the Alt+Tab order which makes keyboard navigation within the entire Windows OS much simpler. Both history and bookmarks can be searched with a "quick search" field that quickly narrows the list down via a substring search. Bookmarks can have a keyword assigned to them which can be typed into the address bar to bring up the bookmark. A ...
...ing to the search tool's web site. Custom searches can be added to this quick search bar and the user can switch between them by choosing from a drop down available via the standard Alt+down arrow key combination. The built-in text zoom feature can be accessed with the Ctrl+plus and Ctrl+minus hotkeys. The Accessibility Extension may be installed on top of Firefox, allowing keyboard access to document structure. 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 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 Customize Your Experience! Many users are finding the ...
...ovides new menus and keyboard shortcuts for accessing every feature of a web page Community Contributions The real reason behind Firefox's success is the great community of volunteers and organizations that realize they have something to benefit from a browser open to utilizing their ideas and hard work. Contributions come in many forms. The Mozilla Firefox community welcomes bug reports, ideas, documentation, answering questions in the support forums -- and nearly any kind of community involvement resulting in a browser built for a broader audience of users and developers. Here are a couple of success stories from businesses who contributed accessibility code because they needed an accessible web browser which supported their software: IBM Contributes Accessible Web Applications (DHTML and AJAX)...
...web applications". A web application may be an easier-to-use online tax assistant, a web calendar or a live sports statistics page, which is familiar in that it acts much like a desktop application. Whether the current buzzword for this technology is "DHTML", "AJAX" or "Web 2.0" doesn't really matter. This fact remains: the web is changing to become more interactive and less like a bunch of plain documents. Firefox is currently the only browser to support the new evolving standards for making these web applications accessible. Companies such as Yahoo! have announced they are already working with the technology their new richer interfaces accessible with this new technology. Sun Contributes Code to Improve Accessibility on UNIX A similar story occurred at Sun Microsystems. Sun needed an accessible ...
Embedding API for Accessibility
lity for a user agent like Mozilla. In part, being accessible means supporting a built-in accessibility APIs for a platform, such as Microsoft Active Accessibility or ATK for Linux and UNIX desktops. There are many other pieces, such as preferences to allow the user to change foreground and background colors, and font sizes. Mozilla already supports some of these options. This document lays out what we already have, and what we'll need later, in the embedding API to support accessibility. Text Zoom on a Per-Window Basis The nsIDOMWindow::GetTextZoom(float *zoomFactor) and nsIDOMWindow::SetTextZoom(float zoomFactor) methods can be used to set a wide range of text zoom factors on a content window. A zoom factor of 1.0 represents 100%, or normal zoom. For double-sized text, us...
... a content window. A zoom factor of 1.0 represents 100%, or normal zoom. For double-sized text, use nsIDOMWindow::SetTextZoom(2.0); Using Accessibility Preferences There are a number of prefs related to accessibility. For the most part, an automatic reframe is performed when one of these prefs is changed. A reframe fixes the appearance of the page to match the new prefs, without reloading the document over the network. Be aware that in debug builds, this can cause a great number of assertions (bug 71598) To use prefs in embedding, use something like the following code: #include "nsIPref.h"; nsresult rv; nsCOMPtr<nsIPref> prefs(do_GetService(NS_PREF_CONTRACTID, &rv)); prefs->SetBoolPref("bool.pref.name", PR_TRUE /* or PR_FALSE */); prefs->SetIntPref("int.pref.name", newValue); prefs->SetCh...
... SetBoolPref("browser.use_system_fonts", useSystemFonts); No Colors for page SetCharPref("browser.display.foreground_color", "#abcdef" /* hex color...
... Colors for page SetCharPref("browser.display.foreground_color", "#abcdef" /* hex color value */); SetCharPref("browser.display.background_color", "#abcdef" /* hex color value */); SetBoolPref("browser.display.use_system_colors", boolSystemColors); SetBoolPref("browser.display.use_document_colors", boolUseAuthorColors); /* Setting use_document_colors also stops background images from loading */ Moz 0.8 Link appearance SetCharPref("browser.anchor_color", "#abcdef" /* hex color value */); SetCharPref("browser.visited_color", "#abcdef" /* hex color value */); ...
Adding a new CSS property
This page describes how to add a new CSS property to the style system. The style system is the part of the code in Gecko that is responsible for producing a computed value for every property for every element. See the Gecko Overview for more information about the style system. This document assumes that you have a specifcation for the property available. Issues about how to write such a specification (including things such as whether it is appropriate to use prefixes or when properties should be inherited by default) are not covered here. If you need more details on any of the points mentioned here, a good place to find them is by looking at other changes in the version control history of the files mentioned. Getting started First, you'll want to add an appropriate test entry to pro...
...ch as whether it is appropriate to use prefixes or when properties should be inherited by default) are not covered here. If you need more details on any of the points mentioned here, a good place to find them is by looking at other changes in the version control history of the files mentioned. Getting started First, you'll want to add an appropriate test entry to property_database.js. See the documentation at the top of the file and the other entries for examples. This will cause tests of your new property to be added to many of the mochitests in layout/style/test, which can be run with the command "./mach mochitest -f plain layout/style/". Then, unless you're implementing a shorthand property, you need to decide which style struct the computed value of the property should go in. (Again, se...
...reset by a particular common shorthand property; this improves the effectiveness of some of the performance and memory optimizations done with the rule tree, and thus we should avoid adding a property not reset by that shorthand to such a struct. Once you know which struct you're going to use (or that the property is a shorthand), you can add appropriate entry to nsCSSPropList.h. Again, see the documentation at the top of the file and the other entries for examples, and also see the next section for details about parsing. Parsing To start implementing the parsing, first read the Syntax line in the property's specification (whose syntax is in turn defined in the CSS Values and Units specification) and any prose in the specification that adds additional restrictions to that syntax. Every proper...
...his case would break partial computation based on a start struct, which is when we computed style data on the basis of computed data we've already computed from a subset of the style rules that we're currently computing from. Then you need to change nsStyle*::CalcDifference (in nsStyleStruct.cpp) to describe how dynamic changes of your new CSS property need to be handled. See nsChangeHint.h for documentation (or if that's not sufficient, see RestyleManager::ProcessRestyledFrames). Then you need to change nsComputedDOMStyle.cpp to implement the getComputedStyle API. You'll need to add an entry in nsComputedDOMStylePropertyList.h and then add a method (matching the method name in the CSS property list) to implement the API. While we implement the string API in terms of the value API, we general...
Creating Custom Events That Can Pass Data
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. ...
... nsCOMPtr<nsIDOMMyEvent> myEvent; //this is a handle to the your inteface to the event. wwatcher->GetActiveWindow(getter_AddRefs(aWindow)); //get ...
... nsCOMPtr<nsIDOMMyEvent> myEvent; //this is a handle to the your inteface to the event. wwatcher->GetActiveWindow(getter_AddRefs(aWindow)); //get the Active window. aWindow->GetDoc...
...ent nsCOMPtr<nsIDOMEventTarget> tWindow; // the target window (really the same window as above but you need // a different inteface :/ nsCOMPtr<nsIDOMEvent> event; //this will be the event we throw. nsCOMPtr<nsIDOMMyEvent> myEvent; //this is a handle to the your inteface to the event. wwatcher->GetActiveWindow(getter_AddRefs(aWindow)); //get the Active window. aWindow->GetDocument(getter_AddRefs(aDoc)); //get the document from the window. nsCOMPtr<nsIDOMDocumentEvent> docEvent = do_QueryInterface(aDoc); //change interfaces so you can create interfaces. docEvent->CreateEvent(NS_LITERAL_STRING("nsDOMMyEvent"), getter_AddRefs(event)); //create the event event->InitEvent(NS_LITERAL_STRING("nsDOMMyEvent"), PR_TRUE, PR_TRUE); //initialize it tWindow = do_Quer...
Runtime Directories
~/.mozilla/firefox/xxxx...
... ~/.mozilla/firefox/xxxxxxxx.default/ n/d Thunderbird OS Application Directory User Profile Directory Tempo...
... ~/.thunderbird/xxxxxxxx.default/ (or ~/...
... ~/.thunderbird/xxxxxxxx.default/ (or ~/.mozilla-thunderbird/xxxxxxxx.default/ on Debian/Ubuntu) n/d See also https://support.mozil...
Limitations of chrome scripts
ensions: they are only a temporary measure, and will be removed eventually they can have a bad effect on responsiveness there are likely to be edge cases in which they don't work properly You can see all the places where your add-on uses compatibility shims by setting the dom.ipc.shims.enabledWarnings preference and watching the browser console as you use the add-on. The rest of this page documents patterns that don't work in multiprocess Firefox as well as how are shims try to paper over the problem. For each pattern we've noted: whether a shim exists and what kind of behavior it provides how to update your add-on so you don't need the shim gBrowser.contentWindow, window.content... Without the shim All APIs in the chrome process that provide direct access to content objects will n...
...ch pattern we've noted: whether a shim exists and what kind of behavior it provides how to update your add-on so you don't need the shim gBrowser.contentWindow, window.content... Without the shim All APIs in the chrome process that provide direct access to content objects will no longer work. ...
... 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 separate script, load that script into the content process...
...bug 1118880. Also note that unlike other shims, this shim is always active. Alternatively, you can use nsIWebProgressListener in the content process. Observers in the chrome process Depending on the topic, you need to register observers in either the chrome process or in a frame script. For most topics you need to register observers in the chrome process. However, you must listen to content-document-global-created and document-element-inserted in a frame script. Observers for these topics get content objects as the aSubject argument to observe(), so notifications are not sent to the chrome process. There is a shim that will forward these two topics to the chrome process, sending CPOWs as the aSubject argument. HTTP requests You can't observe HTTP requests in the content process. If you do...
Chrome-only CSS reference
Mozilla › Gecko › Chrome › CSS
This page lists CSS properties that are only available in Gecko Chrome code (and sometimes in other privileged circumstances, eg. UA stylesheets.) Note: Most of the CSS properties exposed to the Web in general are also usable in Chrome stylesheets: see the CSS documentation for a list of these. -moz-window-draggingThe -moz-window-dragging CSS property specifies whether a window is draggable or not. ...
..., eg. UA stylesheets.) Note: Most of the CSS properties exposed to the Web in general are also usable in Chrome stylesheets: see the CSS documentation for a list of these. -moz-window-draggingThe -moz-window-dragging CSS property specifies whether a window is draggable or not. ...
... -moz-window-draggingThe -moz-window-dragging CSS property specifies whether a window is draggable or not. ...
...-moz-lwtheme pseudo-class matches in chrome documents when the root element's lightweightthemes attribute is true and a theme is selected.:-moz-lwtheme-brighttextThe :-moz-lwtheme-brighttext pseudo-class matches in chrome documents when :-moz-lwtheme is true and a lightweight theme with a bright text color is selected.:-moz-lwtheme-darktextThe :-moz-lwtheme-darktext pseudo-class matches in chrome documents when :-moz-lwtheme is true and a lightweight theme with a dark text color is selected.::-moz-tree-cellActivated by the properties attribute.::-moz-tree-cell-textActivated by the properties attribute.::-moz-tree-cell-text(hover)The :-moz-tree-cell-text(hover) CSS pseudo-class will match an element if the mouse cursor is presently hovering over text in a tree cell.::-moz-tree-columnActivated by th...
Embedding Tips
you may also implement the nsIURIContentListener::IsPreferred(), returning PR_TRUE to ensure you are always the preferred URI handler and are called no matter what the content type. How do I copy items to the clipboard? Obtain the nsIClipboardCommands interface from the appropriate web browser object via nsIServiceProvider::GetInterface (or the do_GetInterface() helper method). ...
...e called no matter what the content type. How do I copy items to the clipboard? Obtain the nsIClipboardCommands interface from the appropriate web browser object via nsIServiceProvider::GetInterface (or the do_GetInterface() helper method). How do I save a document or data to disk? Query for the nsIWebBrowserPersist interface implemented on the web browser object and call the saveURI() or saveDocument() methods on that. Alternatively, create a standalone webbrowser persist object and call the nsIWebBrowserPersist interface on that to save URIs and documents. This is recommended if you intend anything other than the uri or document your browser is looking at. Register your own nsIWebProgressListener object to listen for progress and state notifications. How do I save / upload a document / dat...
...file to make gecko actually use a profile location. How do I change the user agent string? The default useragent is set using the value from your application.ini/nsXREAppData. You can override this default using the "general.useragent.override" preference. How do I display my own message, alert and prompt boxes? You need to implement and register your own prompt service. How do I get the DOM document from the web browser object? nsCOMPtr<nsIDOMDocument> doc; nsCOMPtr<nsIDOMWindow> window; webBrowser->GetContentDOMWindow(getter_AddRefs(window)); if (window) { window->GetDocument(getter_AddRefs(doc)); } What is the docshell? A description of the docshell may be found here. How do I implement context menus? Make your chrome object implement the nsIContextMenuListener or nsIContextMenuLis...
...at is the docshell? A description of the docshell may be found here. How do I implement context menus? Make your chrome object implement the nsIContextMenuListener or nsIContextMenuListener2. The nsIContextMenuListener::OnShowContextMenu() method will be called with the DOM node that the context applies, the DOM event plus some flag combinations that assist in determining what menu to display (document, link, image, selected text etc.) How do I implement tool tips? Make your chrome object implement the nsITooltipListener interface. Methods to hide or show the tool tips will automatically be called upon it when the user hovers over an item with TITLE text. The contract ID is defined here. For an example, see BrowserImpl.cpp in mfcembed and its simple CBrowserToolTip class implemented in MFC. ...
How Mozilla determines MIME Types
Content-Type "hints" Mozilla has a concept of "content-type hints". This means that, for example, if Mozilla encounters a <link type="text/css" rel="stylesheet" href="..."> element, a type of text/css will be assumed. This is, however, overridden by the actual MIME type the server sends (if any). ...
...c example, the server override only happens in standards-compliant mode. See Mozilla's Quirks Mode or Web Author FAQ). Similar handling happens for <a href="..." type="foo/bar">, starting in Mozilla 1.6alpha. HTTP For HTTP URIs Mozilla usually gets a MIME type sent from the server, and uses it. Contrary to Internet Explorer's MIME type guessing, Mozilla will generally not sniff the type of the document. However, starting in Mozilla 1.7alpha, Mozilla does do content sniffing, like this: When the Content-Type sent by the server is one of (case-sensitively) text/plain text/plain; charset=ISO-8859-1 text/plain; charset=iso-8859-1 and the server did not send a Content-Encoding header, Mozilla will sniff the first block of data it gets and check for non-text bytes. Text bytes are 9-13, 27, an...
...ory. If this fails, the data source is searched via the extension (Content-Disposition as above). ...
...Content-Disposition as above). If one of these lookups succeed, this is where the application in the "Open with" field comes from, and also where the description of the type comes from. ...
Localizing without a specialized tool
From the Create a New Localization document, an interested localizer can follow a technical step-by-step process that starts the localization process by focusing on how to localize two of the primary types of localization files (DTD and properties) used in the Mozilla source code. With that document, users can see immediately two localized files in their user interface by following closely and carefully the steps to create a language pack or a binary file that is ready for installation. Repeating the process allows a localizer to create a testable package to see his or her work as they progress to a final version. ...
...ed files in their user interface by following closely and carefully the steps to create a language pack or a binary file that is ready for installation. Repeating the process allows a localizer to create a testable package to see his or her work as they progress to a final version. If you choose to localize Mozilla with nothing more than a text editing application and not a specialized tool, this document (along with Create a New Localization) will enable you to learn just what needs to be done. Before we start, did you make sure to install Mercurial and confirm that you have set up the proper build environment on your local machine? You cannot begin localizing Mozilla file by file without a specialized tool without going through the Create a New Localization page. What we will translate We will ...
...ght of the location bar, and by default points to the Google search. If you click on the highlighted arrow pointing down while reading this tutorial on MDC, you will see two string that need to be translated: Add "MDC Search" Manage Search Engines... There is also a tooltip that appears when you hover over the magnifying glass icon on the right side of the bar. ...
...Get the source Change your current directory to your working directory with the following command: $ cd /path/to/your/working/directory First, you will need to check out the sources of mozilla-1.9.2 together with the en-US strings. Assuming that you have installed Mercurial, issue the following command: $ hg clone http://hg.mozilla.org/releases/mozilla-1.9.2...
Localization at Mozilla
Localization (L10n) is the process of translating software user interfaces from one language to another and adapting it to suit a foreign culture. These resources are for anyone with an interest in the technical aspects involved in localization. ...
... Localization (L10n) is the process of translating software user interfaces from one language to another and adapting it to suit a foreign culture. These resources are for anyone with an interest in the technical aspects involved in localization. ...
...tware user interfaces from one language to another and adapting it to suit a foreign culture. These resources are for anyone with an interest in the technical aspects involved in localization. They are for developers and all contributors. ...
...hese resources are for anyone with an interest in the technical aspects involved in localization. They are for developers and all contributors. The documentation here is no longer being maintained and is inaccurate. ...
Basics
The context menu won't show up. Rather, the math fragment will zoom, and if you right-click a second time, you will see the MathML WYSIWYG markup of the fragment, and if you right-click again a third time, the fragment will revert to its initial state. ...
...The context menu won't show up. ...
...imes;</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"); setSelection("a42","2"); setSelection("a43","2"); } functio...
... MathML Button HTML Content <div style="text-align: center"> <button style="white-space: normal;"> <span style="color: brown;"> For example, <b>click</b> this MathML continued fraction<br/> inside this H...
Mozilla Web Services Security Model
Please do not depend on anything in it being correct for security.) To prevent the browser from being used as a tool for Web sites to obtain priveleges that belong to the browser's user (such as being behind a firewall or getting the benefits of the user's cookies), Web browsers restrict what Web pages can do when accessing things in other domains. These restrictions apply to Web Services. However, Web Services can be designed to be accessed from other domains, or even from any domain. Mozilla allows sites hosting such Web Services to tell Mozilla that other sites can access the service. ...
...er domains to access Web Services. For example, to determine what Web sites can access a Web Service at http://www.example.com/dir1/dir2/service, Mozilla would load the file http://www.example.com/web-scripts-access.xml, which may choose to delegate the decision to http://www.example.com/dir1/dir2/web...pts-access.xml. web-scripts-access.xml File Format The web-scripts-access.xml file is an XML document. Any errors in XML syntax, as well as many failures to follow the format, will cause the document to be ignored. The webScriptAccess element Its root element must be a webScriptAccess element in the http://www.mozilla.org/2002/soap/security namespace. This element must have either one delegate element child or any number (0 or more) of allow element children. All of these children elements must...
...wed if one of them allows it. The type attribute The type attribute of the allow element can take the following values: any means that the allow element applies to all services that use web-scripts-access.xml for security checks. There may be more such such services in the future than there are now. This is the same as not having a type attribute. load [Not implemented!] Ability to load documents via XMLHttpRequest or similar mechanisms. soap SOAP requests without verification headers soapv SOAP requests with verification headers The from attribute The from attribute on the allow element says which calling sites the allow element applies to. If there is no from attribute then the allow element applies to all sites. The from attribute otherwise gives a URL to match, which may con...
...02/soap/security"> <delegate/> <allow type="none"/> </webScriptAccess> And in the services directory: <webScriptAccess xmlns="http://www.mozilla.org/2002/soap/security"> <allow type="soapv"/> <allow type="soap"/> </webScriptAccess> Good examples (Needed.) References New Security Model for Web Services, the original proposal for the web-scripts-access.xml file format Web Services Roadmap, documenting when Web services features, including the security model, were first supported Additional Reading Documentation of crossdomain.xml, a similar format used by Macromedia Flash Player ...
Mozilla Development Strategies
e content of this article may be out of date. It has not been updated for usage of Mercurial (instead of CVS). Work on the most important bugs first Everyone likes to check in. But keep in mind that your checkin rate isn't everything. It's better to fix one data loss bug, crasher, or performance bug that really affects the user than edge case bugs that are rarely seen or minor bugs. Make sure documentation gets updated If the bug you're fixing is likely to require an update to developer documentation once it's fixed, be sure to add the dev-doc-needed keyword to the bug (or ask someone to do it, if you don't have editbugs privileges on Bugzilla). This puts the bug on the radar of our documentation team to ensure that once the bug is resolved, the documentation will be updated appropriately. If...
... Note: You can mark the bug with this keyword at any time; you don't need to wait until it's actually fixed. ...
...eded keyword to the bug (or ask someone to do it, if you don't have editbugs privileges on Bugzilla). This puts the bug on the radar of our documentation team to ensure that once the bug is resolved, the documentation will be updated appropriately. If you don't mark the bug, your work might go unnoticed by the docs team! Of course, our documentation is a wiki; you can really help by updating the documentation yourself. Even if you're not comfortable with your writing skills, keep in mind that our helpful, happy documentation gnomes will follow along behind you and clean up for you. Note: You can mark the bug with this keyword at any time; you don't need to wait until it's actually fixed. Take extra time to do it right the first time It's also better to come up with one really solid, well teste...
...your local disk cd mozilla find . -type d \! -name CVS | xargs -l -P10 cvs tag -l MY_BASE_TAG > & ../taglog1.txt find . -type d \! -name CVS | xargs -l -P10 cvs tag -b -l MY_BRANCH_TAG > & ../taglog2.txt From your Windows box: cvs co -r MY_BRANCH_TAG mozilla/client.mak cd mozilla edit client.mak, putting MY_BRANCH_TAG in the right places. cvs commit client.mak nmake -f client.mak Original Document Information Author(s): Seth Spitzer and Alec Flett Last Updated Date: September 3, 2006 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Mozilla Quirks Mode Behavior
58899). Residual style tags' size info does not take precedence over heading tags' size (bug 77352). Use box-sizing:border-box for most INPUT types and TEXTAREA. Give FORM a margin-bottom:1em (bug 41806). In quirks mode CSS class and id names are case insensitive. In standards mode they are case sensitive. (This also applies to getElementsByClassName.) Stylesheets linked in the document with an advisory MIME type of text/css will still be treated as CSS even if the server gives a Content-Type header other than text/css. The CSS parser accepts colors not beginning with #, except in shorthands. The CSS parser interprets unitless numbers as px (except for line-height and any other properties where they have distinct meaning, and except in shorthands). In quirks mode, the CSS par...
...lass:hover did not work. Prior to Gecko 36, it also applied to images, and form controls but the quirk has been adapted to match the behavior of other browser (bug 783213). Prior to Gecko 36, the quirk was also applied if another pseudo-class was used in the same selector, if a pseudo-element was used in the selector, or if it was part of a pseudo-class argument (bug 783213). Quirks mode has document.all support (undetected). Images (IMG elements) without alt attributes sometimes display placeholder icons in quirks mode. Obsolete since Gecko 2.0 HTML colors were parsed differently up to Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) (bug 121738). In quirks mode, the URL fragment #top scrolls to the top of the page when there is no such anchor. Obsolete since Gecko 10.0 However,...
...o blocks in between), it is assumed that it is not possible to break before and after an image (when otherwise it would be). Obsolete since Gecko 8.0 Prior to Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5) text-decoration in quirks mode had line thickness and position adjusted on descendant text to match the descendant. Tables TD, TH, TR, THEAD, TBODY, and TFOOT elements have the document background (and color?) applied to them (when the document background is specified in certain ways?) (see also bug 70831). [This may have been an accurate description when written in June 2001, but no longer appears accurate. Should look into TableQuirkColorRule, re-describe, and figure out when it changed.] Obsolete since Gecko 37 The empty-cells property defaulted to hide in quirks mode but sh...
...83). Obsolete The scrolling attribute on FRAME is handled differently. ...
Leak-hunting strategies and tips
Use with caution. Strategy for finding leaks When trying to make a particular testcase not leak, I recommend focusing first on the largest object graphs (since these entrain many smaller objects), then on smaller reference-counted object graphs, and then on any remaining individual objects or small object graphs that don't entrain other objects. Because (1) large graphs of leaked objects tend to include some objects pointed to by global variables that confuse GC-based leak detectors, which can make leaks look smaller (as in bug 99180) or hide them completely and (2) large graphs of leaked objects tend to hide smaller ones, it's much better to go after the large graphs of leaks first. ...
...er to the size of a graph of objects, I'm referring to the number of objects, not the size in bytes. ...
...oes. The wrapper itself is just a normal reference-counted object, so a leaked nsXPCWrappedJS can be debugged using the normal refcount-balancer tools. If you really need to debug leaks that involve JS objects closely, you can get detailed printouts of the paths JS uses to mark objects when it is determining the set of live objects by using the functions added in bug 378261 and bug 378255. (More documentation of this replacement for GC_MARK_DEBUG, the old way of doing it, would be useful. It may just involve setting the XPC_SHUTDOWN_HEAP_DUMP environment variable to a file name, but I haven't tested that.) Post-processing of stack traces On Mac and Linux, the stack traces generated by our internal debugging tools don't have very good symbol information (since they just show the results of dladd...
...is allocated with a separate call to malloc. ...
Memory reporting
Memory Reporters A memory reporter makes one or more memory measurements (a.k.a. reports). ...
... Memory Reporters A memory reporter makes one or more memory measurements (a.k.a. reports). ...
... Each reporter implements a collectReports function which takes a nsIMemoryReporterCallback argument; for each measurement the reporter must pass in several values, including: a path (which identifies the report); an amount (the most important thing); a unit (most commonly bytes, but sometimes a unitless count or percentage); a description of what is measured. See the nsIMemoryReporter documentation and nsIMemoryReporter.idl for full details. Making Measurements nsIMemoryReporter provides the high-level interface for a memory reporter, but the heart of a memory reporter is the measurement of the "amount". Two Ways to Measure Memory reporters can be divided into the two following kinds. Traversal-based reporters traverse one or more data structures and measure the size of all the ...
...bject, but instead for the singleton object to implement nsIMemoryReporter, and thus measure and report its own memory consumption. There are many such examples in the code, such as nsCategoryManager. If you write a memory reporter, please get two people to review it: (a) someone who knows the data structures being measured, and (b) nnethercote, who can check for all the things covered by this document. Thanks! DMD DMD is a tool that detects two deficiencies with memory reporters. It identifies places in the code that allocate memory but do not have memory reporters for that memory. This helps drive about:memory's heap-unclassified number down. It detects certain defects in existing heap memory reporters: if non-heap memory is reported, or if a heap block is partially reported or double-r...
TraceMalloc
TraceMalloc captures stack traces of all malloc, calloc , realloc, and free calls (this currently covers all operator new and delete calls in Mozilla, too). To enable TraceMalloc in your build, configure with --enable-trace-malloc. The built Mozilla application will support the following additional command-line options: --trace-malloc filename The application will log allocation and deallocation events with stack traces in a binary format to the given file. ...
... Also, your JavaScript can call the following DOM...
... ...
...ets of nodes in the graph in which any node is reachable from all other nodes). (A strongly connected component with only one node is listed as a single object.) Any single object listed as a root is really a leak root, and any component listed as a root either (a) contains an object that is a root or (b) contains objects that form an ownership cycle that is a root. Other documentation Some older documentation about TraceMalloc is here. ...
NSS_3.11.10_release_notes.html
NSS 3.11.10 Release Notes 2008-12-10 Newsgroup: <ahref="news: mozilla.dev.tech.crypto"="" news.mozilla.org="">mozilla.dev.tech.crypto</ahref="news:> Contents Introduction Distribution Information Bugs Fixed Documentation Compatibility Feedback Introduction Network Security Services (NSS) 3.11.10 is a patch release for NSS 3.11. The bug fixes in NSS 3.11.10 are described in the "Bugs Fixed" section below. Distribution Information The CVS tag for the NSS 3.11.10 release is NSS_3_11_10_RTM. NSS 3.11.10 requires NSPR 4.7.1. See the Documentation section for the build instructions. NSS 3.11.10 source and binary distributions are also available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/...
...New and revised documents available since the release of NSS 3.9 include the following: Build Instructions for NSS 3.11.4 and above Compatibility NSS 3.11.10 shared libraries are backward compatible with all older NSS 3.x shared libraries. A program linked with older NSS 3.x shared libraries will ...
...A program linked with older NSS 3.x shared libraries will work with NSS 3.11.10 shared libraries witho...
...ions and diginotar root certs to NSS Bug 442912: fix nssckbi version number on 3.11 branch Bug 443045: Fix PK11_GenerateKeyPair for ECC keys on the 3.11 branch Bug 444850: NSS misbehaves badly in the presence of a disabled PKCS#11 slot Bug 462948: lint warnings for source files that include keythi.h Documentation For a list of the primary NSS documentation pages on mozilla.org, see NSS Documentation. New and revised documents available since the release of NSS 3.9 include the following: Build Instructions for NSS 3.11.4 and above Compatibility NSS 3.11.10 shared libraries are backward compatible with all older NSS 3.x shared libraries. A program linked with older NSS 3.x shared libraries will work with NSS 3.11.10 shared libraries without recompiling or relinking. Furthermore, a...
NSS 3.12.4 release notes
Information This release is built from the source, at the CVS repository rooted at cvs.mozilla.org:/cvsroot, with the CVS tag NSS_3_12_4_RTM. NSS 3.12.4 requires NSPR 4.8. This is not a hard requirement. Our QA tested NSS 3.12.4 with NSPR 4.8, but it should work with NSPR 4.7.1 or later. You can check out the source from CVS by cvs co -r NSPR_4_8_RTM NSPR cvs co -r NSS_3_12_4_RTM NSS See the Documentation section for the build instructions. NSS 3.12.4 source is also available on ftp.mozilla.org for secure HTTPS download: Source tarball: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_12_4_RTM/src/. Major changes in NSS 3.12.4 NSS 3.12.4 is the version that we submitted to NIST for FIPS 140-2 validation. Currently NSS 3.12.4 is in the "Review Pending" state in the FIPS 1...
...so available on ftp.mozilla.org for secure HTTPS download: Source tarball: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_12_4_RTM/src/. Major changes in NSS 3.12.4 NSS 3.12.4 is the version that we submitted to NIST for FIPS 140-2 validation. ...
...ges in NSS 3.12.4 NSS 3.12.4 is the version that we submitted to NIST for FIPS 140-2 validation. Currently NSS 3.12.4 is in the "Review Pending" state in the FIPS 140-2 pre-validation list at http://csrc.nist.gov/groups/STM/cmvp/documents/140-1/140InProcess.pdf Added CRL Distribution Point support (see cert.h). CERT_DecodeCRLIssuingDistributionPoint CERT_FindCRLIssuingDistPointExten The old documentation of the expression matching syntax rules was incorrect, and the new corrected documentation is as follows for public nssutil functions (see portreq.h): PORT_RegExpValid PORT_RegExpSearch PORT_RegExpCaseSearch These functions will match a string with a shell expression. The expressions accepted are based loosely on the expressions accepted by zsh. Expected return values: NON_SXP if exp ...
...@ PORT_FreeArena - lg_mkSecretKeyRep] when PORT_NewArena fails Bug 507482: NSS 3.12.3 (and later) doesn't build on AIX 5.1 Bug 507937: pwdecrypt program problems Bug 508259: Pk11mode crashed on Linux2.4 Bug 508467: libpkix ocsp checker should use date argument to obtain the time for cert validity verification Bug 510367: Fix the UTF8 characters in the nickname string for AC Raiz Certicamara S.A. Documentation For a list of the primary NSS documentation pages on developer.mozilla.org, see NSS. New and revised documents available since the release of NSS 3.12 include the following: Build Instructions for NSS 3.12.4 Compatibility NSS 3.12.4 shared libraries are backward compatible with all older NSS 3.x shared libraries. A program linked with older NSS 3.x shared libraries will work with NSS 3.12.
NSS 3.12.5 release_notes
a patch release for NSS 3.12. The bug fixes in NSS 3.12.5 are described in the "Bugs Fixed" section below. NSS 3.12.5 is tri-licensed under the MPL 1.1/GPL 2.0/LGPL 2.1. Distribution Information The CVS tag for the NSS 3.12.5 release is NSS_3_12_5_RTM. NSS 3.12.5 requires NSPR 4.8. You can check out the source from CVS by cvs co -r NSPR_4_8_RTM NSPR cvs co -r NSS_3_12_5_RTM NSS See the Documentation section for the build instructions. NSS 3.12.5 source is also available on ftp.mozilla.org for secure HTTPS download: Source tarball: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_12_5_RTM/src/. New in NSS 3.12.5 SSL3 & TLS Renegotiation Vulnerability See CVE-2009-3555 and US-CERT VU#120541 for more information about this security vulnerability. All SSL/TL...
...gin Modified functions SGN_Update (see cryptohi.h) The parameter "input" of this function is changed from unsigned char * to const unsigned char *. PK11_ConfigurePKCS11 (see nss.h) The name of some parameters have been slightly changed ("des" became "desc"). Deprecated headers The header file key.h is deprecated. Please use keyhi.h instead. Additional documentation In pk11pub.h: The caller of PK11_DEREncodePublicKey should free the returned SECItem with a SECITEM_FreeItem(..., PR_TRUE) call. PK11_ReadRawAttribute allocates the buffer for returning the attribute value. The caller of PK11_ReadRawAttribute should free the data buffer pointed to by item using a SECITEM_FreeItem(item, PR_FALSE) or PORT_Free(item->data) call. In secasn1.h: ...
...codePublicKey leaks a CERTSubjectPublicKeyInfo Bug 518457: SECKEY_EncodeDERSubjectPublicKeyInfo and PK11_DEREncodePublicKey are duplicate Bug 522510: Add deprecated comments to key.h and pk11func.h Bug 522580: NSS uses PORT_Memcmp for comparing secret data. Bug 525056: Timing attack against ssl3ext.c:ssl3_ServerHandleSessionTicketXtn() Bug 526689: SSL3 & TLS Renegotiation Vulnerability Documentation For a list of the primary NSS documentation pages on mozilla.org, see NSS Documentation. New and revised documents available since the release of NSS 3.11 include the following: Build Instructions NSS Shared DB Compatibility NSS 3.12.5 shared libraries are backward compatible with all older NSS 3.x shared libraries. A program linked with older NSS 3.x shared libraries will work w...
... shared libraries will work with NSS 3.12.5 shared libraries without recompiling or relinking. Furthermore, applications that restrict their use of NSS APIs to the functions listed in NSS Public Functions will remain compatible with future versions of the NSS shared libraries. Feedback Bugs discovered should be reported by filing a bug report with mozilla.org Bugzilla (product NSS). This document was generated by genma teruaki on November 28, 2010 using texi2html 1.82. ...
PKCS11 Implement
Function-specific information organized in the same categories as the PKCS #11 specification. Functions for Different Kinds of Tokens. Summarizes the support NSS expects from different kinds of tokens. Installation. ...
...Function-specific information organized in the same categories as the PKCS #11 specification. Functions for Different Kinds of Tokens. Summarizes the support NSS expects from different kinds of tokens. Installation. ...
...echanismList The NSS calls C_GetMechanismList fairly frequently to identify the mechanisms supported by a token. C_GetMechanismInfo The NSS currently doesn't call C_GetMechanismInfo. This function may be called in the future, so you should implement it anyway. C_InitToken The NSS never calls C_InitToken. C_InitPIN The NSS calls C_InitPIN only in the key generation case, as noted in this document under C_GetTokenInfo, when CFK_LOGIN_REQUIRED = TRUE and CFK_USER_PIN_INITIALIZED = FALSE. C_SetPIN Called only in the key generation case, as noted in this document under C_GetTokenInfo, when CFK_LOGIN_REQUIRED = TRUE and CFK_USER_PIN_INITIALIZED = FALSE. Session Management C_OpenSession The NSS calls C_OpenSession whenever it initializes a token and keeps the session open as long as pos...
...IME and for encrypted transactions over unsecured networks such as the Internet. Multipurpose tokens provide the full range of cryptographic services. They can be thought of as cryptographic accelerator cards. Future releases of NSS will also support multipurpose tokens that are FIPS-140 compliant. Table 1.2 summarizes the PKCS #11 functions (in addition to the other functions described in this document) that NSS expects each type of token to support. PKCS #11 functions required for different kinds of tokens External key distribution tokens Signing tokens Signing and decryption tokens Multipurpose tokens C_Encrypt C_Decrypt CKM_RSA_PKCS CKM_RSA_X_509 (SSL 2.0 server only) C_Decrypt CKM_RSA_PKCS CKM_RSA_X_509 (SSL 2.0 server only) C_Decrypt C_Sign CKM_RSA_PKCS CKM_DSA ...
Network Security Services
.509 v3 certificates, and other security standards. For detailed information on standards supported, see Overview of NSS. For a list of frequently asked questions, see the FAQ. NSS is available under the Mozilla Public License. For information on downloading NSS releases as tar files, see Download PKI Source. If you're a developer and would like to contribute to NSS, you might want to read the documents highlevel overview of internal details of NSS and getting started with NSS. Documentation Background Information Overview of NSS Provides a brief summary of NSS and its capabilities. NSS FAQ Answers basic questions about NSS. Introduction to Public-Key Cryptography Explains the basic concepts of public-key cryptography that underlie NSS. ...
... by the NSS shared libraries. NSS SSL Reference API used to invoke SSL operations. NSS API Guidelines Explains how the libraries and code are organized, and guidelines for developing code (naming conventions, error handling, thread safety, etc.) NSS Technical Notes Links to NSS technical notes, which provide latest information about new NSS features and supplementary documentation for advanced topics in programming with NSS. Tools, testing, and other technical details Build Instructions for NSS Describe how to check out and build NSS releases. NSS Developer Tutorial How to make changes in NSS. Coding style, maintaining ABI compatibility. NSS Tools Tools for developing, debugging, and managing applicat...
...ts for NSS 3.2 and later releases. Encryption Technologies Available in NSS 3.11 Archived version. Lists the cryptographic algorithms used by NSS 3.11. NSS 3.1 Loadable Root Certificates Archived version. Describes the scheme for loading root CA certificates. cert7.db Archived version. General format of the cert7.db database. ...
...te policy List of pre-loaded CA certificates Consumers of this list must consider 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. Additional Information Using the window.crypto object from JavaScript Delegation of HTTP download for OCSP TLS Cipher Suite Discovery NSS Certificate Download Specification FIPS Mode - an explanation Format of key log files View all NSS-related articles on MDN Planning Information on NSS planning can be found at wiki.mozilla.
Redis Tips
It is intended primarily for developers, and deliberately omits some topics that will be important in any redis deployment, like security and backups. Some Uses for Redis Data Types You may have heard of Redis referred to as a NoSQL Database. Technically, this is true: It's a database that doesn't use SQL. But the statement is meaningless. It is also true that ice cream is a food that isn't made from whale meat. ...
..., LINSERT, LINDEX, etc. event logging lists, zsets, pubsub queues lists (RPUSH, BLPOP, BLPOPRPUSH, etc.) priority queues zsets membership sets, bitstrings state hashes heartbeats zsets hit counters zsets message broadcast pubsub search reverse indexes (never use KEYS in production) Documentation Redis has fantastic documentation. Yet redis is so easy to learn and use that you'll seldom feel you need to consult it. There are three reasons to look at the docs for every command you use. Time complexity - Each command's complexity is given in Big-O notation. This is immensely helpful. Related commands - An ever-growing list of related commands is given on the right-hand side of ...
...is given in Big-O notation. This is immensely helpful. Related commands - An ever-growing list of related commands is given on the right-hand side of the page. Recipes - At the bottom of many pages is a section that gives usage patterns or recipes for the command under discussion. There are many insightful ideas to be found here. Getting Started with Redis Before you go any further in this document, make sure you have played with redis for at least 5 or 10 minutes. If you have not, here is a fantastic on-line, interactive redis tutorial: http://try.redis.io/ For reference later on, you'll want the source of all things redis: https://redis.io You'll want to run a redis-server on your machine, and use the redis-cli at the command-line for hacking. Node.JS redis client: https://gith...
... some cases, stashing JSON or passing it over queues and pubsub channels could be the right thing to do. I think logging data is a good candidate for this. But before you start cramming huge messes of stringified JSON in your db, check in with your gut and ask yourself: Does the structure of the JSON matter for my queries? How much space could this consume over time? Do I want a structured document db and/or sql on the side? If the structure matters, consider using redis hashes or flattening your data across your keyspace. Or consider storing the JSON data in MongoDB and manipulating pointers and commonly-used and/or rapidly-changing metadata in redis. Maybe the data doesn't belong in your redis memory at all? For example, if you have a job queueing system, you might want redis to man...
Gecko events
IALOG_END A dialog box has been closed Is Supported: no EVENT_SCROLLING_START Scrolling has started on a scroll bar Is Supported: yes EVENT_SCROLLING_END Scrolling has ended on a scroll bar Is Supported: yes EVENT_MINIMIZE_START A window object is about to be minimized or maximized Is Supported: no EVENT_MINIMIZE_END A window object has been minimized or maximized Is Supported: no EVENT_DOCUMENT_LOAD_START Is Supported: yes EVENT_DOCUMENT_LOAD_COMPLETE The loading of the document has completed. Is Supported: yes EVENT_DOCUMENT_RELOAD The document contents are being reloaded. Is Supported: yes EVENT_DOCUMENT_LOAD_STOPPED The loading of the document was interrupted. Is Supported: yes EVENT_DOCUMENT_ATTRIBUTES_CHANGED The document wide attributes of the document object have chang...
... Is Supported: no EVENT_PROPERTY_CHANGED Is Supported: no EVENT_SELECTION_CHANGED Is Supported: yes EVENT_TEXT_ATTRIBUTE_CHANGED A text object's attributes changed. Also see EVENT_OBJECT_ATTRIBUTE_CHANGED Is Supported: no EVENT_TEXT_CARET_MOVED The caret has moved to a new position. ...
... Is Supported: no EVENT_PROPERTY_CHANGED Is Supported: no EVENT_SELECTION_CHANGED Is Supported: yes EVENT_TEXT_ATTRIBUTE_CHANGED A text object's attributes changed. Also see EVENT_OBJECT_ATTRIBUTE_CHANGED Is Supported: no EVENT_TEXT_CARET_MOVED The caret has moved to a new position. ...
... another, or focus moved from a non-hypertext object to a hypertext object, or focus moved from a hypertext object to a non-hypertext object. EVENT_HYPERTEXT_NLINKS_CHANGED The number of hyperlinks associated with a hypertext object changed. EVENT_OBJECT_ATTRIBUTE_CHANGED An object's attributes changed. Also see EVENT_TEXT_ATTRIBUTE_CHANGED. EVENT_PAGE_CHANGED A slide changed in a presentation document or a page boundary was crossed in a word processing document. EVENT_INTERNAL_LOAD Used internally in Gecko. EVENT_REORDER An object's children have changed ...
Implementation Details
AT-SPI Events Refer to specific pages to get information of supported events for interested AT API: Gecko MSAA IA2 AT-SPI Implementation Features This ...
...Instead, the same information is available via theISimpleDOMDocument interface. AT-SPI Events Refer to specific pages to get information of supported events for interested AT API: Gecko MSAA IA2 AT-SPI Implementation Features This section highlights special features of AT APIs implementation by Gecko. Unsu...
...ported object attributes for interested AT API: Gecko MSAA IA2 AT-SPI Text Attributes Refer to specific pages to get information of supported text attributes for interested AT API: Gecko MSAA - doesn't have a way to expose text attributes, use IA2 IA2 AT-SPI Document Attributes Refer to specific pages to get information of supported document attributes for interested AT API: Gecko/MSAA/IA2 - document attributes are not exposed. Instead, the same information is available via theISimpleDOMDocument interface. AT-SPI Events Refer to specific pages to get information of supported events for interested AT API: Gecko MSAA IA2 AT-SPI Implementation Features This section highlights special features of AT APIs implementation by Gecko. Unsupported Features We do not support some AT APIs features. Ple...
...cial features of AT APIs implementation by Gecko. Unsupported Features We do not support some AT APIs features. Please refer to pages below for interesting AT API: MSAA IA2 AT-SPI Differences With Other Applications This section provides information about implementation differences between Gecko based applications and other applications. MSAA AT-SPI How to Find the Content Window and Load the Document In XUL-based clients, screen readers may need to find the content window so that they know where to start grabbing the accessible tree, in order to load the current document into a buffer in their own process. Refer to specific pages for interested AT API. MSAA/IAccessible2 AT-SPI Avoiding Memory Leaks It is the assistive technology's responsibility to watch for events that indicate when window...
Feed content access API
However, you could also parse it from a file using parseFromStream(), or directly from an URL using parseAsync(). The actual processing of the parsed feed is done by a method called handleResult() on the FeedTestResultListener object. That code looks like this: FeedTestResultListener.prototype = { handleResult: ...
...e parsed feed is done by a method called handleResult() on the FeedTestResultListener object. ...
...To get the title of the feed, you look at the feed.title property. The title is an nsIFeedTextConstruct that can represent the text in various formats; we ...
...present the text in various formats; we get its text property to fetch the feed's title as HTML-encoded text. We could, alternatively, use its plainText() method to get a copy of the title translated into plain text. We then scan the array of items in the feed by looking at the feed.items nsIArray. This array contains nsIFeedEntry objects that describe each feed item. We build the contents of the document by looking at the title, link, summary, and content properties for each item. The full URL of the link is retrieved using the link's resolve() method. To initialize a fetch of the feed, we simply call fetch(url). This opens a new window containing the feed contents, with each item's title a clickable link that takes you to the article itself. For details on each of the feed access interfaces, vis...
Mozilla internal string guide
Most 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 libxul). Introduction The string classes are a library of C++ classes which are used to manage buffers of wide (16-bit) and narrow (8-bit) character strings. The headers and implementation are in the xpcom/string directory. All strings are stored as a single contiguous buffer of characters. The 8-bit and 16-bit string classes have completely separate base classes, but share the same APIs. ...
...character strings. The headers and implementation are in the xpcom/string directory. All strings are stored as a single contiguous buffer of characters. The 8-bit and 16-bit string classes have completely separate base classes, but share the same APIs. As a result, you cannot assign a 8-bit string to a 16-bit string without some kind of conversion helper class or routine. For the purpose of this document, we will refer to the 16-bit string classes in class documentation. Every 16-bit class has an equivalent 8-bit class: Naming convention for wide and narrow string classes Wide Narrow nsAString nsACString nsString nsCString nsAutoString nsAutoCString etc... The string classes distinguish, as part of the type hierarchy, between strin...
... == 0 .Equals(string) - TRUE if the given string has the same value as the current string. Common methods that modify the string: .Assign(string) - Assigns a new value to the string. .Append(string) - Appends a value to the string. .Insert(string, position) - Inserts the given string before the code unit at position. .Truncate(length) - shortens the string to the given length. Complete documentation can be found in the Appendix. Read-only strings The const attribute on a string determines if the string is writable. If a string is defined as a const nsAString then the data in the string cannot be manipulated. If one tries to call a non-const method on a const string the compiler will flag this as an error at build time. For example: void nsFoo::ReverseCharacters(nsAString& str) { ...
...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 write past the logical length of the string. Use SetLength() or BulkWrite() as appropriate. Original Document Information Author: Alec Flett Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. Thanks to David Baron for actual docs, Peter Annema for lots of direction Myk Melez for some more docs David Bradley for a diagram Revised by Darin Fisher for Mozilla 1.7 Revised by Jungshik...
XPCOM guide
Mozilla › Tech › 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. ...
... 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. ...
... 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 libxul). mozilla::services namespaceThe services C++ namespace offers an easy and efficient alternative for obtaining a service as compared to the indirect XPCOM approach: GetService(), CallGetService(), etc methods are expensive and should be avoided when possible.Receiving startup notificati...
...ry for XPCOM components to receive notifications as to the progress of the application's startup process, so they can start new services at appropriate times, for example.XPCOM array guideMozilla has many array classes because each array is optimized for a particular usage pattern. This guide describes the available arrays as well as the enumerator classes that can be used to get to them. In this document the term Array refers to a container for multiple objects with a numeric, zero-based index.XPCOM changes in Gecko 2.0Several changes that affect XPCOM component compatibility are taking place in Gecko 2. This article details those changes, and provides suggestions for how to update your code.XPCOM hashtable guideA hashtable is a data construct that stores a set of items. Each item has a key that ...
Components.utils.exportFunction
Xray filtering and waiving Xrays provide a...
...nsole.log(user.name); // "Jim" window.changeMyName(user); console.log(user.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, con...
...Because you can call Function Xrays just like normal functions, this means that passing callbacks into the exported function just works, making the allowCallbacks option redundant: // privilege...
...This prevents passing cross-origin objects (like Window or Location) to privileged functions, since the privileged code will have full ac...
IAccessibleHypertext
A typical implementation is to implement this interface on the smallest text object such as a paragraph of text. ...
...A typical implementation is to implement this interface on the smallest text object such as a paragraph of text. ...
...A typical implementation is to implement this interface on the smallest text object such as a paragraph of text. ...
...A typical implementation is to implement this interface on the smallest text object such as a paragraph of text. ...
imgICache
image/public/imgICache.idlScriptable Please add a summary to this article. Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) As of Firefox 18, there is no longer a single image cache. That means that using getService in order to obtain it will yield incorrect results. ...
...e Please add a summary to this article. Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) As of Firefox 18, there is no longer a single image cache. That means that using getService in order to obtain it will yield incorrect results. ...
... a summary to this article. Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) As of Firefox 18, there is no longer a single image cache. That means that using getService in order to obtain it will yield incorrect results. ...
...orrect results. Use the following snippet to obtain a relevant image cache for a given document or channel (where relevantDocument is a Document object that contains images you care about, or relevantChannel is an nsIChannel that is used for fetching images): var tools = Components.classes["@mozilla.org/image/tools;1"].getService(Components.interfaces.imgITools); var cache = tools.getImgCacheForDocument(relevantDocument); // alternatively, tools.getImgCacheForChannel(relevantChannel) If there is no relevant document or channel, null may be passed, but this will cause any image cache requests to use the permanent storage cache (ie. any images from windows in private browsing mode will not be present in the cache returned from a call with a null parameter). Method overview void ...
nsIChannel
n earlier versions callers could get the "content-length" property as 64-bit value by QueryInterfacing the channel to nsIPropertyBag2, if that interface is exposed by the channel. contentType ACString The MIME type of the channel's content if available. Note: The content type can often be wrongly specified (For example wrong file extension, wrong MIME type, wrong document type stored on a server and so on.), and the caller most likely wants to verify with the actual data. Setting contentType before the channel has been opened provides a hint to the channel as to what the MIME type is. The channel may ignore this hint in deciding on the actual MIME type that it will report. Setting contentType after onStartRequest has been fired or after open() is called ...
...changed, then a cached interface pointer may become invalid and may therefore need to be re-queried. originalURI nsIURI The original URI used to construct the channel. This is used in the case of a redirect or URI "resolution" (For example resolving a resource: URI to a file: URI) so that the original pre-redirect URI can still be obtained. This is also used as the RI of the document resulting from the channel, unless the channel has the LOAD_REPLACE flag set. This is never null. Attempts to set it to null must throw. Note: This is distinctly different from the http Referer (referring URI), which is typically the page that contained the original URI (accessible from nsIHttpChannel.) owner nsISupports The owner, corresponding to the entity that is res...
... interfaces nsITransportSecurityInfo and nsISSLStatusProvider Read only. URI nsIURI The URI corresponding to the channel. Its value is immutable. Read only. Constants Channel specific load flags: Bits 23-31 are reserved for future use by this interface or one of its derivatives (For an example see nsICachingChannel). Constant Value Description LOAD_DOCUMENT_URI 16 Set (for example by the docshell) to indicate whether or not the channel corresponds to a document URI. LOAD_RETARGETED_DOCUMENT_URI 17 If the end consumer for this load has been retargeted after discovering its content, this flag will be set: LOAD_REPLACE 18 This flag is set to indicate that this channel is replacing another channel. This means tha...
... method of some other channel This channel's URI is a better identifier of the resource being accessed than this channel's originalURI. This flag can be set, for example, for redirects or for cases when a single channel has multiple parts to it (and thus can follow onStopRequest with another onStartRequest/onStopRequest pair, each pair for a different request). LOAD_INITIAL_DOCUMENT_URI 19 Set (for example by the docshell) to indicate whether or not the channel corresponds to an initial document URI load (for example link click). LOAD_TARGETED 20 Set (For example by the URILoader) to indicate whether or not the end consumer for this load has been determined. LOAD_CALL_CONTENT_SNIFFERS 21 If this flag is set, the channel should call th...
nsIContentView
coming; see bug 618975 for details. Method overview void scrollBy(in float dxPx, in float dyPx); void scrollTo(in float xPx, in float yPx); void setScale(in float xScale, in float yScale); Attributes Attribute Type Description contentHeight float Read only. contentWidth float Dimensions of scrolled content in chrome-document CSS pixels. Read only. id nsContentViewId ID that can be used in conjunction with nsIDOMWindowUtils to change the actual document, instead of just how it is transformed; this is a 64-bit unsigned integer. Read only. scrollX float Horizontal scroll offset in chrome-document CSS pixels. When this view is active (that is it is being painted because it's in the...
...Fails if the view isn't valid. ...
...isible region of the screen), this value is at first lined up with the content's scroll offset. Note: When this view becomes inactive, the new content view will have scroll values that are reset to the default. Read only. scrollY float Horizontal scroll offset in chrome-document CSS pixels. Read only. viewportHeight float Height of the viewport in chrome-document CSS pixels. Read only. viewportWidth float Width of the viewport in chrome-document CSS pixels. Read only. Methods scrollBy() Scrolls the content view by the specified number of chrome-document CSS pixels along each axis. Fails if the view isn't valid. void scrollBy( in float dxPx, in float dyPx ); Parameters dxPx The number of CSS pixels to scroll on the X axis...
...loat dxPx, in float dyPx ); Parameters dxPx The number of CSS pixels to scroll on the X axis; specify a positive value to scroll to the right or a negative value to scroll to the left. dyPx The number of CSS pixels to scroll on the Y axis; specify a positive value to scroll down or a negative value to scroll up. scrollTo() Scrolls the content view to the specified position, in chrome-document CSS pixels. Fails if the view isn't valid. void scrollTo( in float xPx, in float yPx ); Parameters xPx The X coordinate to scroll to, in CSS pixels. yPx The Y coordinate to scroll to, in CSS pixels. setScale() Sets the content view's scale for each axis. void setScale( in float xScale, in float yScale ); Parameters xScale Horizontal scaling factor; specify 1.0 to use th...
nsIDOMNode
It represents a single node in the document tree. ...
... dom/interfaces/core/nsIDOMNode.idlScriptable This interface is the primary datatype for the entire Document Object Model. It represents a single node in the document tree. Inherits from: nsISupports Last changed in Gecko 0.9.6 Method overview nsIDOMNode appendChild(in nsIDOMNode newChild) nsIDOMNode cloneNode(in boolean deep); boolean hasAttributes(); boolean hasChildNodes(); nsIDOMNode insertBefore(in nsIDOMNode newChild, in nsIDOMNode refChild) boolean isSupported(in DOMString feature, in DOMString version); void normalize(); nsIDOMNode removeChild(in nsIDOMNode oldChild) nsIDOMNode replaceChild(in nsIDOMNode newChild, in nsIDOMNode oldChild) Attributes Attribute Type Description attributes nsIDOMNamedNodeMap Read only. childNodes nsIDOMNodeList Read ...
... Attributes Attribute Type Description attributes nsIDOMNamedNodeMap Read only. childNodes nsIDOMNodeList Read only. firstChild nsIDOMNode Read only. lastChild nsIDOMNode Read only. localName DOMString Read only. namespaceURI DOMString Read only. nextSibling nsIDOMNode Read only. nodeName DOMString Read only. nodeType unsigned short Read only. nodeValue DOMString ownerDocument nsIDOMDocument Read only. parentNode nsIDOMNode Read only. prefix DOMString previousSibling nsIDOMNode Read only. Constants Constant Value Description ELEMENT_NODE 1 ATTRIBUTE_NODE 2 TEXT_NODE 3 CDATA_SECTION_NODE 4 ENTITY_REFERENCE_NODE 5 ENTITY_NODE 6 PROCESSING_INSTRUCTION_NODE 7 COMMENT_NODE 8 DOCUMENT_NODE 9 DOCUMENT_TYPE_NODE 10 DOCUME...
... in DOMString feature, in DOMString version ); Parameters feature version Return value normalize() void normalize(); Parameters None. removeChild() nsIDOMNode removeChild( in nsIDOMNode oldChild ); Parameters oldChild Return value replaceChild() nsIDOMNode replaceChild( in nsIDOMNode newChild, in nsIDOMNode oldChild ); Parameters newChild oldChild Return value See also Document Object Model (DOM) Level 2 Core SpecificationREC ...
nsIDOMXPathEvaluator
PathNSResolver createNSResolver(in nsIDOMNode nodeResolver); nsISupports evaluate(in DOMString expression, in nsIDOMNode contextNode, in nsIDOMXPathNSResolver resolver, in unsigned short type, in nsISupports result) Methods createExpression() Creates an nsIDOMXPathExpression which can then be used for (repeated) evaluations. Note: Prior to Gecko 1.9, you could call this method on documents other than the one you planned to run the XPath against; starting with Gecko 1.9, however, you must call it on the same document. nsIDOMXPathExpression createExpression( in DOMString expression, in nsIDOMXPathNSResolver resolver ); Parameters expression A string representing the XPath to be created. resolver A name space resolver created by createNSResolver(), or a use...
...re on Implementing a User Defined Namespace Resolver if you wish to take the latter approach. Return value An XPath expression, as an nsIDOMXPathExpression object. createNSResolver() Creates an nsIDOMXPathExpression which resolves name spaces with respect to the definitions in scope for a specified node. It is used to resolve prefixes within the XPath itself, so that they can be matched with the document. null is common for HTML documents or when no name space prefixes are used. nsIDOMXPathNSResolver createNSResolver( in nsIDOMNode nodeResolver ); Parameters nodeResolver The node to be used as a context for name space resolution. Return value A name space resolver. evaluate() Evaluate the specified XPath expression. nsISupports evaluate( in DOMString expression, in nsIDOMNode con...
...aluate() Evaluate the specified XPath expression. nsISupports evaluate( in DOMString expression, in nsIDOMNode contextNode, in nsIDOMXPathNSResolver resolver, in unsigned short type, in nsISupports result ); Parameters expression A string representing the XPath to be evaluated. contextNode A DOM Node to evaluate the XPath expression against. To evaluate against a whole document, use the document.documentElement. resolver A name space resolver created by createNSResolver(), or a user defined name space resolver. Read more on Implementing a User Defined Namespace Resolver if you wish to take the latter approach. type A number that corresponds to one of the type constants of nsIXPathResult. result An existing nsIXPathResult to use for the result. Us...
... space resolver. Read more on Implementing a User Defined Namespace Resolver if you wish to take the latter approach. ...
nsIDownloadProgressListener
Methods onDownloadStateChange() Called when the status of a particular download changes. void onDownloadStateChange( in short aState, in nsIDownload aDownload ); Parameters aState The previous state of the download. See nsIDownloadManager.Constants for a list of possible values. aDownload The nsIDow...
... Methods onDownloadStateChange() Called when the status of a particular download changes. void onDownloadStateChange( in short aState, in nsIDownload aDownload ); Parameters aState The previous state of the download. See nsIDownloadManager.Constants for a list of possible values. aDownload The nsIDownload object repre...
... Methods onDownloadStateChange() Called when the status of a particular download changes. void onDownloadStateChange( in short aState, in nsIDownload aDownload ); Parameters aState The previous state of the download. See nsIDownloadManager.Constants for a list of possible values. aDownload The nsIDownload object representing the ...
...ss, in nsIRequest aRequest, in unsigned long aStateFlags, in nsresult aStatus, in nsIDownload aDownload); void onStatusChange(in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage, in nsIDownload aDownload); Obsolete since Gecko 1.9.1 Attributes Attribute Type Description document nsIDOMDocument document The document of the download manager frontend. Methods onDownloadStateChange() Called when the status of a particular download changes. void onDownloadStateChange( in short aState, in nsIDownload aDownload ); Parameters aState The previous state of the download. See nsIDownloadManager.Constants for a list of possible values. aDownload The nsIDownload object representing the file whose do...
nsIEditorSpellCheck
l typically be language IDs, such as "en-US". void GetDictionaryList( [array, size_is(count)] out wstring dictionaryList, out PRUint32 count ); Parameters dictionaryList An array into which the list of dictionary name strings are placed. count On return, contains the number of entries in the dictionaryList array. GetNextMisspelledWord() When interactively spell checking the document, this will return the value of the next word that is misspelled. This also computes the suggestions which you can get by calling GetSuggestedWord(). wstring GetNextMisspelledWord(); Parameters None. Return value The next misspelled word in the document. GetPersonalDictionary() Fills an internal list of words added to the personal dictionary. These words can be retrieved using GetPersonalDictiona...
...here are no more suggestions, an empty string (not a null pointer) is returned. wstring GetSuggestedWord(); Parameters None. Return value The next best suggestion for the last word that was checked and was misspelled, or an empty string if there are no remaining suggestions. IgnoreWordAllOccurrences() Tells the spell checker to ignore all occurrences of the specified word when spell checking the document. void IgnoreWordAllOccurrences( in wstring word ); Parameters word The word to ignore when spell checking. InitSpellChecker() Turns on the spell checker for the given editor. void InitSpellChecker( in nsIEditor editor, in boolean enableSelectionChecking ); Parameters editor The nsIEditor on which to enable spell checking. enableSelectionChecking If true, the spe...
... InitSpellChecker() Turns on the spell checker for the given editor. void InitSpellChecker( in nsIEditor editor, in boolean enableSelectionChecking ); Parameters editor The nsIEditor on which to enable spell checking. enableSelectionChecking If true, the spell checker is initialized only for checking the current selection; otherwise, it's initialized for checking the entire document. This affects the behavior of GetNextMisspelledWord()). For spell checking clients with no modal UI (such as inline spell checkers), this flag is not relevant. RemoveWordFromDictionary() Removes a word from the current personal dictionary. void RemoveWordFromDictionary( in wstring word ); Parameters word The word to remove from the current personal dictionary. ReplaceWord() Call thi...
...ilter() Used to filter the content (for example, to skip blockquotes in email from spell checking). Call this before calling InitSpellChecker(); calling it after initialization will have no effect. void setFilter( in nsITextServicesFilter filter ); Parameters filter An nsITextServicesFilter describing the filter to apply. This filter lets you avoid spell checking specific parts of the document. UninitSpellChecker() Call this to release the spell checking object. It will also save the current selected language as the default for future use. If you have called CanSpellCheck() but not InitSpellChecker(), you can still call this function to clear the cached spell check object, and no preferences are saved. void UninitSpellChecker(); Parameters None. UpdateCurrentDictionary() Updates the ...
nsIParserUtils
o--use nsContentUtils, nsTreeSanitizer, and so on directly instead. Implemented by: @mozilla.org/parserutils;1 as a service: var parserUtils = Components.classes["@mozilla.org/parserutils;1"] .getService(Components.interfaces.nsIParserUtils); Method overview AString convertToPlainText(in AString src, in unsigned long flags, in unsigned long wrapCol); nsIDOMDocumentFragment parseFragment(in AString fragment, in unsigned long flags, in boolean isXML, in nsIURI baseURI, in nsIDOMElement element); AString sanitize(in AString src, in unsigned long flags); Constants Constant Value Description SanitizerAllowComments (1 << 0) Flag for sanitizer: Allow comment nodes. SanitizerAllowStyle (1 << 1) Fl...
...o the console for everything that gets sanitized. Methods convertToPlainText() Converts HTML to plain text. ...
... long wrapCol ); Parameters src The HTML source to parse (C++ callers are allowed but not required to use the same string for the return value.) flags Conversion option flags defined in nsIDocumentEncoder. wrapCol Number of characters per line; 0 for no auto-wrapping. Return value The plain text conversion of the HTML specified in src. parseFragment() Parses markup into a sanitized document fragment. nsIDOMDocumentFragment parseFragment( in AString fragment, in unsigned long flags, in boolean isXML, in nsIURI baseURI, in nsIDOMElement element ); Parameters fragment The input markup. flags Sanitization option flags defined above. isXML true if |fragment| is XML and false if HTML. baseURI The base URL for this fragment. element The context node for the fragmen...
...nt( in AString fragment, in unsigned long flags, in boolean isXML, in nsIURI baseURI, in nsIDOMElement element ); Parameters fragment The input markup. flags Sanitization option flags defined above. isXML true if |fragment| is XML and false if HTML. baseURI The base URL for this fragment. element The context node for the fragment parsing algorithm. Return value An nsIDOMDocumentFragment object for the resulting sanitized document fragment. sanitize() Parses a string into an HTML document, sanitizes the document, and returns the result serialized to a string. The sanitizer is designed to protect against XSS when sanitized content is inserted into a different-origin context without an iframe-equivalent sandboxing mechanism. By default, the sanitizer doesn't try to avoi...
nsISHistoryListener
story entry by index, for example, when nsIWebNavigation.gotoIndex() is called. boolean OnHistoryGotoIndex( in long aIndex, in nsIURI aGotoURI ); Parameters aIndex The index in session history of the entry to be loaded. aGotoURI The URI of the session history entry to be loaded. Return value true to allow the operation to proceed or false to cancel it. OnHistoryNewEntry() Called when a new document is added to session history. New documents are added to session history by the docshell when new pages are loaded in a frame or content area; for example by calling nsIWebNavigation.loadURI(). Note: You can't cancel this operation. void OnHistoryNewEntry( in nsIURI aNewURI ); Parameters aNewURI The URI of the document to be added to session history. OnHistoryPurge() Called when entries are r...
...igation.loadURI(). Note: You can't cancel this operation. void OnHistoryNewEntry( in nsIURI aNewURI ); Parameters aNewURI The URI of the document to be added to session history. OnHistoryPurge() Called when entries are removed from session history. Entries can be removed from session history for various reasons; for example to control the browser's memory usage, to prevent users from loading documents from history, to erase evidence of prior page loads, etc. To purge documents from session history call nsISHistory.PurgeHistory(). ...
...See the nsIWebNavigation interface's load constants. ...
...eters aNumEntries The number of entries to be removed from session history. Return value true to allow the purge operation to proceed or false to cancel it. OnHistoryReload() Called when the current document is reloaded, for example due to an nsIWebNavigation.reload() call. boolean OnHistoryReload( in nsIURI aReloadURI, in unsigned long aReloadFlags ); Parameters aReloadURI The URI of the document to be reloaded. aReloadFlags Flags that indicate how the document is to be refreshed. See the nsIWebNavigation interface's load constants. Return value true to allow the reload operation to proceed or false to cancel it. ...
nsIScriptableUnescapeHTML
h legacy extensions) and all its functionality is available with more configuration options via the nsIParserUtils interface. Implemented by: @mozilla.org/feed-unescapehtml;1 as a service: var scriptableUnescapeHTML = Components.classes["@mozilla.org/feed-unescapehtml;1"] .getService(Components.interfaces.nsIScriptableUnescapeHTML); Method overview nsIDOMDocumentFragment parseFragment(in AString fragment, in PRBool isXML, in nsIURI baseURI, in nsIDOMElement element); AString unescape(in AString src); Methods parseFragment() Parses a string of HTML or XML source into a sanitized DocumentFragment. This is equivalent to calling nsIParserUtils::parseFragment(fragment, 0, isXML, baseURI, element). You should call nsIParserUtils::parseFragmen...
... in PRBool isXML, in nsIURI baseURI, in nsIDOMElement element); AString unescape(in AString src); Methods parseFragment() Parses a string of HTML or XML source into a sanitized DocumentFragment. This is equivalent to calling nsIParserUtils::parseFragment(fragment, 0, isXML, baseURI, element). You should call nsIParserUtils::parseFragment() instead of calling this method. nsIDOMDocumentFragment parseFragment( in AString fragment, in PRBool isXML, in nsIURI baseURI, in nsIDOMElement element ); Parameters fragment A string of HTML or XML source to parse as a fragment. isXML Set this to true if the fragment is an XML string; otherwise set it to false. baseURI Pointer to the base URI against which to resolve any URIs included in the fragment. This parameter is igno...
... or XML source to parse as a fragment. isXML Set this to true if the fragment is an XML string; otherwise set it to false. baseURI Pointer to the base URI against which to resolve any URIs included in the fragment. This parameter is ignored if isXML is false. element The nsIDOMElement to be used as the context node for the purposes of the fragment parsing algorithm. Return value An nsIDOMDocumentFragment of the element with the new text appended. Exceptions thrown NS_ERROR_FAILURE Unable to append the text to the element. unescape() Convents HTML source into plain text. This is equivalent to calling nsIParserUtils::convertToPlainText(src, nsIDocumentEncoder::OutputSelectionOnly | nsIDocumentEncoder::OutputAbsoluteLinks, 0). You should call nsIParserUtils::convertToPlainText() ins...
...putSelectionOnly | nsIDocumentEncoder::OutputAbsoluteLinks, 0). You should call nsIParserUtils::convertToPlainText() instead of calling this method. AString unescape( in AString src ); Parameters src The HTML string to convert into plain text. Return value The result of the plain text conversion. Exceptions thrown NS_ERROR_FAILURE Unable to convert the string. ...
XPCOM Interface Reference
lbackmozIStorageStatementParamsmozIStorageStatementRowmozIStorageStatementWrappermozIStorageVacuumParticipantmozIStorageValueArraymozITXTToHTMLConvmozIThirdPartyUtilmozIVisitInfomozIVisitInfoCallbackmozIVisitStatusCallbacknsIAbCardnsIAboutModulensIAbstractWorkernsIAccelerometerUpdatensIAccessNodensIAccessibilityServicensIAccessiblensIAccessibleCaretMoveEventnsIAccessibleCoordinateTypensIAccessibleDocumentnsIAccessibleEditableTextnsIAccessibleEventnsIAccessibleHyperLinknsIAccessibleHyperTextnsIAccessibleImagensIAccessibleProvidernsIAccessibleRelationnsIAccessibleRetrievalnsIAccessibleRolensIAccessibleScrollTypensIAccessibleSelectablensIAccessibleStateChangeEventnsIAccessibleStatesnsIAccessibleTablensIAccessibleTableCellnsIAccessibleTableChangeEventnsIAccessibleTextnsIAccessibleTextChangeEventnsIAcc...
...OMGeoPositionCallbacknsIDOMGeoPositionCoordsnsIDOMGeoPositionErrornsIDOMGeoPositionErrorCallbacknsIDOMGeoPositionOptionsnsIDOMGlobalPropertyInitializernsIDOMHTMLAudioElementnsIDOMHTMLFormElementnsIDOMHTMLMediaElementnsIDOMHTMLSourceElementnsIDOMHTMLTimeRangesnsIDOMJSWindownsIDOMMouseScrollEventnsIDOMMozNetworkStatsnsIDOMMozNetworkStatsDatansIDOMMozNetworkStatsManagernsIDOMMozTouchEventnsIDOMNSHTMLDocumentnsIDOMNavigatorDesktopNotificationnsIDOMNodensIDOMOfflineResourceListnsIDOMOrientationEventnsIDOMParsernsIDOMProgressEventnsIDOMSerializernsIDOMSimpleGestureEventnsIDOMStoragensIDOMStorage2nsIDOMStorageEventObsoletensIDOMStorageItemnsIDOMStorageListnsIDOMStorageManagernsIDOMStorageWindownsIDOMUserDataHandlernsIDOMWindownsIDOMWindow2nsIDOMWindowInternalnsIDOMWindowUtilsnsIDOMXPathEvaluatornsIDOMXPa...
...nsIDOMXULSelectControlItemElementnsIDataSignatureVerifiernsIDebugnsIDebug2nsIDeviceMotionnsIDeviceMotionDatansIDeviceMotionListenernsIDialogCreatornsIDialogParamBlocknsIDictionarynsIDirIndexnsIDirIndexListenernsIDirIndexParsernsIDirectoryEnumeratornsIDirectoryIteratornsIDirectoryServicensIDirectoryServiceProvidernsIDirectoryServiceProvider2nsIDiskCacheStreamInternalnsIDispatchSupportnsIDocShellnsIDocumentLoadernsIDownloadnsIDownloadHistorynsIDownloadManagernsIDownloadManagerUInsIDownloadObservernsIDownloadProgressListenernsIDownloadernsIDragDropHandlernsIDragServicensIDragSessionnsIDroppedLinkHandlernsIDroppedLinkItemnsIDynamicContainernsIEditornsIEditorBoxObjectnsIEditorDocShellnsIEditorIMESupportnsIEditorLoggingnsIEditorMailSupportnsIEditorObservernsIEditorSpellChecknsIEffectiveTLDServicensIEnum...
...backnsIInstallLocationnsIInterfaceRequestornsIJSCIDnsIJSIDnsIJSIIDnsIJSONnsIJetpacknsIJetpackServicensIJumpListBuildernsIJumpListItemnsILivemarkServicensILoadGroupnsILocalFilensILocalFileMacnsILocalensILocaleServicensILoginInfonsILoginManagernsILoginManagerCryptonsILoginManagerIEMigrationHelpernsILoginManagerPrompternsILoginManagerStoragensILoginMetaInfonsIMIMEInputStreamnsIMacDockSupportnsIMarkupDocumentViewernsIMemorynsIMemoryMultiReporternsIMemoryMultiReporterCallbacknsIMemoryReporternsIMemoryReporterManagernsIMenuBoxObjectnsIMessageBroadcasternsIMessageListenernsIMessageListenerManagernsIMessageSendernsIMessageWakeupServicensIMessengernsIMicrosummarynsIMicrosummaryGeneratornsIMicrosummaryObservernsIMicrosummaryServicensIMicrosummarySetnsIMimeConverternsIMimeHeadersnsIModulensIMsgAccountnsIMsgA...
XPCOM Interface Reference by grouping
ort elements (such as device calls). This is the root element and may contain some functions defined in other groups. User This section contains elements specific to a given user's data storage. ...
...itionCoords nsIDOMGeoPositionError nsIDOMGeoPositionErrorCallback nsIDOMGeoPositionOptions nsIDOMGlobalPropertyInitializer Element nsIDOMChromeWindow nsIDOMClientRect nsIDOMElement nsIDOMHTMLAudioElement nsIDOMHTMLFormElement nsIDOMHTMLMediaElement nsIDOMHTMLSourceElement nsIDOMHTMLTimeRanges nsIDOMJSWindow nsIDOMNode nsIDOMNSHTMLDocument nsIDOMStorageItem nsIDOMStorageManager nsIDOMWindow nsIDOMWindow2 nsIDOMWindowInternal nsIDOMWindowUtils nsIDynamicContainer nsIEditor Event nsIDOMEvent nsIDOMEventGroup nsIDOMEventListener nsIDOMEventTarget nsIDOMMouseScrollEvent nsIDOMMozTouchEvent nsIDOMOrientationEvent nsIDOMProgressEvent nsIDOMSimpleGestureEvent ...
...tainer nsIEditor Event nsIDOMEvent nsIDOMEventGroup nsIDOMEventListener nsIDOMEventTarget nsIDOMMouseScrollEvent nsIDOMMozTouchEvent nsIDOMOrientationEvent nsIDOMProgressEvent nsIDOMSimpleGestureEvent nsIDragDropHandler nsIDragService nsIDragSession HTML nsIAccessibilityService nsIAccessibleCoordinateType nsIAccessibleDocument nsIAccessibleEditableText nsIAccessibleEvent nsIAccessibleHyperLink nsIAccessibleHyperText nsIAccessibleImage nsIAccessibleProvider nsIAccessibleRetrieval nsIAccessibleRole nsIAccessibleScrollType nsIAccessibleSelectable nsIAccessibleStates nsIAccessibleTable nsIAccessibleText nsIAccessibleTreeCache nsIAccessibleValue nsIAccessNode ...
...een nsIScreenManager Geolocation nsIGeolocationProvider nsIGeolocationUpdate orientation nsIAcceleration nsIAccelerationListener nsIAccelerometer Misc nsISound nsIWifiMonitor Document nsIWebNavigation Environment nsIEnvironment Event nsIEventListenerInfo nsIEventListenerService nsIEventTarget Exception nsIException Extention nsIExtensionManager nsIInstallLocation External nsIExternalProtocolService ...
Storage
en", which means it is subject to change at any time; in fact, it has changed somewhat with each release of Firefox since it was introduced, and will likely continue to do so for a while. Note: Storage is not the same as the DOM:Storage feature which can be used by web pages to store persistent data or the Session store API (an XPCOM storage utility for use by extensions). Getting started This document covers the Storage API and some peculiarities of SQLite. It does not cover SQL or "regular" SQLite. You can find some very useful links in the See also section however. For Storage API help, you can post to mozilla.dev.apps.platform on the news server news.mozilla.org. To report bugs, use Bugzilla. The overall procedure for use is: Get the Storage service - mozIStorageService. Open a connect...
...is helper object by manually creating the statement wrapper, mozIStorageStatementWrapper, which is provided in Gecko 1.9.1 and later. Using named parameters in C++ is a lot more difficult, so it's generally accepted to use numerical placeholders instead. The example below uses mozIStorageStatement.bindInt32Parameter(). The full list of binding functions can be found with the mozIStorageStatement documentation. C++ example: nsCOMPtr<mozIStorageStatement> statement; rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM table_name WHERE id = ?1"), getter_AddRefs(statement)); NS_ENSURE_SUCCESS(rv, rv); rv = statement->BindInt32Parameter(0, 1234); NS_ENSURE_SUCCESS(rv, rv); Note: Numerical indexes for parameters are always one less than the number you write...
...w.getResultByName("column_name"); } }, handleError: function(aError) { print("Error: " + aError.message); }, handleCompletion: function(aReason) { if (aReason != Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED) print("Query canceled or aborted!"); } }); The call to executeAsync takes an object that implements mozIStorageStatementCallback. See its documentation for more details on each method. The callback is optional, however, so if you do not want to receive feedback, you can pass nothing. Synchronously If you are OK with the possibility of locking up your user interface, or if you are running on a background thread, you can use mozIStorageStatement.executeStep(). This function allows you to enumerate all the results produced by the statement. ...
...like this: var stmt = aConn.createStatement("SELECT * FROM foo ORDER BY name COLLATE locale ASC"); var results = []; while (stmt.executeStep()) { results.push(stmt.row.t); } stmt.finalize(); How to Corrupt a Database SQLite is very good about maintaining database integrity, but there are a few things you can do that can lead to database corruption. You can find out more by reading SQLite's documentation on this. These are a few simple things you can avoid to help make sure this doesn't happen: Open more than one connection to the same file with names that aren't exactly the same as determined by strcmp. This includes "my.db" and "../dir/my.db" or, on Windows (case-insensitive) "my.db" and "My.db". Sqlite tries to handle many of these cases, but you shouldn't count on it. Access a dat...
Using the clipboard
line gets the transferring component which implements nsITransferable. Next we need to initialize it with a "privacy context", which will ensure that source data from inside private browsing mode will be cleared when the mode is exited. Please note: the sourceWindow variable is a placeholder for whatever window owns the data being copied -- from any DOM element you can obtain it via element.ownerDocument.defaultView. If, and only if, you are placing data on the clipboard that is unrelated to web content the user is viewing, you can pass a null privacy context to the init method. The next step is to tell the transferable what type of data we want to use. The type of data is referred to as a data flavor. The function addDataFlavor is used to tell the transferable that it needs to transfer data of ...
...ut and paste operations from the Edit menu typically use. If you use kSelectionClipboard instead, you will copy into the selection buffer, which is generally only available on Unix systems. This multi-step process has resulted in text being copied on the clipboard. We can cut to the clipboard instead of copying by doing a copy and then deleting the original data. Normally, the text would be in a document or textbox. The code is put together below, with additional error checking: var copytext = "Text to copy"; var trans = Transferable(sourceWindow); trans.addDataFlavor("text/unicode"); trans.setTransferData("text/unicode", SupportsString(copytext), copytext.length * 2); Services.clipboard.setData(trans, null, Services.clipboard.kGlobalClipboard); The complete function shown below copies some...
....nsISupportsString).data; } Because the data from the transferable is an nsISupportsString, we need to convert it into a JavaScript string. ...
...ansferable is an nsISupportsString, we need to convert it into a JavaScript string. ...
Thunderbird Configuration Files
Windows and gedit or kate on Linux. Locate your profile folder Before the configuration files are presented, you should know how to find your profile folder, which is where Thunderbird saves all your settings on your hard drive. On Windows Vista/XP/2000, the path is usually %AppData%\Thunderbird\Profiles\xxxxxxxx.default\, where xxxxxxxx is a random string of 8 characters. Just browse to C:\Documents and Settings\[User Name]\Application Data\Thunderbird\Profiles\ on Windows XP/2000 or C:\users\[User Name]\AppData\Roaming\Thunderbird\Profiles\ on Windows Vista, and the rest should be obvious. On Windows 95/98/Me, the path is usually C:\WINDOWS\Application Data\Thunderbird\Profiles\xxxxxxxx.default\ On Linux, the path is usually ~/.thunderbird/xxxxxxxx.default/ On Mac OS X, the path is usua...
...xxx.default\ On Linux, the path is usually ~/.thunderbird/xxxxxxxx.default/ On Mac OS X, the path is usually ~/Library/Thunderbird/Profiles/xxxxxxxx.default/ %AppData% is a shorthand for the Application Data path on Windows 2000/XP/Vista. To use it, click Start > Run... (use the search box on Vista), enter %AppData% and press Enter. You will be taken to the "real" folder, which is normally C:\Documents and Settings\[User Name]\Application Data on Windows XP/2000, C:\users\[User Name]\AppData\Roaming on Windows Vista. Thunderbird is capable of handling more than one user and thus, more than one profile. The path examples above refers to the default profile that is automatically created when you start Thunderbird for the first time. You can manage any number of profiles by using the Profile Man...
... know how to create a file, just skip this section. Before you can create the file, you must make sure that you can see the file type extensions in Windows. Start Explorer (just click on the My Computer icon on your desktop) and select Tools > Folder Options. Click the View tab and uncheck the Hide extensions for known file types option. Now, go to your profile folder and select File > New > Text Document. 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...
... 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. ...
Using COM from js-ctypes
s applications among themselves, Microsoft has developed a series of technologies alongside the main Windows API. This started out with Dynamic Data Exchange (DDE), which was superseded by Object 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 t...
... $ cl ole32.lib test.cpp vtable Needs vtable description here. The order of the vtable is very critical. When used from C or js-ctypes, the order of the vtable methods shou...
... $ cl ole32.lib test.c C code with pseudo struct Needs pseudo struct description here. #include <sapi.h> struct MyISpVoiceVtbl; struct MyISpVoice { struct MyISpVoiceVtbl* lpVtbl; }; struct M...
...It could be converted into js-ctypes in almost straightforward way. CLSID and IID Needs CLSID and IID of SpVoice and ISpVoice description here. COM types and functions Needs COM types (GUID) and functions (CoI...
Debugger.Source - Firefox Developer Tools
from which it was produced. If a single piece of source 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 le...
...cessor on Debugger.Source instances for such sources should return undefined.) If the instance refers to WebAssembly code, the URL of the script that called new WebAssembly.Module with the string "> wasm" appended. sourceMapURL If the instance refers to JavaScript source, if this source was produced by a minimizer or translated from some other language, and we know the URL of a source map document relating the source positions in this source to the corresponding source positions in the original source, then this property's value is that URL. Otherwise, this is null. (On the web, the translator may provide the source map URL in a specially formatted comment in the JavaScript source code, or via a header in the HTTP reply that carried the generated JavaScript.) This property is writable,...
... element The Debugger.Object instance referring to the DOM element to which this source code belongs, if any, or undefined if it belongs to no DOM element. Source belongs to a DOM element in the following cases: Source belongs to a <script> element if it is the element's text content (that is, it is written out as the body of the <script> element in the markup text), or is the source document referenced by its src attribute. Source belongs to a DOM element if it is an event handler content attribute (that is, if it is written out in the markup text as an attribute value). Source belongs to a DOM element if it was assigned to one of the element's event handler IDL attributes as a string. (Note that one may assign both strings and functions to DOM elements' event handl...
...ssigning to the corresponding JavaScript property creates a source whose introductionScript and introductionOffset refer to the property assignment. Since a <script> element parsed from a web page's original HTML was not introduced by any scripted call, its source's introductionScript and introductionOffset accessors both return undefined. If a <script> element was dynamically inserted into a document, then these accessors refer to the call that actually caused the script to run--usually the call that made the element part of the document. Thus, they donot refer to the call that created the element; stored the source as the element's text child; made the element a child of some uninserted parent node that was later inserted; or the like. Although the main script of a worker thread is introdu...
DevTools API - Firefox Developer Tools
e toolbox Parameters: hostType {Toolbox.HostType} - The type of the new host. Return value: A Promise that is fulfilled once the new host is ready. reloadTarget(force) Reloads the current target of the toolbox. Parameters: force {Boolean} - If true the target is shift-reloaded i.e. the cache is bypassed during the reload. zoomIn() Increases the zoom level of the Toolbox document. zoomOut() Decreases the zoom level of the Toolbox document. zoomReset() Resets the zoom level of the Toolbox document. setZoom(value) Set the zoom level to an arbitrary value. Parameters: value {Number} - The zoom level such as 1.2. destroy() Closes the toolbox. Return value: A Promise that is resolved once the Toolbox is destroyed. Events The Toolbox object em...
...e shortcut was triggered for. Return value: Undefined. Properties The ToolDefinition object can contain following properties. Most of them are optional and can be used to customize the presense of the tool in the Browser and the Toolbox. id String, required. An unique identifier for the tool. It must be a valid id for an HTML Element. url String, required. An URL of the panel document. label String, optional. The tool's name. If undefined the icon should be specified. tooltip String, optional. The tooltip for the tool's tab. panelLabel String, optional. An accessibility label for the panel. ordinal Integer, optional. The position of the tool's tab within the toolbox. Default: 99 visibilityswitch String, optional. A preference name that controls th...
... basic template for a ToolPanel implementation. // In the ToolDefintion object, do // build: (window, target) => new MyPanel(window, target), function MyPanel(window, target) { // The window object that has loaded the URL defined in the ToolDefinition this.window = window; // The Target this toolbox is debugging. this.target = target; // Do synchronous initialization here. window.document.body.addEventListener("click", this.handleClick); } MyPanel.prototype = { open: function() { // Any asynchronous operations should be done here. return this.doSomethingAsynchronous() .then(() => this); }, destroy: function() { // Synchronous destruction. this.window.document.body.removeEventListener("click", this.handleClick); // Async destruction. return th...
...ome tool-related conditions, we might want to not let the user select a tab. This API provides methods to hide the tabstripe. For example, in the Web Console, there are 2 views (Network View and Object View). These views are only available in certain conditions controlled by the WebConsole code. So it's up the WebConsole the hide and show the sidebar, and select the correct tab. If the loaded document exposes a window.setPanel(ToolPanel) function, the sidebar will call it once the document is loaded. Method Description new ToolSidebar(xul:tabbox, ToolPanel, uid, showTabstripe=true) ToolSidebar constructor void addTab(tabId, url, selected=false) Add a tab in the sidebar void select(tabId) Select a tab void hide() Hide the sidebar ...
Examine and edit HTML - Firefox Developer Tools
To start searching the markup, click in the search box to expand it or press Ctrl + F , or Cmd + F on a Mac. ...
... To start searching the markup, click in the search box to expand it or press Ctrl + F , or Cmd + F on a Mac. ...
... Collapse In the tree view, collapse the current element. This is equivalent to clicking the disclosure arrow next to an element that's expanded. (Paste) Inner HTML Paste the clipboard contents into the node as its innerHTML. (Paste) Outer HTML Paste the clipboard contents into the node as its outerHTML. (Paste) Before Paste the clipboard contents into the document immediately before this node. (Paste) After Paste the clipboard contents into the document immediately after this node. (Paste) As First Child Paste the clipboard contents into the document as the first child of this node. (Paste) As Last Child Paste the clipboard contents into the document as the last child of this node. Scroll Into View Scrol...
...ent of a page by moving nodes in the HTML tree. Just click and hold on any element and drag it up or down in the tree. When you release the mouse button, the element will be inserted at the corresponding position: You can cancel the drag and drop by pressing the Esc key. Inserting new nodes There's a "+" icon at the top of the markup view: Click this icon to insert an empty <div> into the document as the last child of the currently selected element. You can then edit the new node's content and styling just as you would any other node in the document. You can access the same functionality using the "Create New Node" popup menu item. Note that this button is disabled if the selected element's type is such that adding a last-child would have no effect (for example, if is is an <html> or <...
AudioContext.createMediaElementSource() - Web APIs
ge() function is invoked, which calculates the current gain as a ratio of mouse Y position divided by overall window height. You can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. Note: You can also view this example running live, or view the source. ...
...the current gain as a ratio of mouse Y position divided by overall window height. You can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. Note: You can also view this example running live, or view the source. ...
...n divided by overall window height. You can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. Note: You can also view this example running live, or view the source. ...
...eate a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var source = audioCtx.createMediaElementSource(myAudio); // Create a gain node var gainNode = audioCtx.createGain(); // Create variables to store mouse pointer Y coordinate // and HEIGHT of screen var CurY; var HEIGHT = window.innerHeight; // Get new mouse pointer coordinates when mouse is moved // then set new gain value document.onmousemove = updatePage; function updatePage(e) { CurY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); gainNode.gain.value = CurY/HEIGHT; } // connect the AudioBufferSourceNode to the gainNode // and the gainNode to the destination, so we can play the // music and adjust the volume using...
AudioContext.createMediaStreamSource() - Web APIs
de. Next, we feed this source audio into a low pass BiquadFilterNode (which effectively serves as a bass booster), then a AudioDestinationNode. The range slider below the <video> element controls the amount of gain given to the lowpass filter -- increase the value of the slider to make the audio sound more bass heavy! Note: You can see this example running live, or view the source. ...
...low pass BiquadFilterNode (which effectively serves as a bass booster), then a AudioDestinationNode. The range slider below the <video> element controls the amount of gain given to the lowpass filter -- increase the value of the slider to make the audio sound more bass heavy! Note: You can see this example running live, or view the source. ...
...ves as a bass booster), then a AudioDestinationNode. The range slider below the <video> element controls the amount of gain given to the lowpass filter -- increase the value of the slider to make the audio sound more bass heavy! Note: You can see this example running live, or view the source. ...
...nNode. The range slider below the <video> element controls the amount of gain given to the lowpass filter -- increase the value of the slider to make the audio sound more bass heavy! Note: You can see this example running live, or view the source. ...
AudioParam.exponentialRampToValueAtTime() - Web APIs
e code, or view the example live.) When these buttons are pressed, exponentialRampToValueAtTime() is used to fade the gain value up to 1.0, and down to 0, respectively. ...
...se buttons are pressed, exponentialRampToValueAtTime() is used to fade the gain value up to 1.0, and down to 0, respectively. ...
...AtTime() is used to fade the gain value up to 1.0, and down to 0, respectively. ...
...etty useful for fade in/fade out effects: // create audio context var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext(); // set basic variables for example var myAudio = document.querySelector('audio'); var pre = document.querySelector('pre'); var myScript = document.querySelector('script'); pre.innerHTML = myScript.innerHTML; var expRampPlus = document.querySelector('.exp-ramp-plus'); var expRampMinus = document.querySelector('.exp-ramp-minus'); // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var source = audioCtx.createMediaElementSource(myAudio); // Create a gain node and set its gain value to 0.5 var gainNode = audioCtx.createGain(); // connect the AudioBufferSourceNode to the gainNode // and the gainNode to t...
CSSStyleDeclaration.setProperty() - Web APIs
le.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 contained inside the second stylesheet applied to the page, so we grab a reference to it using document.styleSheets[1]. We then loop through the different rules contained inside the stylesheet, which are contained in the array found at stylesheet.cssRules; for each one, we check whether its CSSStyleRule.selectorText property is equal to the selector .box p, which indicates it is the one we want. If so, we store a reference to this CSSStyleRule object in a variable. We then use three functions to g...
...rgin: 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) + ', ' + random(0,255) + ')'; } const s...
...or('.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) + ', ' + random(0,255) + ')'; } const stylesheet = document.styleSheets[1]; let boxParaRule; for(let i = 0; i < stylesheet.cssRules.length; i++) { if(stylesheet.cssRules[i].selectorText === '.box p') { boxParaRule = stylesheet.cssRules[i]; } } function setRandomBorder() { const newBorder = random(1, 50) + 'px solid ' + randomColor(); boxParaRule.style.setProperty('border', newBorder); } function setRandomBgColor() { const newBgColor = ran...
... Obsolete ...
CSSStyleSheet.insertRule() - Web APIs
with a HierarchyRequestError. If rule is @namespace and the rule-list has more than just @import at-rules and/or @namespace at-rules, the method aborts with an InvalidStateError. Examples Inserting a new rule This snippet pushes a new rule onto the top of my stylesheet. myStyle.insertRule('#blanc { color: white }', 0); Function to add a stylesheet rule /** * Add a stylesheet rule to the document (it may be better practice * to dynamically change classes, so style information can be kept in * genuine stylesheets and avoid adding extra elements to the DOM). * Note that an array is needed for declarations and rules since ECMAScript does * not guarantee a predictable object iteration order, and since CSS is * order-dependent. * @param {Array} rules Accepts an array of JSON-encoded decl...
...dependent. * @param {Array} rules Accepts an array of JSON-encoded declarations * @example addStylesheetRules([ ['h2', // Also accepts a second argument as an array of arrays instead ['color', 'red'], ['background-color', 'green', true] // 'true' for !important rules ], ['.myClass', ['background-color', 'yellow'] ] ]); */ function addStylesheetRules (rules) { var styleEl = document.createElement('style'); // Append <style> element to <head> document.head.appendChild(styleEl); // Grab style element's sheet var styleSheet = styleEl.sheet; for (var i = 0; i < rules.length; i++) { var j = 1, rule = rules[i], selector = rule[0], propStr = ''; // If the second argument of a rule is an array of arrays, correct our variables. if (Arr...
... Obsolete Initial definition ...
... Obsolete Initial definition ...
Drawing text - Web APIs
ntext provides two methods to render text: fillText(text, x, y [, maxWidth]) Fills a given text at the given (x,y) position. Optionally with a maximum width to draw. strokeText(text, x, y [, maxWidth]) Strokes a given text at the given (x,y) position. Optionally with a maximum width to draw. A fillText example The text is filled using the current fillStyle. ...
...draw. A fillText example The text is filled using the current fillStyle. function draw() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.font = '48px serif'; ctx.fillText('Hello world', 10, 50); } <canvas id="canvas" width="300" height="100"></canvas> draw(); A strokeText example The text is filled using the current strokeStyle. function draw() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.font = '48px serif'; ctx.strokeText('Hello world', 10, 50); } <canvas id="canvas" width="300" height="100"></canvas> draw(); Styling text In the examples above we are already making use of the font property to make the text a bit larger than the default size. There are some more properties which let you adjust the way the text gets displa...
...; Playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.font = "48px serif"; ctx.textBaseline = "hanging"; ctx.strokeText("Hello world", 0, 100);</textarea> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var edit = document.getElementById('edit'); var code = textarea.value; function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code;...
... Advanced text measurements In the case you need to obtain more details about the text, the following method allows you to measure it. measureText() Returns a TextMetrics object containing the width, in pixels, that the specified text will be when drawn in the current text style. The following code snippet shows how you can measure a text and get its width. function draw() { var ctx = document.getElementById('canvas').getContext('2d'); var text = ctx.measureText('foo'); // TextMetrics object text.width; // 16; } Gecko-specific notes In Gecko (the rendering engine of Firefox, Firefox OS and other Mozilla based applications), some prefixed APIs were implemented in earlier versions to draw text on a canvas. These are now deprecated and removed, and are no longer guaranteed to work.
CharacterData - Web APIs
" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="331" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">CharacterData</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits properties from its parent, Node, and implements the ChildNode and NonDocumentTypeChildNode interface. CharacterData.data Is a DOMString representing the textual data contained in this object. CharacterData.length Read only Returns an unsigned long representing the size of the string contained in CharacterData.data. NonDocumentTypeChildNode.nextElementSibling Read only Returns the Element immediately following the specified one in its parent's children list, or nu...
...g representing the textual data contained in this object. CharacterData.length Read only Returns an unsigned long representing the size of the string contained in CharacterData.data. NonDocumentTypeChildNode.nextElementSibling Read only 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. NonDocumentTypeChildNode.previousElementSibling Read only Returns the Element immediately prior to the specified one in its parent's children list, or null if the specified element is the first one in the list. Methods Inherits methods from its parent, Node, and implements the ChildNode and NonDocumentTypeChildNode interface. CharacterData.appendData() Appends the given DOMString to the CharacterDat...
... returns, data contains the modified DOMString. CharacterData.substringData() Returns a DOMString containing the part of CharacterData.data of the specified length and starting at the specified offset. Specifications Specification Status Comment DOMThe definition of 'CharacterData' in that specification. ...
...ring. CharacterData.substringData() Returns a DOMString containing the part of CharacterData.data of the specified length and starting at the specified offset. Specifications Specification Status Comment DOMThe definition of 'CharacterData' in that specification. Living Standard Added implemention of the ChildNode and NonDocumentTypeChildNode interface. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'CharacterData' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification. Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'CharacterData' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. D...
ChildNode.replaceWith() - Web APIs
set of Node or DOMString objects. DOMString objects are inserted as equivalent Text nodes. Syntax [Throws, Unscopable] void ChildNode.replaceWith((Node or DOMString)... nodes); Parameters nodes A set of Node or DOMString objects to replace. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. Examples Using replaceWith() var parent = document.createElement("div"); var child = document.createElement("p"); parent.appendChild(child); var span = document.createElement("span"); child.replaceWith(span); console.log(parent.outerHTML); // "<div><span></span></div>" ChildNode.replaceWith() is unscopable The replaceWith() method is not scoped into the with statement. See Symbol.unscopables for more information. with(node) { replaceWith(...
...yfill() { 'use-strict'; // For safari, and IE > 10 var parent = this.parentNode, i = arguments.length, currentNode; if (!parent) return; if (!i) // if there are no arguments parent.removeChild(this); while (i--) { // i-- decrements i and returns the value of i before the decrement currentNode = arguments[i]; if (typeof currentNode !== 'object'){ currentNode = this.ownerDocument.createTextNode(currentNode); } else if (currentNode.parentNode){ currentNode.parentNode.removeChild(currentNode); } // the value of "i" below is after the decrement if (!i) // if currentNode is the first argument (currentNode === arguments[0]) parent.replaceChild(currentNode, this); else // if currentNode isn't the first parent.insertBefore(currentNode, this.
... Living Standard Initial definition. ...
... Living Standard Initial definition. ...
DataTransferItem.webkitGetAsEntry() - Web APIs
presenting 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 empty array. In Chromium-based browsers, the following example will only return a max of 100 entries. ...
...d 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 empty array. In Chromium-based browsers, the following example will only return a max of 100 entries. ...
...ntents (the container parameter). Note that to read all files in a directory, readEntries needs to be called repeatedly until it returns an empty array. In Chromium-based browsers, the following example will only return a max of 100 entries. ...
...ing example will only return a max of 100 entries. ...
Element: cut event - Web APIs
Web › API › Element › cut event
owser's user interface. If the user attempts a cut action on uneditable content, the cut event still fires but the event object contains no data. Bubbles Yes Cancelable Yes Interface ClipboardEvent Event handler property oncut The event's default action is to copy the current selection (if any) to the system clipboard and remove it from the document. A handler for this event can modify the clipboard contents by calling setData(format, data) on the event's ClipboardEvent.clipboardData property, and cancelling the default action using event.preventDefault(). Note though that cancelling the default action will also prevent the document from being updated. So an event handler which wants to emulate the default action for "cut" while modifying ...
...y calling setData(format, data) on the event's ClipboardEvent.clipboardData property, and cancelling the default action using event.preventDefault(). Note though that cancelling the default action will also prevent the document from being updated. So an event handler which wants to emulate the default action for "cut" while modifying the clipboard must also manually remove the selection from the document. The handler cannot read the clipboard data. It's possible to construct and dispatch a synthetic cut event, but this will not affect the system clipboard or the document's contents. Examples Live example HTML <div class="source" contenteditable="true">Try cutting text from this box...</div> <div class="target" contenteditable="true">...and pasting it into this one</div> CSS div.source, d...
...oard or the document's contents. ...
...">Try cutting text from this box...</div> <div class="target" contenteditable="true">...and pasting it into this one</div> CSS div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } JS const source = document.querySelector('div.source'); source.addEventListener('cut', (event) => { const selection = document.getSelection(); event.clipboardData.setData('text/plain', selection.toString().toUpperCase()); selection.deleteFromDocument(); event.preventDefault(); }); Result Specifications Specification Status Clipboard API and events Working Draft ...
Element.getElementsByTagName() - Web APIs
lements with the given tag name. All descendants of the specified element are searched, but not the element itself. The returned list is live, which means it updates itself with the DOM tree automatically. Therefore, there is no need to call Element.getElementsByTagName() with the same element and arguments repeatedly if the DOM changes in between calls. When called on an HTML element in an HTML document, getElementsByTagName lower-cases the argument before searching for it. This is undesirable when trying to match camel-cased SVG elements (such as <linearGradient>) in an HTML document. Instead, use Element.getElementsByTagNameNS(), which preserves the capitalization of the tag name. Element.getElementsByTagName is similar to Document.getElementsByTagName(), except that it only searches for elem...
...f no elements are found, the HTMLCollection is empty. element is the element from where the search starts. Only the element's descendants are included, not the element itself. tagName is the qualified name to look for. The special string "*" represents all elements. For compatibility with XHTML, lower-case should be used. Example // Check the status of each data cell in a table const table = document.getElementById('forecast-table'); const cells = table.getElementsByTagName('td'); for (let cell of cells) { let status = cell.getAttribute('data-status'); if (status === 'open') { // Grab the data } } Specifications Specification Status Comment DOMThe definition of 'Element.getElementsByTagName()' in that specification. Living Standard Changed the retur...
...table.getElementsByTagName('td'); for (let cell of cells) { let status = cell.getAttribute('data-status'); if (status === 'open') { // Grab the data } } Specifications Specification Status Comment DOMThe definition of 'Element.getElementsByTagName()' in that specification. ...
... } } Specifications Specification Status Comment DOMThe definition of 'Element.getElementsByTagName()' in that specification. Living Standard Changed the return value from NodeList to HTMLCollection Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Element.getElementsByTagName()' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Element.getElementsByTagName()' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification Document Object Model (DOM) Level 1 SpecificationThe definition of 'Element.getElementsByTagName()' in that specification. O...
Element.getElementsByTagNameNS() - Web APIs
Syntax elements = element.getElementsByTagNameNS(namespaceURI, localName) elements is a live HTMLCollection of found elements in the order they appear in the tree. element is the element from where the search should start. Note that only the descendants of this element are included in the search, not the node itself. ...
...or (see Element.namespaceURI and Attr.namespaceURI). For example, if you need to look for XHTML elements, use the XHTML namespace URI, http://www.w3.org/1999/xhtml. localName is either the local name of elements to look for or the special value "*", which matches all elements (see Element.localName and Attr.localName). Example // check the alignment on a number of cells in a table in an XHTML document. ...
...aceURI and Attr.namespaceURI). For example, if you need to look for XHTML elements, use the XHTML namespace URI, http://www.w3.org/1999/xhtml. localName is either the local name of elements to look for or the special value "*", which matches all elements (see Element.localName and Attr.localName). Example // check the alignment on a number of cells in a table in an XHTML document. ...
...xhtml", "td"); for (var i = 0; i < cells.length; i++) { var axis = cells[i].getAttribute("axis"); if (axis == "year") { // grab the data } } Specifications Specification Status Comment DOMThe definition of 'Element.getElementsByTagNameNS()' in that specification. Living Standard Changed the return value from NodeList to HTMLCollection. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Element.getElementsByTagNameNS()' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification. Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Element.getElementsByTagNameNS()' in that specification. Obsolete Initial definition ...
Element.matches() - Web APIs
Web › API › Element › matches
ent.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 do not support Element.ma...
...th; 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. ...
...IE9+ support). ...
...IE9+ support). if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.msMatchesSelector || ...
Element.onfullscreenchange - Web APIs
Example This example establishes a fullscreenchange event handler, handleFullscreenChange(). ...
... targetDocument.onfullscreenchange = fullscreenChangeHandler; Value An event handler for the fullscreenchange event, indicating that the element has changed in or out of full-screen mode. Example This example establishes a fullscreenchange event handler, handleFullscreenChange(). This function determines which element it was called on by checking the value of event.target, then compares the document's fullscreenElement value to the element to see if they're the same node. This gives us a value, isFullscreen, which we pass into a function called adjustMyControls(), which we imagine to be a function that makes adjustments to the app's user interface to present itself optimally when it's in full-screen mode versus being displayed in a window. function toggleFullscreen() { let elem = documen...
... us a value, isFullscreen, which we pass into a function called adjustMyControls(), which we imagine to be a function that makes adjustments to the app's user interface to present itself optimally when it's in full-screen mode versus being displayed in a window. ...
... when it's in full-screen mode versus being displayed in a window. function toggleFullscreen() { let elem = document.querySelector("video"); elem.onfullscreenchange = handleFullscreenChange; if (!document.fullscreenElement) { elem.requestFullscreen().then({}).catch(err => { alert(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`); }); } else { document.exitFullscreen(); } } function handleFullscreenChange(event) { let elem = event.target; let isFullscreen = document.fullscreenElement === elem; adjustMyControls(isFullscreen); } Specifications Specification Status Comment Fullscreen APIThe definition of 'onfullscreenchange' in that specification. Living Standard Initial definition. ...
Element: paste event - Web APIs
d a "paste" action through the browser's user interface. Bubbles Yes Cancelable Yes Interface ClipboardEvent Event handler property onpaste If the cursor is in an editable context (for example, in a <textarea> or an element with contenteditable attribute set to true) then the default action is to insert the contents of the clipboard into the document at the cursor position. A handler for this event can access the clipboard contents by calling getData() on the event's clipboardData property. To override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventDefault(), and then insert its desired data manually. It's poss...
...by calling getData() on the event's clipboardData property. To override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventDefault(), and then insert its desired data manually. ...
... affect the document's contents. ...
...adding: .5rem; height: 1rem; background-color: #e9eef1; } JS const target = document.querySelector('div.target'); target.addEventListener('paste', (event) => { let paste = (event.clipboardData || window.clipboardData).getData('text'); paste = paste.toUpperCase(); const selection = window.getSelection(); if (!selection.rangeCount) return false; selection.deleteFromDocument(); selection.getRangeAt(0).insertNode(document.createTextNode(paste)); event.preventDefault(); }); Result Specifications Specification Status Clipboard API and events Working Draft ...
Element.setCapture() - Web APIs
Warning: This interface never had much cross-browser support and you probably looking for element.setPointerCapture instead, from the Pointer Events API. Syntax element.setCapture(retargetToElement); retargetToElement If true, all events are targeted directly to this element; if false, events can also fire at descendants of this element. ...
...the current mouse coordinates are drawn while you mouse around after clicking and holding down on an element. ...
... border: solid black 1px; color: black; padding: 2px; box-shadow: black 2px 2px; } </style> <script type="text/javascript"> function init() { var btn = document.getElementById("myButton"); if (btn.setCapture) { btn.addEventListener("mousedown", mouseDown, false); btn.addEventListener("mouseup", mouseUp, false); } else { document.getElementById("output").innerHTML = "Sorry, there appears to be no setCapture support on this browser"; } } function mouseDown(e) { e.target.setCapture(); e.target.addEventListener("mousemove", mouseMoved, false); } function mouseUp(e) { e.target.removeEventListener("mousemove", mouseMoved, false); } function mouseMoved(e) { var ...
...ntById("output").innerHTML = "Sorry, there appears to be no setCapture support on this browser"; } } function mouseDown(e) { e.target.setCapture(); e.target.addEventListener("mousemove", mouseMoved, false); } function mouseUp(e) { e.target.removeEventListener("mousemove", mouseMoved, false); } function mouseMoved(e) { var output = document.getElementById("output"); output.innerHTML = "Position: " + e.clientX + ", " + e.clientY; } </script> </head> <body onload="init()"> <p>This is an example of how to use mouse capture on elements in Gecko 2.0.</p> <p><a id="myButton" href="#">Test Me</a></p> <div id="output">No events yet</div> </body> </html> View Live Examples Notes The element may not be scrolled completel...
Event.composed - Web APIs
Web › API › Event › composed
t attribute and insert them into the element's shadow DOM as the text content of a <p> element. The only difference between the two is that their shadow roots are attached with their modes set to open and closed respectively. ...
... The composed property returns true beause the click event is always able to propagate across shadow boundaries. You'll notice a difference in the value of compos...
... click on the <open-shadow> element and then the <closed-shadow> element, you'll notice two things. The composed property returns true beause the click event is always able to propagate across shadow boundaries. You'll notice a difference in the value of composedPath for the two elements. ...
...shadow boundaries. You'll notice a difference in the value of composedPath for the two elements. The <open-shadow> element's composed path is this: Array [ p, ShadowRoot, open-shadow, body, html, HTMLDocument https://mdn.github.io/web-components-examples/composed-composed-path/, Window ] Whereas the <closed-shadow> element's composed path is a follows: Array [ closed-shadow, body, html, HTMLDocument https://mdn.github.io/web-components-examples/composed-composed-path/, Window ] In the second case, the event listeners only propagate as far as the <closed-shadow> element itself, but not to the nodes inside the shadow boundary. Specifications Specification Status Comment DOMThe definition of 'composed' in that specification. Living Standard ...
Event.composedPath() - Web APIs
t attribute and insert them into the element's shadow DOM as the text content of a <p> element. The only difference between the two is that their shadow roots are attached with their modes set to open and closed respectively. ...
...First, the composed property returns true beause the click event is always able to propagate across shadow boundaries. Second, you'll notice a difference in the valu...
... the <open-shadow> element and then the <closed-shadow> element, you'll notice two things. First, the composed property returns true beause the click event is always able to propagate across shadow boundaries. Second, you'll notice a difference in the value of composedPath for the two elements. ...
...w boundaries. Second, you'll notice a difference in the value of composedPath for the two elements. The <open-shadow> element's composed path is this: Array [ p, ShadowRoot, open-shadow, body, html, HTMLDocument https://mdn.github.io/web-components-examples/composed-composed-path/, Window ] Whereas the <closed-shadow> element's composed path is a follows: Array [ closed-shadow, body, html, HTMLDocument https://mdn.github.io/web-components-examples/composed-composed-path/, Window ] In the second case, the event listeners only propagate as far as the <closed-shadow> element itself, but not to the nodes inside the shadow boundary. Specifications Specification Status Comment DOMThe definition of 'composedPath()' in that specification. Living Standard ...
EventTarget.removeEventListener() - Web APIs
ons. An EventListener will not be invoked for the event it was registered for after being removed. However, it can be reattached. Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect. Example This example shows how to add a mouseover-based event listener that removes a click-based event listener. ...
...vent it was registered for after being removed. However, it can be reattached. Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect. Example This example shows how to add a mouseover-based event listener that removes a click-based event listener. ...
...be reattached. Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect. Example This example shows how to add a mouseover-based event listener that removes a click-based event listener. ...
... Obsolete Initial definition ...
FileList - Web APIs
Web › API › FileList
bute is true, the FileList may contain multiple files. Using the file list All <input> element nodes have a files attribute of type FileList on them which allows access to the items in this list. For example, if the HTML includes the following file input: <input id="fileItem" type="file"> The following line of code fetches the first file in the node's file list as a File object: var file = document.getElementById('fileItem').files[0]; Method overview File item(index); Properties Attribute Type Description length integer A read-only value indicating the number of files in the list. Methods item() Returns a File object representing the file at the specified index in the file list. File item( index ); Parameters index The z...
... specified index in the file list. File item( index ); Parameters index The zero-based index of the file to retrieve from the list. Return value The File representing the requested file. Example This example iterates over all the files selected by the user using an input element: // fileInput is an HTML input element: <input type="file" id="myfileinput" multiple> var fileInput = document.getElementById("myfileinput"); // files is a FileList object (similar to NodeList) var files = fileInput.files; var file; // loop through files for (var i = 0; i < files.length; i++) { // get item file = files.item(i); //or file = files[i]; alert(file.name); } Here is a complete example. <!DOCTYPE HTML> <html> <head> </head> <body> <!--multiple is set to allow multiple ...
... < files.length; i++) { // get item file = files.item(i); //or file = files[i]; alert(file.name); } Here is a complete example. ...
... Working Draft HTML Living StandardThe definition of 'selected files' in that specification. ...
FileSystemDirectoryReader.readEntries() - Web APIs
presenting 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 empty array. In Chromium-based browsers, the following example will only return a max of 100 entries. ...
...d 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 empty array. In Chromium-based browsers, the following example will only return a max of 100 entries. ...
...ntents (the container parameter). Note that to read all files in a directory, readEntries needs to be called repeatedly until it returns an empty array. In Chromium-based browsers, the following example will only return a max of 100 entries. ...
...ing example will only return a max of 100 entries. ...
Using FormData Objects - Web APIs
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: FormData will only use input fields that use the name attribute. ...
...hat use the name attribute. var formData = new FormData(someFormElement); For example: var formElement = document.querySelector("form"); var request = new XMLHttpRequest(); request.open("POST", "submitform.php"); request.send(new FormData(formElement)); You can also append additional data to the FormData object between retrieving it from a form and sending it, like this: var formElement = document.querySelector("form"); var formData = new FormData(formElement); var request = new XMLHttpRequest(); request.open("POST", "submitform.php"); formData.append("serialnumber", serialNumber++); request.send(formData); This lets you augment the form's data before sending it along, to include additional information that's not necessarily user-editable. Sending files using a FormData object You can a...
...s name="userid" placeholder="email" required size="32" maxlength="64" /><br /> <label>Custom file label:</label> <input type="text" name="filelabel" size="12" maxlength="32" /><br /> <label>File to stash:</label> <input type="file" name="file" required /> <input type="submit" value="Stash the file!" /> </form> <div></div> Then you can send it using code like the following: var form = document.forms.namedItem("fileinfo"); form.addEventListener('submit', function(ev) { var oOutput = document.querySelector("div"), oData = new FormData(form); oData.append("CustomField", "This is some extra data"); var oReq = new XMLHttpRequest(); oReq.open("POST", "stash.php", true); oReq.onload = function(oEvent) { if (oReq.status == 200) { oOutput.innerHTML = "Uploaded!"; ...
...s 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.onanimationcancel - Web APIs
d, or when the animating node is hidden--either directly or because any of its containing nodes are hidden--using CSS. Syntax var animCancelHandler = target.onanimationcancel; target.onanimationcancel = Function Value A Function to be called when an animationcancel event occurs indicating that a CSS animation has begun on the target, where the target object is an HTML element (HTMLElement), document (Document), or window (Window). The function receives as input a single parameter: an AnimationEvent object describing the event which occurred. Example HTML <div class="main"> <div id="box" onanimationcancel="handleCancelEvent(event);"> <div id="text">Box</div> </div> </div> <div class="button" id="toggleBox"> Hide the Box </div> <pre id="log"></pre> CSS :root { --boxwidth: 5...
...ers 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 += msg; if (event) { logBox.innerHTML += " <code>"+ event.animationName + "</code> at time " + event.elapsedTime.toFixed(2) + " seconds."; } logBox.innerHTML += "\n"; }; Then we set up the handleCancelEvent() function, which is called in response to the animationcancel event, as set up in the HTML above. All we do here is lo...
...do here is log information to the console, but you might find other use cases, such as starting a new animation or effect, or terminating some dependent operation. ...
...ent operation. function handleCancelEvent(event) { log("Animation canceled", event); }; Then we add a method to handle toggle display between "flex" and "none" and establish it as the handler for a click event on the "Hide/Show" the Box button: document.getElementById('toggleBox').addEventListener('click', function() { if (box.style.display == "none") { box.style.display = "flex"; document.getElementById("toggleBox").innerHTML = "Hide the box"; } else { box.style.display = "none"; document.getElementById("toggleBox").innerHTML = "Show the box"; } }); Toggling the box to display: none has the effect of aborting its animation. In browsers that support animationcancel, the event is fired and this handler is called. Result Assembled together, you get this: If your br...
GlobalEventHandlers.onanimationiteration - Web APIs
on instructions is completed by executing the last animation step. Syntax var animIterationHandler = target.onanimationiteration; target.onanimationiteration = Function Value A Function to be called when an animationiteration event occurs indicating that a CSS animation has reached the end of an iteration while running on the target, where the target object is an HTML element (HTMLElement), document (Document), or window (Window). The function receives as input a single parameter: an AnimationEvent object describing the event which occurred. Example Let's create an animation which automatically pauses at the end of each iteration, allowing the user to choose whether or not to start the next iteration. Much of this code is the same as in other examples of animation events, so it may look fa...
...ich 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. ...
...op: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 global variables: box, which references the "box" element that we're animating, and iterationCounter, which is initially zero, which indicates how many iterations of the animation have occurred. The onanimationiteration event handler is then set up. It simply sets the box's animation-play-state t...
...ch indicates how many iterations of the animation have occurred. The onanimationiteration event handler is then set up. It simply sets the box's animation-play-state to "paused", then updates the text displayed in the button to indicate that clicking the button will start playing the next iteration of theanimation. Finally, we set up a handler for a click on the button that runs the animation: document.getElementById("play").addEventListener("click", function(event) { box.style.animationPlayState = "running"; iterationCounter++; }, false); This sets the box element's animation-play-state to "running" and increments the iteration counter. That's all there is to it! Result Assembled together, you get this: Each time the box reaches the opposing corner, it stops, with the button reflecti...
GlobalEventHandlers.oninvalid - Web APIs
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. ...
...emonstrates 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. ...
...rs 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. ...
...rror" 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.onsubmit - Web APIs
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. ...
...emonstrates 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. ...
...rs 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. ...
...rror" 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. ...
HTMLElement.offsetLeft - Web APIs
nt.getBoundingClientRect() to get its position). Therefore, a box with the left, top, width and height of offsetLeft, offsetTop, offsetWidth and offsetHeight will not be a bounding box for a span with wrapped text. Syntax left = element.offsetLeft; left is an integer representing the offset to the left in pixels from the closest relatively positioned parent element. Example var colorTable = document.getElementById("t1"); var tOLeft = colorTable.offsetLeft; if (tOLeft > 5) { // large left offset: do something here } This example shows a 'long' sentence that wraps within a div with a blue border, and a red box that one might think should describe the boundaries of the span. <div style="width: 300px; border-color:blue; border-style:solid; border-width:1;"> <span>Short span. </span> ...
...nk should describe the boundaries of the span. <div style="width: 300px; border-color:blue; border-style:solid; border-width:1;"> <span>Short span. ...
... <div style="width: 300px; border-color:blue; border-style:solid; border-width:1;"> <span>Short span. ...
...:1;"> <span>Short span. </span> <span id="longspan">Long span that wraps within this div.</span> </div> <div id="box" style="position: absolute; border-color: red; border-width: 1; border-style: solid; z-index: 10"> </div> <script type="text/javascript"> var box = document.getElementById("box"); var longspan = document.getElementById("longspan"); box.style.left = longspan.offsetLeft + document.body.scrollLeft + "px"; box.style.top = longspan.offsetTop + document.body.scrollTop + "px"; box.style.width = longspan.offsetWidth + "px"; box.style.height = longspan.offsetHeight + "px"; </script> Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'offsetLeft' in that specification. Working Draft ...
HTMLElement: transitioncancel event - Web APIs
SS transition is canceled. See GlobalEventHandlers.ontransitioncancel for more information. ...
...nsitioncancel Examples This code gets an element that has a transition defined and adds a listener to the transitioncancel event: const transition = document.querySelector('.transition'); transition.addEventListener('transitioncancel', () => { console.log('Transition canceled'); }); The same, but using the ontransitioncancel property instead of addEventListener(): const transition = document.querySelector('.transition'); transition.ontransitioncancel = () => { console.log('Transition canceled'); }; Live example In the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition"></div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: tra...
...); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ...
...e'll add some JavaScript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ...
HTMLElement: transitionend event - Web APIs
ault or non-transitioned state. If there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. If the transitioncancel event is fired, the transitionend event will not fire. ...
...ransitioncancel event is fired, the transitionend event will not fire. ...
...); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ...
...e'll add some JavaScript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ...
HTMLElement - Web APIs
HTMLElement.accessKey Is a DOMString representing the access key assigned to the element. HTMLElement.accessKeyLabel Read only Returns a DOMString containing the element's assigned access key. HTMLElement.contentEditable Is a DOMString, where a value of true means the element ...
...ent's style attributes. HTMLOrForeignElement.tabIndex Is a long representing the position of the element in the tabbing order. HTMLElement.title Is a DOMString containing the text that appears in a popup box when mouse is over the element. HTMLElement.translate Is a Boolean representing the translation. Event handlers Most event handler properties, of the form onXYZ, are defined on the DocumentAndElementEventHandlers, GlobalEventHandlers or TouchEventHandlers interfaces and implemented by HTMLElement. In addition, the following handlers are specific to HTMLElement. HTMLElement.oncopy Returns the event handling code for the copy event (bug 280959). HTMLElement.oncut Returns the event handling code for the cut event (bug 280959). HTMLElement.onpaste Returns the event handlin...
...dling code for the touchmove event. TouchEventHandlers.ontouchenter Returns the event handling code for the touchenter event. TouchEventHandlers.ontouchleave Returns the event handling code for the touchleave event. TouchEventHandlers.ontouchcancel Returns the event handling code for the touchcancel event. Methods Inherits methods from its parent, Element, and implements those from DocumentAndElementEventHandlers, ElementCSSInlineStyle, GlobalEventHandlers, HTMLOrForeignElement and TouchEventHandlers. HTMLElement.attachInternals() Attaches an ElementInternals instance to the custom element. HTMLOrForeignElement.blur() Removes keyboard focus from the currently focused element. HTMLElement.click() Sends a mouse click event to the element. HTMLOrForeignElement.focus() Makes...
...ication. Recommendation Added the following properties: dataset, hidden, tabindex, accessKey, accessKeyLabel, draggable, dropzone, contentEditable, isContentEditable, contextMenu, spellcheck, commandType, commandLabel, commandIcon, commandHidden, commandDisabled, commandChecked, style, and all the onXYZ properties. Moved the id and className properties to the Element interface. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 HTML Specification Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLElement' in that specification. Obsolete Initial definition. ...
HTMLFormElement.elements - Web APIs
ependently, you can obtain just the number of form controls using the length property. You can access a particular form control in the returned collection by using either an index or the element's name or id. Prior to HTML 5, the returned object was an HTMLCollection, on which HTMLFormControlsCollection is based. Note: Similarly, you can get a list of all of the forms contained within a given document using the document's forms property. Syntax nodeList = HTMLFormElement.elements Value An HTMLFormControlsCollection containing all non-image controls in the form. This is a live collection; if form controls are added to or removed from the form, this collection will update to reflect the change. The form controls in the returned collection are in the same order in which they appear in the ...
...n excellent way to get at the elements most important when processing forms. Example Quick syntax example In this example, we see how to obtain the list of form controls as well as how to access its members by index and by name or ID. ...
...-name"> <input type="password" name="password"> </form> var inputs = document.getElementById("my-form").elements; var inputByIndex = inputs[0]; var inputByName = inputs["username"]; Accessing form controls This example gets the form's element list, then iterates over the list, looking for <input> elements of type "text" so that some form of processing can be performed on them. ...
...put> elements of type "text" so that some form of processing can be performed on them. var inputs = document.getElementById("my-form").elements; // Iterate over the form controls for (i = 0; i < inputs.length; i++) { if (inputs[i].nodeName === "INPUT" && inputs[i].type === "text") { // Update text input inputs[i].value.toLocaleUpperCase(); } } Disabling form controls var inputs = document.getElementById("my-form").elements; // Iterate over the form controls for (i = 0; i < inputs.length; i++) { // Disable all form controls inputs[i].setAttribute("disabled", ""); } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement.elements' in that specification. Living Standard Document Object Model (...
HTMLImageElement.crossOrigin - Web APIs
mode to use when fetching the image resource. If you don't specify crossOrigin, the image is fetched without CORS (the fetch no-cors mode). Permitted values are: anonymous Requests by the <img> element have their mode set to cors and their credentials mode set to same-origin. ...
... 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. ...
...t, 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. ...
...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", () => container.prepend(image) ); image.addEventListener("error", () => { const errMsg = document.createElement("output"); errMsg.value = `Error loading image at ${url}`; container.append(errMsg); }); image.crossOrigin = "anonymous"; image.alt = ""; image.src = url; } loadImage(imageUrl); HTML <div class="container"> <p>Here's a paragraph. It's a very interesting paragraph. You are captivated by this paragraph. Keep reading this paragraph. Okay, now you can stop read...
HTMLImageElement.currentSrc - Web APIs
le image options using the sizes and/or HTMLImageElement.srcset properties. currentSrc lets you determine which image from the set of provided images was selected by the browser. Example In this example, two different sizes are provided for an image of a clock. One is 200px wide and the other is 400px wide. ...
...ine which image from the set of provided images was selected by the browser. Example In this example, two different sizes are provided for an image of a clock. One is 200px wide and the other is 400px wide. The sizes 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. ...
...cate 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. ...
...50% of the document width if the viewport is under 400px wide; otherwise, the image is drawn at 90% width of the document. HTML <img src="/files/16797/clock-demo-400px.png" alt="Clock" srcset="/files/16864/clock-demo-200px.png 200w, /files/16797/clock-demo-400px.png 400w" sizes="(max-width: 400px) 50%, 90%"> JavaScript var clockImage = document.querySelector("img"); let p = document.createElement("p"); if (!clockImage.currentSrc.endsWith("200px.png")) { p.innerText = "Using the 200px image."; } else { p.innerText = "Using the 400px image!"; } document.body.appendChild(p); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLImageElement.currentSrc' in that specification. Living Standard ...
HTMLLinkElement - Web APIs
This object inherits all of the properties and methods of the HTMLElement interface. ...
...he language code for the linked resource. HTMLLinkElement.media Is a DOMString representing a list of one or more media formats to which the resource applies. HTMLLinkElement.referrerPolicy Is a DOMString that reflects the referrerpolicy HTML attribute indicating which referrer to use. HTMLLinkElement.rel Is a DOMString representing the forward relationship of the linked resource from the document to the resource. HTMLLinkElement.relList Read only Is a DOMTokenList that reflects the rel HTML attribute, as a list of tokens. HTMLLinkElement.sizes Read only Is a DOMSettableTokenList that reflects the sizes HTML attribute, as a list of tokens. LinkStyle.sheet Read only Returns the StyleSheet object associated with the given element, or null if there is none. HTMLLinkElement.type Is ...
...ociated with the given element, or null if there is none. HTMLLinkElement.type Is a DOMString representing the MIME type of the linked resource. Obsolete properties HTMLLinkElement.charset Is a DOMString representing the character encoding for the target resource. HTMLLinkElement.rev Is a DOMString representing the reverse relationship of the linked resource from the resource to the document. Note: Currently the W3C HTML 5.2 spec states that rev is no longer obsolete, whereas the WHATWG living standard still has it labeled obsolete. Until this discrepancy is resolved, you should still assume it is obsolete. HTMLLinkElement.target Is a DOMString representing the name of the target frame to which the resource applies. Methods No specific method; inherits methods from its pare...
...s the following properties: crossOrigin, referrerPolicy, and as. HTML 5.1The definition of 'HTMLLinkElement' in that specification. Recommendation HTML5The definition of 'HTMLLinkElement' in that specification. Recommendation The following properties are now obsolete: charset, rev, and shape. The following properties have been added: relList, and sizes. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLLinkElement' in that specification. Obsolete Added a second inheritence, the LinkStyle interface. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLLinkElement' in that specification. Obsolete Initial definition. ...
HTMLMediaElement.srcObject - Web APIs
rsions of the Media Source specification required using createObjectURL() to create an object URL then setting src to that URL. Now you can just set srcObject to the MediaStream directly. Examples Basic example In this example, a MediaStream from a camera is assigned to a newly-created <video> element. ...
...ic example In this example, a MediaStream from a camera is assigned to a newly-created <video> element. const mediaStream = await navigator.mediaDevices.getUserMedia({video: true}); const video = document.createElement('video'); video.srcObject = mediaStream; In this example, a new MediaSource is assigned to a newly-created <video> element. const mediaSource = new MediaSource(); const video = document.createElement('video'); video.srcObject = mediaSource; Supporting fallback to the src property The examples below support older browser versions that require you to create an object URL and assign it to src if srcObject isn't supported. First, a MediaStream from a camera is assigned to a newly-created <video> element, with fallback for older browsers. const mediaStream = await navigator.media...
...rce; Supporting fallback to the src property The examples below support older browser versions that require you to create an object URL and assign it to src if srcObject isn't supported. First, a MediaStream from a camera is assigned to a newly-created <video> element, with fallback for older browsers. const mediaStream = await navigator.mediaDevices.getUserMedia({video: true}); const video = document.createElement('video'); if ('srcObject' in video) { video.srcObject = mediaStream; } else { // Avoid using this in new browsers, as it is going away. video.src = URL.createObjectURL(mediaStream); } Second, a new MediaSource is assigned to a newly-created <video> element, with fallback for older browsers and browsers that don't yet support assignment of MediaSource directly. const mediaSo...
... in video) { video.srcObject = mediaStream; } else { // Avoid using this in new browsers, as it is going away. video.src = URL.createObjectURL(mediaStream); } Second, a new MediaSource is assigned to a newly-created <video> element, with fallback for older browsers and browsers that don't yet support assignment of MediaSource directly. ...
HTMLScriptElement.referrerPolicy - Web APIs
r will be omitted entirely. No referrer information is sent along with requests. no-referrer-when-downgrade (default) This is the user agent's default behavior if no policy is specified. The URL is sent as a referrer when the protocol security level stays the same (e.g.HTTP->HTTP, HTTPS->HTTPS), but isn't sent to a less secure destination (e.g. HTTPS->HTTP). origin Only send the origin of the document as the referrer in all cases. The document https://example.com/page.html will send the referrer https://example.com/. origin-when-cross-origin Send a full URL when performing a same-origin request, but only send the origin of the document for other cases. same-origin A referrer will be sent for same-site origins, but cross-origin requests will contain no referrer information. strict-origin ...
...HTTPS->HTTPS), but don't send it to a less secure destination (e.g. HTTPS->HTTP). strict-origin-when-cross-origin Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (e.g. HTTPS->HTTPS), and send no header to a less secure destination (e.g. ...
...This policy will leak origins and paths from TLS-protected resources to insecure origins. Carefully consider the impact of this setting. Note: An empty string value ("") is both the default value, and a fallback value if referrerpolicy is not supported. If referrerpolicy is not explicitly specified on the <script> element, it will adopt a higher-level referrer policy, i.e. ...
...) is both the default value, and a fallback value if referrerpolicy is not supported. If referrerpolicy is not explicitly specified on the <script> element, it will adopt a higher-level referrer policy, i.e. one set on the whole document or domain. If a higher-level policy is not available, the empty string is treated as being equivalent to no-referrer-when-downgrade. Examples var scriptElem = document.createElement("script"); scriptElem.src = "/"; scriptElem.referrerPolicy = "unsafe-url"; document.body.appendChild(script); Specifications Specification Status Comment Referrer PolicyThe definition of 'referrerpolicy attribute' in that specification. Candidate Recommendation Added the referrerPolicy attribute. HTML Living StandardThe definition of 'HT...
HTMLSelectElement - Web APIs
; pointer-events: all;} Properties This interface inherits the properties of HTMLElement, and of Element and Node. HTMLSelectElement.autofocus A Boolean reflecting the autofocus HTML attribute, which indicates whether the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form-associated element in a document can have this attribute specified. HTMLSelectElement.disabled A Boolean reflecting the disabled HTML attribute, which indicates whether the control is disabled. If it is disabled, it does not accept clicks. HTMLSelectElement.formRead only An HTMLFormElement referencing the form that this element is associated with. If the element is not associated with of a <form> element, then it returns n...
...gning 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. Example Get information about the selected option /* assuming we have the following HTML <select id='s'> <option>First</option> <option selected>Second</option> <option>Third</option> </select> */ var select = document.getElementById('s'); // return the index of the selected option console.log(select.selectedIndex); // 1 // return the value of the selected option console.log(select.options[select.selectedIndex].value) // Second A better way to track changes to the user's selection is to watch for the change event to occur on the <select>. This will tell you when the value changes, and you can then update an...
...lected option console.log(select.selectedIndex); // 1 // return the value of the selected option console.log(select.options[select.selectedIndex].value) // Second A better way to track changes to the user's selection is to watch for the change event to occur on the <select>. This will tell you when the value changes, and you can then update anything you need to. See the example provided in the documentation for the change event for details. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLSelectElement' in that specification. Living Standard Since the latest snapshot, HTML5, it adds the autocomplete property and the reportValidity() method. HTML5The definition of 'HTMLSelectElement' in that specification. Reco...
...ectElement' in that specification. Recommendation Is a snapshot of HTML Living Standard. It adds the autofocus, form, required, labels, selectedOptions, willValidate, validity and validationMessage properties. The tabindex property and the blur() and focus() methods have been moved to HTMLElement. The methods item(), namedItem(), checkValidity() and setCustomValidity(). Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLSelectElement' in that specification. Obsolete options now returns an HTMLOptionsCollection. length now returns an unsigned long. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLSelectElement' in that specification. Obsolete Initial definition ...
HTMLTableRowElement.insertCell() - Web APIs
You can not use insertCell() to create a new <th> element though. ...
...ption will result. If index is omitted it defaults to -1. Return value newCell is an HTMLTableCellElement that references the new cell. Example This example uses 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(). HTML <table id="my-table"> <tr><td>Row 1</td></tr> <tr><td>Row 2</td></tr> <tr><td>Row 3</td></tr> </table> JavaScript function addRow(tableID) { // Get a reference to the table let tableRef = document.getElementById(tableID); // Insert a row at the end of the table let newRow = tableRef.insertRow(-1); // Insert a cell in the row at i...
... Living Standard Document Object Model (DOM) Level 2 HTML SpecificationThe def...
... Obsolete Initial definition ...
HTML Drag and Drop API - Web APIs
Each d...
...fer object) also has methods to manage drag data. The setData() method is used to add an item to the drag data, as shown in the following example. function dragstart_handler(ev) { // Add different types of drag data ev.dataTransfer.setData("text/plain", ev.target.innerText); ev.dataTransfer.setData("text/html", ev.target.outerHTML); ev.dataTransfer.setData("text/uri-list", ev.target.ownerDocument.location.href); } For a list of common data types used in drag-and-drop (such as text, HTML, links, and files), see Recommended Drag Types. For more information about drag data, see Drag Data. Define the drag image By default, the browser supplies an image that appears beside the pointer during a drag operation. However, an application may define a custom image with the setDragImage() met...
...ample shows how to use those attributes, and includes basic event handlers for each attribute. <script> function dragover_handler(ev) { ev.preventDefault(); ev.dataTransfer.dropEffect = "move"; } function drop_handler(ev) { ev.preventDefault(); // Get the id of the target and add the moved element to the target's DOM const data = ev.dataTransfer.getData("text/plain"); ev.target.appendChild(document.getElementById(data)); } </script> <p id="target" ondrop="drop_handler(event)" ondragover="dragover_handler(event)">Drop Zone</p> Note that each handler calls preventDefault() to prevent additional event processing for this event (such as touch events or pointer events). For more information, see: Specifying Drop Targets Handle the drop effect The handler for the drop event is free to p...
...dataTransfer.setData("application/my-app", ev.target.id); ev.dataTransfer.dropEffect = "move"; } function dragover_handler(ev) { ev.preventDefault(); ev.dataTransfer.dropEffect = "move" } function drop_handler(ev) { ev.preventDefault(); // Get the id of the target and add the moved element to the target's DOM const data = ev.dataTransfer.getData("application/my-app"); ev.target.appendChild(document.getElementById(data)); } </script> <p id="p1" draggable="true" ondragstart="dragstart_handler(event)">This element is draggable.</p> <div id="target" ondrop="drop_handler(event)" ondragover="dragover_handler(event)">Drop Zone</div> For more information, see: Performing a Drop Drag end At the end of a drag operation, the dragend event fires at the source element -- the element that was th...
KeyboardEvent.initKeyEvent() - 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 KeyboardEvent.initKeyEvent() method is used to initialize the value of an event created using document.createEvent("KeyboardEvent"). Events initialized in this way must have been created with the document.createEvent("KeyboardEvent") method. initKeyEvent() must be called to set the event before it is dispatched. Do not use this method anymore, use the KeyboardEvent() constructor instead. This method is based on early drafts of Document Object Model (DOM) Level 2 Events Specification and is imple...
...Favor the modern constructor structure as the only cross-browser way of building events. ...
...is true if the virtual key to be generated is a combination of keys containing the Meta key. keyCodeArg Is a unsigned long representing the virtual key code value of the key which was depressed, otherwise 0. See KeyboardEvent.keyCode for the list of key codes. charCodeArg Is a unsigned long representingthe Unicode character associated with the depressed key otherwise 0. Example var event = document.createEvent('KeyboardEvent'); // create a key event // define the event event.initKeyEvent("keypress", // typeArg, true, // canBubbleArg, true, // cancelableArg, null, // viewArg, Specifies UIEvent.view. This value may be null. false, // ctrlKeyArg, ...
... null, // viewArg, Specifies UIEvent.view. This value may be null. false, // ctrlKeyArg, false, // altKeyArg, false, // shiftKeyArg, false, // metaKeyArg, 9, // keyCodeArg, 0); // charCodeArg); document.getElementById('blah').dispatchEvent(event); Specification This implementation of keyboard events is based on the key events spec in the early versions of DOM 2 Events, later removed from that spec. The initKeyEvent is the current Gecko equivalent of the DOM Level 3 Events (initially drafted and also deprecated in favor of KeyboardEvent() Keyboard.initKeyboardEvent() method with the following...
MediaElementAudioSourceNode - Web APIs
ge() function is invoked, which calculates the current gain as a ratio of mouse Y position divided by overall window height. You can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. Note: You can also view this example running live, or view the source. ...
...the current gain as a ratio of mouse Y position divided by overall window height. You can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. Note: You can also view this example running live, or view the source. ...
...n divided by overall window height. You can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. Note: You can also view this example running live, or view the source. ...
...eate a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var source = audioCtx.createMediaElementSource(myAudio); // Create a gain node var gainNode = audioCtx.createGain(); // Create variables to store mouse pointer Y coordinate // and HEIGHT of screen var CurY; var HEIGHT = window.innerHeight; // Get new mouse pointer coordinates when mouse is moved // then set new gain value document.onmousemove = updatePage; function updatePage(e) { CurY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); gainNode.gain.value = CurY/HEIGHT; } // connect the AudioBufferSourceNode to the gainNode // and the gainNode to the destination, so we can play the // music and adjust the volume using...
MediaStreamAudioSourceNode - Web APIs
de. Next, we feed this source audio into a low pass BiquadFilterNode (which effectively serves as a bass booster), then a AudioDestinationNode. The range slider below the <video> element controls the amount of gain given to the lowpass filter -- increase the value of the slider to make the audio sound more bass heavy! Note: You can see this example running live, or view the source. ...
...low pass BiquadFilterNode (which effectively serves as a bass booster), then a AudioDestinationNode. The range slider below the <video> element controls the amount of gain given to the lowpass filter -- increase the value of the slider to make the audio sound more bass heavy! Note: You can see this example running live, or view the source. ...
...ves as a bass booster), then a AudioDestinationNode. The range slider below the <video> element controls the amount of gain given to the lowpass filter -- increase the value of the slider to make the audio sound more bass heavy! Note: You can see this example running live, or view the source. ...
...nNode. The range slider below the <video> element controls the amount of gain given to the lowpass filter -- increase the value of the slider to make the audio sound more bass heavy! Note: You can see this example running live, or view the source. ...
MediaStreamTrackAudioSourceNode - Web APIs
de. Next, we feed this source audio into a low pass BiquadFilterNode (which effectively serves as a bass booster), then a AudioDestinationNode. The range slider below the <video> element controls the amount of gain given to the lowpass filter -- increase the value of the slider to make the audio sound more bass heavy! Note: You can see this example running live, or view the source. ...
...low pass BiquadFilterNode (which effectively serves as a bass booster), then a AudioDestinationNode. The range slider below the <video> element controls the amount of gain given to the lowpass filter -- increase the value of the slider to make the audio sound more bass heavy! Note: You can see this example running live, or view the source. ...
...ves as a bass booster), then a AudioDestinationNode. The range slider below the <video> element controls the amount of gain given to the lowpass filter -- increase the value of the slider to make the audio sound more bass heavy! Note: You can see this example running live, or view the source. ...
...nNode. The range slider below the <video> element controls the amount of gain given to the lowpass filter -- increase the value of the slider to make the audio sound more bass heavy! Note: You can see this example running live, or view the source. ...
MediaStream Recording API - Web APIs
s of the recorded media will not necessarily be individually playable. The media needs to be reassembled before playback. If anything goes wrong during recording, an error event is sent to the MediaRecorder. You can listen for error events by setting up a onerror event handler. Example here, we use an HTML Canvas as source of the MediaStream, and stop recording after 9 seconds. var canvas = document.querySelector("canvas"); // Optional frames per second argument. var stream = canvas.captureStream(25); var recordedChunks = []; console.log(stream); var options = { mimeType: "video/webm; codecs=vp9" }; mediaRecorder = new MediaRecorder(stream, options); mediaRecorder.ondataavailable = handleDataAvailable; mediaRecorder.start(); function handleDataAvailable(event) { console.log("data-avail...
... handleDataAvailable; mediaRecorder.start(); function handleDataAvailable(event) { console.log("data-available"); if (event.data.size > 0) { recordedChunks.push(event.data); console.log(recordedChunks); download(); } else { // ... ...
...rder.start(); function handleDataAvailable(event) { console.log("data-available"); if (event.data.size > 0) { recordedChunks.push(event.data); console.log(recordedChunks); download(); } else { // ... ...
... the list based on desired criteria. In this code snippet, enumerateDevices() is used to examine the available input devices, locate those which are audio input devices, and create <option> elements that are then added to a <select> element representing an input source picker. navigator.mediaDevices.enumerateDevices() .then(function(devices) { devices.forEach(function(device) { let menu = document.getElementById("inputdevices"); if (device.kind == "audioinput") { let item = document.createElement("option"); item.innerHTML = device.label; item.value = device.deviceId; menu.appendChild(item); } }); }); Code similar to this can be used to let the user restrict the set of devices they wish to use. For more information To learn more about using the MediaStre...
MouseEvent.button - Web APIs
Web › API › MouseEvent › button
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. ...
...ng 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. ...
... Obsolete Initial definition. ...
...break; case 2: log.textContent = 'Right button clicked.'; break; default: log.textContent = `Unknown button code: ${e.button}`; } } } Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.button' in that specification. Obsolete Compared to Document Object Model (DOM) Level 2 Events Specification, the return value can be negative. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'MouseEvent.button' in that specification. Obsolete Initial definition. ...
MouseEvent.relatedTarget - Web APIs
the red and blue boxes. ...
...event.relatedTarget.id : "unknown"; mouseoutLog.innerText = `\n...
...event.relatedTarget.id : "unknown"; mouseoutLog.innerText = `\nfrom ${event.target.id} into ${related} ${mou...
...innerText}`; } function overListener(event) { let related = event.relatedTarget ? event.relatedTarget.id : "unknown"; log.innerText = `\ninto ${event.target.id} from ${related} ${mouseoutLog.innerText}`; } Result Specifications Specification Status Comment UI EventsThe definition of 'MouseEvent.relatedTarget' in that specification. Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.relatedTarget' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Events Specification. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'MouseEvent.altkey' in that specification. Obsolete Initial definition. ...
MouseEvent.screenX - Web APIs
screenX Return value A double floating point value. Early versions of the spec defined this as an integer referring to the number of pixels. See the "Browser compatibility" section for details. Example This example displays your mouse's coordinates whenever you trigger the mousemove event. ...
...ng point value. Early versions of the spec defined this as an integer referring to the number of pixels. See the "Browser compatibility" section for details. Example This example displays your mouse's coordinates whenever you trigger the mousemove event. ...
...vent. ...
...es: function checkClickMap(e) { if (e.screenX < 50) doRedButton(); if (50 <= e.screenX && e.screenX < 100) doYellowButton(); if (e.screenX >= 100) doRedButton(); } Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'screenX' in that specification. Working Draft Redefines MouseEvent from long to double. Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.screenX' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Events Specification. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'MouseEvent.sceenX' in that specification. Obsolete Initial definition ...
Node.firstChild - Web APIs
Web › API › Node › firstChild
Syntax var childNode = node.firstChild; Example This example demonstrates the use of firstChild and how whitespace nodes might interfere with using this property. ...
...he node's first child in the tree, or null if the node has no children. If the node is a Document, it returns the first node in the list of its direct children. Syntax var childNode = node.firstChild; Example This example demonstrates the use of firstChild and how whitespace nodes might interfere with using this property. <p id="para-01"> <span>First span</span> </p> <script> var p01 = document.getElementById('para-01'); console.log(p01.firstChild.nodeName); </script> In the above, the console will show '#text' because a text node is inserted to maintain the whitespace between the end of the opening <p> and <span> tags. Any whitespace will create a #text node, from a single space to multiple spaces, returns, tabs, and so on. Another #text node is inserted between the closing </span>...
...<span> tags. Any whitespace will create a #text node, from a single space to multiple spaces, returns, tabs, and so on. Another #text node is inserted between the closing </span> and </p>tags. If this whitespace is removed from the source, the #text nodes are not inserted and the span element becomes the paragraph's first child. <p id="para-01"><span>First span</span></p> <script> var p01 = document.getElementById('para-01'); console.log(p01.firstChild.nodeName); </script> Now the console will show 'SPAN'. To avoid the issue with node.firstChild returning #text or #comment nodes, ParentNode.firstElementChild can be used to return only the first element node. However, node.firstElementChild requires a shim for Internet Explorer 9 and earlier. Specifications Specification St...
...e with node.firstChild returning #text or #comment nodes, ParentNode.firstElementChild can be used to return only the first element node. However, node.firstElementChild requires a shim for Internet Explorer 9 and earlier. Specifications Specification Status Comment DOMThe definition of 'Node.firstChild' in that specification. Living Standard No change Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.firstChild' in that specification. Obsolete No change Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Node.firstChild' in that specification. Obsolete No change Document Object Model (DOM) Level 1 SpecificationThe definition of 'Node.firstChild' in that specification. Obs...
Node.localName - Web APIs
Web › API › Node › localName
nd Attr interfaces. ...
...Name name is the local name as a string (see Notes below for details) Example (Must be served with XML content type, such as text/xml or application/xhtml+xml.) <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <script type="application/javascript"><![CDATA[ function test() { var text = document.getElementById('text'); var circle = document.getElementById('circle'); text.value = "<svg:circle> has:\n" + "localName = '" + circle.localName + "'\n" + "namespaceURI = '" + circle.namespaceURI + "'"; } ]]></script> </head> <body onload="test()"> <svg:svg version="1.1" width="100px" height="100px" viewBox="0 0 100 100"> <svg:circle cx="50" cy="50" r="30" style="fill:#aaa" id="circle"/...
... width="100px" height="100px" viewBox="0 0 100 100"> <svg:circle cx="50" cy="50" r="30" style="fill:#aaa" id="circle"/> </svg:svg> <textarea id="text" rows="4" cols="55"/> </body> </html> Notes The local name of a node is that part of the node'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 documents. For example, in the qualified name ecomm:partners, partners is the local name and ecomm is the prefix: <ecomm:business id="soda_shop" type="brick_n_mortar" xmlns:ecomm="http://example.com/ecomm"> <ecomm:partners> <ecomm:partner id="1001">Tony's Syrup Warehouse </ecomm:partner> </ecomm:partners> </ecomm:business> Note: In Gecko 1.9.2 and earlier, the property returns the upper-ca...
...erty returns in the case of the internal DOM storage, which is lower case for both HTML elements in HTML DOMs and XHTML elements in XML DOMs. The tagName property continues to return in the upper case for HTML elements in HTML DOMs. For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE localName is always null. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.localName' in that specification. Obsolete Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Node.localName' in that specification. Obsolete Initial definition ...
Node.namespaceURI - Web APIs
Web › API › Node › namespaceURI
In DOM4 this API was moved from Node to the Element and Attr interfaces. Syntax namespace = node.namespaceURI Example In this snippet, a node is being examined for its Node.localName and its namespaceURI. If the namespaceURI returns the XUL namespace and the localName returns "browser", then the node is understood to be a XUL <browser/>. ...
... node.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { // this is a XUL browser } Notes This is not a computed value that is the result of a namespace lookup based on an examination of the namespace declarations in scope. The namespace URI of a node is frozen at the node creation time. In Firefox 3.5 and earlier, the namespace URI for HTML elements in HTML documents is null. In later versions, in compliance with HTML5, it is https://www.w3.org/1999/xhtml as in XHTML. For nodes of any Node.nodeType other than ELEMENT_NODE and ATTRIBUTE_NODE the value of namespaceURI is always null. You can create an element with the specified namespaceURI using the DOM Level 2 method Document.createElementNS and attributes with the method Element.setAttributeNS. Per the ...
...nt it is attached to. If an attribute is not explicitly given a namespace, it has no namespace. The DOM does not handle or enforce namespace validation per se. It is up to the DOM application to do any validation necessary. Note too that the namespace prefix, once it is associated with a particular node, cannot be changed. ...
...ication to do any validation necessary. Note too that the namespace prefix, once it is associated with a particular node, cannot be changed. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.namespaceURI' in that specification. Obsolete Specifies the behavior when it's set to null. Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'DOM Level 2 Core: XML Namespaces' in that specification. Obsolete Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Node.namespaceURI' in that specification. Obsolete Initial definition ...
NodeFilter.acceptNode() - Web APIs
sn't provide any object implementing this method. It is the user who is expected to write an object implementing the NodeFilter interface, tailoring the acceptNode() method to its needs, and using it with some TreeWalker or NodeIterator objects. Syntax result = nodeFilter.acceptNode(node) Parameters node Is a Node being the object to check against the filter. ...
...the user who is expected to write an object implementing the NodeFilter interface, tailoring the acceptNode() method to its needs, and using it with some TreeWalker or NodeIterator objects. Syntax result = nodeFilter.acceptNode(node) Parameters node Is a Node being the object to check against the filter. ...
... Obsolete Initial definition. ...
... Obsolete Initial definition. ...
NodeFilter - Web APIs
Note: The browser doesn't provide any object implementing this interface. It is the user who is expected to write one, tailoring the acceptNode() method to its needs, and using it with some TreeWalker or NodeIterator objects. Properties This interface neither implements nor inherits any properties. Methods This interface doesn't inherit any methods. ...
... are also rejected. For NodeIterator, this flag is synonymous with FILTER_SKIP. FILTER_SKIP Value to be returned by NodeFilter.acceptNode() for nodes to be skipped by the NodeIterator or TreeWalker object. The children of skipped nodes are still considered. This is treated as "skip this node but not its children". ...
...synonymous with FILTER_SKIP. FILTER_SKIP Value to be returned by NodeFilter.acceptNode() for nodes to be skipped by the NodeIterator or TreeWalker object. The children of skipped nodes are still considered. This is treated as "skip this node but not its children". ...
... Obsolete Initial definition. ...
NodeList.entries() - Web APIs
Web › API › NodeList › entries
The NodeList.entries() method returns an iterator allowing to go through all key/value pairs contained in this object. The values are Node objects. Syntax list.entries(); Return value Returns an iterator. ...
... The NodeList.entries() method returns an iterator allowing to go through all key/value pairs contained in this object. The values are Node objects. Syntax list.entries(); Return value Returns an iterator. ...
... The NodeList.entries() method returns an iterator allowing to go through all key/value pairs contained in this object. The values are Node objects. Syntax list.entries(); Return value Returns an iterator. ...
... The NodeList.entries() method returns an iterator allowing to go through all key/value pairs contained in this object. The values are Node objects. Syntax list.entries(); Return value Returns an iterator. ...
NodeList.prototype.forEach() - Web APIs
Web › API › NodeList › forEach
ment of someNodeList. It accepts 3 parameters: currentValue The current element being processed in someNodeList. currentIndex Optional The index of the currentValue being processed in someNodeList. listObj Optional The someNodeList that forEach() is being applied to. thisArg Optional Value to use as this when executing callback. Return value undefined. ...
...ers: currentValue The current element being processed in someNodeList. currentIndex Optional The index of the currentValue being processed in someNodeList. listObj Optional The someNodeList that forEach() is being applied to. thisArg Optional Value to use as this when executing callback. Return value undefined. ...
...ment being processed in someNodeList. currentIndex Optional The index of the currentValue being processed in someNodeList. listObj Optional The someNodeList that forEach() is being applied to. thisArg Optional Value to use as this when executing callback. Return value undefined. ...
...rentIndex Optional The index of the currentValue being processed in someNodeList. listObj Optional The someNodeList that forEach() is being applied to. thisArg Optional Value to use as this when executing callback. Return value undefined. ...
NodeList.keys() - Web APIs
Web › API › NodeList › keys
The NodeList.keys() method returns an iterator allowing to go through all keys contained in this object. The keys are unsigned integer. Syntax nodeList.keys(); Return value Returns an iterator. ...
... The NodeList.keys() method returns an iterator allowing to go through all keys contained in this object. The keys are unsigned integer. Syntax nodeList.keys(); Return value Returns an iterator. ...
... The NodeList.keys() method returns an iterator allowing to go through all keys contained in this object. The keys are unsigned integer. Syntax nodeList.keys(); Return value Returns an iterator. ...
... The NodeList.keys() method returns an iterator allowing to go through all keys contained in this object. The keys are unsigned integer. Syntax nodeList.keys(); Return value Returns an iterator. ...
NodeList.values() - Web APIs
Web › API › NodeList › values
The NodeList.values() method returns an iterator allowing to go through all values contained in this object. The values are Node objects. Syntax nodeList.values(); Return value Returns an iterator. ...
... The NodeList.values() method returns an iterator allowing to go through all values contained in this object. The values are Node objects. Syntax nodeList.values(); Return value Returns an iterator. ...
... The NodeList.values() method returns an iterator allowing to go through all values contained in this object. The values are Node objects. Syntax nodeList.values(); Return value Returns an iterator. ...
... The NodeList.values() method returns an iterator allowing to go through all values contained in this object. The values are Node objects. Syntax nodeList.values(); Return value Returns an iterator. ...
PerformanceNavigationTiming.unloadEventEnd - Web APIs
Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
....getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM complete = " + p.domComplete); console.log("DOM interactive = " + p.interactive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Specifications Specification Status Comment Navigation Timing Level 2The...
PerformanceNavigationTiming.unloadEventStart - Web APIs
Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
....getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM complete = " + p.domComplete); console.log("DOM interactive = " + p.interactive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Specifications Specification Status Comment Navigation Timing Level 2The...
Multi-touch interaction - Web APIs
tes, applications and provide a good user experience regardless of the user's hardware. Pointer events have many similarities to mouse events but they support multiple simultaneous pointers such as multiple fingers on a touch screen. This additional feature can be used to provide richer user interaction models but at the cost of additional complexity in the multi-touch interaction handling. This document demonstrates via example code, using pointer events with different multi-touch interactions. A live version of this application is available on Github. The source code is available on Github; pull requests and bug reports are welcome. Example This example demonstrates using pointer events' various event types (pointerdown, pointermove, pointerup pointercancel, etc.) for different multi-touch i...
...he3 = new Array(); Register event handlers Event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup. The handler for pointerup is used for the pointercancel, pointerout and pointerleave events, since these four events have the same semantics in this application. function set_handlers(name) { // Install event handlers for the given element var el=document.getElementById(name); el.onpointerdown = pointerdown_handler; el.onpointermove = pointermove_handler; // Use same handler for pointer{up,cancel,out,leave} events since // the semantics for these events - in this app - are the same. el.onpointerup = pointerup_handler; el.onpointercancel = pointerup_handler; el.onpointerout = pointerup_handler; el.onpointerleave = pointerup_handler; } fun...
...default: // Three or more simultaneous touches ev.target.style.background = "lightblue"; } } Event logging These functions are used send to event activity to the application window (to support debugging and learning about the event flow). ...
...ts flag var logEvents = false; function enableLog(ev) { logEvents = logEvents ? ...
RTCIceTransport: selectedcandidatepairchange event - Web APIs
No Interface Event Event handler property onselectedcandidatepairchange Examples This example creates an event handler for selectedcandidatepairchange that updates a display providing the user information about the progress of the ICE negotiation for an RTCPeerConnection called pc. ...
... onselectedcandidatepairchange Examples This example creates an event handler for selectedcandidatepairchange that updates a display providing the user information about the progress of the ICE negotiation for an RTCPeerConnection called pc. ...
...tepairchange", ev => { let pair = iceTransport.getSelectedCandidatePair(); localProtoElem.innerText = pair.local.protocol.toUpperCase(); remoteProtoElem.innerText = pair.remote.protocol.toUpperCase(); }, false) This can also be done by setting the onselectedcandidatepairchange event handler property directly. ...
...datePair(); localProtoElem.innerText = pair.local.protocol.toUpperCase(); remoteProtoElem.innerText = pair.remote.protocol.toUpperCase(); }, false) This can also be done by setting the onselectedcandidatepairchange event handler property directly. ...
Range.cloneContents() - Web APIs
Event Listeners added using DOM Events are not copied during cloning. HTML attribute events are duplicated as they are for the DOM Core cloneNode method. HTML id attributes are also cloned, which can lead to an invalid document through cloning. Partially selected nodes include the parent tags necessary to make the document fragment valid. ...
...eturns a DocumentFragment copying the objects of type Node included in the Range. Event Listeners added using DOM Events are not copied during cloning. HTML attribute events are duplicated as they are for the DOM Core cloneNode method. HTML id attributes are also cloned, which can lead to an invalid document through cloning. Partially selected nodes include the parent tags necessary to make the document fragment valid. ...
...the objects of type Node included in the Range. Event Listeners added using DOM Events are not copied during cloning. HTML attribute events are duplicated as they are for the DOM Core cloneNode method. HTML id attributes are also cloned, which can lead to an invalid document through cloning. Partially selected nodes include the parent tags necessary to make the document fragment valid. Syntax documentFragment = range.cloneContents(); Example range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); documentFragment = range.cloneContents(); document.body.appendChild(documentFragment); Specifications Specification Status Comment DOMThe definition of 'Range.cloneContents()' in that specification. Living Standard No change. ...
... Obsolete Initial specification. ...
Range.getBoundingClientRect() - Web APIs
<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>. ...
...ositions 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>. ...
...he range's content <b>starts here</b> and continues on until it <b>ends here</b>. ...
...ins everything selected in the range.</p> CSS #highlight { background: yellow; position: absolute; z-index: -1; } p { width: 200px; } JavaScript const range = document.createRange(); range.setStartBefore(document.getElementsByTagName('b').item(0), 0); range.setEndAfter(document.getElementsByTagName('b').item(1), 0); const clientRect = range.getBoundingClientRect(); const highlight = document.getElementById('highlight'); highlight.style.left = `${clientRect.x}px`; highlight.style.top = `${clientRect.y}px`; highlight.style.width = `${clientRect.width}px`; highlight.style.height = `${clientRect.height}px`; Result Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'Range.getBoundingClientRect()' in that specificat...
Selection.containsNode() - Web APIs
ent Optional When true, containsNode() returns true when a part of the node is part of the selection. When false, containsNode() only returns true when the entire node is part of the selection. If not specified, the default value false is used. Example Check for selection This snippet checks whether anything inside the body element is selected. ...
...election().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. ...
... Find the hidden word In this example, a message appears when you select the secret word. It uses addEventListener() to check for selectionchange events. ...
...u select the secret word. It uses addEventListener() to check for selectionchange events. HTML <p>Can you find the secret word?</p> <p>Hmm, where <span id="secret" style="color:transparent">SECRET</span> could it be?</p> <p id="win" hidden>You found it!</p> JavaScript const secret = document.getElementById('secret'); const win = document.getElementById('win'); // Listen for selection changes document.addEventListener('selectionchange', () => { const selection = window.getSelection(); const found = selection.containsNode(secret); win.toggleAttribute('hidden', !found); }); Result Specifications Specification Status Comment Selection APIThe definition of 'Selection.containsNode()' in that specification. Working Draft Current ...
Using Service Workers - Web APIs
When the oninstall handler completes, the service worker is considered installed. Next is activation. When the service worker is installed, it then receives an activate event. The primary use of onactivate is for cleanup of resources used in previous versions of a Service worker script. The Service worker will now control pages, but only those opened after the register() is successful. i.e. a document starts life with or without a Service worker and maintains that for its lifetime. So documents will have to be reloaded to actually be controlled. The below graphic shows a summary of the available service worker events: Promises Promises are a great mechanism for running async operations, with success dependant on one another. This is central to the way service workers work. Promises ...
...cted -- in this case return a 200 OK status or not -- and then call resolve on success, or reject on failure. The rest of the contents of this function is fairly standard XHR stuff, so we won't worry about that for now. ...
...ce workers. Note: IndexedDB can be used inside a service worker for data storage if you require it. Custom responses to requests Now you've got your site assets cached, you need to tell service workers to do something with the cached content. This is easily done with the fetch event. A fetch event fires every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope, and any resources referenced in those documents (for example if index.html makes a cross origin request to embed an image, that still goes through its service worker.) You can attach a fetch event listener to the service worker, then call the respondWith() method on the event to hijack our HTTP responses and update them with your own magic. self.addEventListener('fe...
...ondWith( caches.match(event.request) ); }); caches.match(event.request) allows us to match each resource requested from the network with the equivalent resource available in the cache, if there is a matching one available. The matching is done via url and vary headers, just like with normal HTTP requests. Let's look at a few other options we have when defining our magic (see our Fetch API documentation for more information about Request and Response objects.) The Response() constructor allows you to create a custom response. In this case, we are just returning a simple text string: new Response('Hello from your friendly neighbourhood service worker!'); This more complex Response below shows that you can optionally pass a set of headers in with your response, emulating standa...
SpeechSynthesisUtterance - Web APIs
.onsubmit handler, we stop the form submitting with preventDefault(), use the constructor to create a new utterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the SpeechSynthesis.speak() method. ...
...with preventDefault(), use the constructor to create a new utterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the SpeechSynthesis.speak() method. ...
...e a new utterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the SpeechSynthesis.speak() method. ...
...oice to the voice selected in the <select> element, and start the utterance speaking via the SpeechSynthesis.speak() method. ...
SubtleCrypto.deriveBits() - Web APIs
e key is not a key for the requested derivation algorithm or if the CryptoKey.usages value of that key doesn't contain deriveKey. NotSupported Raised when trying to use an algorithm that is either unknown or isn't suitable for derivation, or if the algorithm requested for the derived key doesn't define a key length. Supported algorithms See the Supported algorithms section of the deriveKey() documentation. Examples Note: You can try the working examples on GitHub. ECDH In this example Alice and Bob each generate an ECDH key pair. We then use Alice's private key and Bob's public key to derive a shared secret. See the complete code on GitHub. async function deriveSharedSecret(privateKey, publicKey) { const sharedSecret = await window.crypto.subtle.deriveBits( { name: "ECDH",...
...y and Bob's public key to derive a shared secret. See the complete code on GitHub. ...
... // Bob could generate the same secret using his private key and Alice's public key. deriveSharedSecret(alicesKeyPair.privateKey, bobsKeyPair.publicKey); }); }); PBKDF2 In this example we ask the user for a pas...
...DerivedBits() { const keyMaterial = await getKeyMaterial(); salt = window.crypto.getRandomValues(new Uint8Array(16)); const derivedBits = await window.crypto.subtle.deriveBits( { "name": "PBKDF2", salt: salt, "iterations": 100000, "hash": "SHA-256" }, keyMaterial, 256 ); const buffer = new Uint8Array(derivedBits, 0, 5); const derivedBitsValue = document.querySelector(".pbkdf2 .derived-bits-value"); derivedBitsValue.classList.add("fade-in"); derivedBitsValue.addEventListener("animationend", () => { derivedBitsValue.classList.remove("fade-in"); }); derivedBitsValue.textContent = `${buffer}...[${derivedBits.byteLength} bytes total]`; } const deriveBitsButton = document.querySelector(".pbkdf2 .derive-bits-button"); deriveBitsButton.addE...
SubtleCrypto.encrypt() - Web APIs
CM is an "authenticated" mode, which means that it includes checks that the ciphertext has not been modified by an attacker. Examples Note: You can try the working examples out on GitHub. RSA-OAEP This code fetches the contents of a text box, encodes it for encryption, and encrypts it with using RSA-OAEP. See the complete code on GitHub. ...
...e); } function encryptMessage(publicKey) { let encoded = getMessageEncoding(); return window.crypto.subtle.encrypt( { name: "RSA-OAEP" }, publicKey, encoded ); } AES-CTR This code fetches the contents of a text box, encodes it for encryption, and encrypts it using AES in CTR mode. See the complete code on GitHub. ...
...nt = await window.crypto.subtle.encrypt( { name: "AES-CTR", counter: iv, length: 128 }, key_encoded, data ); //Uint8Array console.log(encrypted_content); AES-CBC This code fetches the contents of a text box, encodes it for encryption, and encrypts it using AES in CBC mode. See the complete code on GitHub. ...
...eeded for decryption iv = window.crypto.getRandomValues(new Uint8Array(16)); return window.crypto.subtle.encrypt( { name: "AES-CBC", iv }, key, encoded ); } AES-GCM This code fetches the contents of a text box, encodes it for encryption, and encrypts it using AES in GCM mode. See the complete code on GitHub. ...
SubtleCrypto.sign() - Web APIs
Web › API › SubtleCrypto › sign
ey(). Examples Note: You can try the working examples out on GitHub. RSASSA-PKCS1-v1_5 This code fetches the contents of a text box, encodes it for signing, and signs it with a private key. See the complete source code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getMessageEncoding() { const messageBox = document.querySelector(".rsassa-pkcs1 #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } let encoded = getMessageEncoding(); let signature = await window.crypto.subtle.sign( "RSASSA-PKCS1-v1_5", privateKey, encoded ); RSA-PSS This code fetches the contents of a text box, encodes it for signing, and signs it with a private key. See the com...
...wait window.crypto.subtle.sign( "RSASSA-PKCS1-v1_5", privateKey, encoded ); RSA-PSS This code fetches the contents of a text box, encodes it for signing, and signs it with a private key. See the complete source code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. ...
....sign( { name: "RSA-PSS", saltLength: 32, }, privateKey, encoded ); ECDSA This code fetches the contents of a text box, encodes it for signing, and signs it with a private key. See the complete source code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. ...
...( { name: "ECDSA", hash: {name: "SHA-384"}, }, privateKey, encoded ); HMAC This code fetches the contents of a text box, encodes it for signing, and signs it with a secret key. See the complete source code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getMessageEncoding() { const messageBox = document.querySelector(".hmac #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } let encoded = getMessageEncoding(); let signature = await window.crypto.subtle.sign( "HMAC", key, encoded ); Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.sign()' in that specification. ...
Text.splitText() - Web APIs
Web › API › Text › splitText
eption with a value of INDEX_SIZE_ERR is thrown if the specified offset is negative or is greater than the number of 16-bit units in the node's text; a DOMException with a value of NO_MODIFICATION_ALLOWED_ERR is thrown if the node is read-only. Example In this example, the text of a <p> is split into two text nodes, and a <u> is inserted between them. ...
...xt of a <p> is split into two text nodes, and a <u> is inserted between them. HTML <p>foobar</p> JavaScript const p = document.querySelector('p'); // Get contents of <p> as a text node const foobar = p.firstChild; // Split 'foobar' into two text nodes, 'foo' and 'bar', // and save 'bar' as a const const bar = foobar.splitText(3); // Create a <u> element containing ' new content ' const u = document.createElement('u'); u.appendChild(document.createTextNode(' new content ')); // Add <u> before 'bar' p.insertBefore(u, bar); // The result is: <p>foo<u> new content </u>bar</p> Result Specifications Specification Status Comment DOMThe definition of 'Text.splitText' in that specification. Living Standard No change from Document Object Model (DOM) Level 3 Co...
...ndChild(document.createTextNode(' new content ')); // Add <u> before 'bar' p.insertBefore(u, bar); // The result is: <p>foo<u> new content </u>bar</p> Result Specifications Specification Status Comment DOMThe definition of 'Text.splitText' in that specification. Living Standard No change from Document Object Model (DOM) Level 3 Core Specification. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Text.splitText' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification. Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Text.splitText' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. ...
...Object Model (DOM) Level 3 Core SpecificationThe definition of 'Text.splitText' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification. Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Text.splitText' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'Text.splitText' in that specification. Obsolete Initial definition. ...
Text - Web APIs
Web › API › Text
The Text interface represents the textual content of Element or Attr. If an element has no markup within its content, it has a single child implementing Text that contains the element's text. However, if the element contains markup, it is parsed into information items and Text nodes that form its children. New documents have a single Text node for each block of text. Over time, more Text nodes may be created as the document's content changes. The Node.normalize() method merges adjacent Text objects back into a single node for each block of text. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" view...
...ns a Text node with the parameter as its textual content. Properties Inherits properties from its parent, CharacterData. Text.isElementContentWhitespace Read only Returns a Boolean flag indicating whether or not the text node contains only whitespace. Text.wholeText Read only Returns a DOMString containing the text of all Text nodes logically adjacent to this Node, concatenated in document order. Text.assignedSlot Read only Returns the HTMLSlotElement object associated with the element. Properties included from Slotable The Text interface includes the following property, defined on the Slotable mixin. Slotable.assignedSlot Read only Returns a HTMLSlotElement representing the <slot> the node is inserted in. Methods Inherits methods from its parent, CharacterData. ...
...text. Text.splitText Breaks the node into two nodes at a specified offset. Specifications Specification Status Comment DOMThe definition of 'Text' in that specification. Living Standard Removed the isElementContentWhitespace property. Removed the replaceWholeText() method. Added the Text() constructor. Added the assignedSlot property. ...
...moved the isElementContentWhitespace property. Removed the replaceWholeText() method. Added the Text() constructor. Added the assignedSlot property. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Text' in that specification. Obsolete Added the isElementContentWhitespace and wholeText properties. Added the replaceWholeText() method. Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Text' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'Text' in that specification. Obsolete Initial definition. ...
Touch.target - Web APIs
Web › API › Touch › target
If there is any risk of an element being removed while it is being touched, the best practice is to attach the touch listeners directly to the target. ...
...If there is any risk of an element being removed while it is being touched, the best practice is to attach the touch listeners directly to the target. ...
...If there is any risk of an element being removed while it is being touched, the best practice is to attach the touch listeners directly to the target. ...
... started when contact is first placed on the surface. In following simple code snippet, we assume the user initiates one or more touch contacts on the source element. When the touchstart event handler for this element is invoked, each touch point's Touch.target property is accessed via the event's TouchEvent.targetTouches list. // Register a touchmove listener for the 'source' element var src = document.getElementById("source"); src.addEventListener('touchstart', function(e) { // Iterate through the touch points that were activiated // for this element. for (var i=0; i < e.targetTouches.length; i++) { console.log("touchpoint[" + i + "].target = " + e.targetTouches[i].target); } }, false); Specifications Specification Status Comment Touch Events - Level 2 ...
UIEvent.layerX - Web APIs
Web › API › UIEvent › layerX
The UIEvent.layerX read-only property returns the horizontal coordinate of the event relative to the current layer. This property takes scrolling of the page into account and returns a value relative to the whole of the document unless the event occurs inside a positioned element, where the returned value is relative to the top left of the positioned element. Syntax var xpos = event.layerX xpos is an integer value in pixels for the x-coordinate of the mouse pointer, when the mouse event fired. ...
...nside a positioned element, where the returned value is relative to the top left of the positioned element. Syntax var xpos = event.layerX xpos is an integer value in pixels for the x-coordinate of the mouse pointer, when the mouse event fired. ...
... page.</p> <div id="d1"> <span>This is an un-positioned div so clicking it will return layerX/layerY values almost the same as pageX/PageY values.</span> </div> <div id="d2"> <span>This is a positioned div so clicking it will return layerX/layerY values that are relative to the top-left corner of this positioned element. ...
...rner of this positioned element. Note the pageX\pageY properties still return the absolute position in the document, including page scrolling.</span> <span>Make the page scroll more! This is a positioned div so clicking it will return layerX/layerY values that are relative to the top-left corner of this positioned element. Note the pageX\pageY properties still return the absolute position in the document, including page scrolling.</span> </div> <div id="d3"> <form name="form_coords" id="form1"> Parent Element id: <input type="text" name="parentId" size="7" /><br /> pageX:<input type="text" name="pageXCoords" size="7" /> pageY:<input type="text" name="pageYCoords" size="7" /><br /> layerX:<input type="text" name="layerXCoords" size="7" /> layerY:<input type="text" name="layerYCoords" size="...
UIEvent.layerY - Web APIs
Web › API › UIEvent › layerY
The UIEvent.layerY read-only property returns the vertical coordinate of the event relative to the current layer. This property takes scrolling of the page into account, and returns a value relative to the whole of the document, unless the event occurs inside a positioned element, where the returned value is relative to the top left of the positioned element. Syntax var ypos = event.layerY; ypos is an integer value in pixels for the y-coordinate of the mouse pointer, when the mouse event fired. ...
...side a positioned element, where the returned value is relative to the top left of the positioned element. Syntax var ypos = event.layerY; ypos is an integer value in pixels for the y-coordinate of the mouse pointer, when the mouse event fired. ...
... page.</p> <div id="d1"> <span>This is an un-positioned div so clicking it will return layerX/layerY values almost the same as pageX/PageY values.</span> </div> <div id="d2"> <span>This is a positioned div so clicking it will return layerX/layerY values that are relative to the top-left corner of this positioned element. ...
...rner of this positioned element. Note the pageX\pageY properties still return the absolute position in the document, including page scrolling.</span> <span>Make the page scroll more! This is a positioned div so clicking it will return layerX/layerY values that are relative to the top-left corner of this positioned element. Note the pageX\pageY properties still return the absolute position in the document, including page scrolling.</span> </div> <div id="d3"> <form name="form_coords" id="form1"> Parent Element id: <input type="text" name="parentId" size="7" /><br /> pageX:<input type="text" name="pageXCoords" size="7" /> pageY:<input type="text" name="pageYCoords" size="7" /><br /> layerX:<input type="text" name="layerXCoords" size="7" /> layerY:<input type="text" name="layerYCoords" size="...
UIEvent.pageY - Web APIs
Web › API › UIEvent › pageY
The UIEvent.pageY read-only property returns the vertical coordinate of the event relative to the whole document. Syntax var pageY = event.pageY; pageY is an integer value in pixels for the y-coordinate of the mouse pointer, relative to the whole document, when the mouse event fired. This property takes into account any vertical scrolling of the page. ...
...cument. Syntax var pageY = event.pageY; pageY is an integer value in pixels for the y-coordinate of the mouse pointer, relative to the whole document, when the mouse event fired. This property takes into account any vertical scrolling of the page. ...
...e page.</p> <div id="d1"> <span>This is an un-positioned div so clicking it will return layerX/layerY values almost the same as pageX/PageY values.</span> </div> <div id="d2"> <span>This is a positioned div so clicking it will return layerX/layerY values that are relative to the top-left corner of this positioned element. ...
...rner of this positioned element. Note the pageX\pageY properties still return the absolute position in the document, including page scrolling.</span> <span>Make the page scroll more! This is a positioned div so clicking it will return layerX/layerY values that are relative to the top-left corner of this positioned element. Note the pageX\pageY properties still return the absolute position in the document, including page scrolling.</span> </div> <div id="d3"> <form name="form_coords"> Parent Element id: <input type="text" name="parentId" size="7" /><br /> pageX:<input type="text" name="pageXCoords" size="7" /> pageY:<input type="text" name="pageYCoords" size="7" /><br /> layerX:<input type="text" name="layerXCoords" size="7" /> layerY:<input type="text" name="layerYCoords" size="7" /> </form...
Detect WebGL - Web APIs
ture detection ]</p> <button>Press here to detect WebGLRenderingContext</button> body { text-align : center; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } // Run everything inside window load event handler, to make sure // DOM is fully loaded and styled before trying to manipulate it. ...
... detect WebGLRenderingContext</button> body { text-align : center; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } // Run everything inside window load event handler, to make sure // DOM is fully loaded and styled before trying to manipulate it. ...
... var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); // Report the result. ...
... var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); // Report the result. ...
Scissor animation - Web APIs
; if (!(gl = getRenderingContext())) return; gl.enable(gl.SCISSOR_TEST); gl.clearColor(color[0], color[1], color[2], 1.0); // Unlike the browser window, vertical position in WebGL is // measured from bottom to top. In here we set the initial // position of the square to be at the top left corner of the // drawing buffer. ...
... from bottom to top. In here we set the initial // position of the square to be at the top left corner of the // drawing buffer. ...
...emoveEventListener(evt.type, startAnimation, false); button.addEventListener("click", stopAnimation, false); document.querySelector("strong").innerHTML = "stop"; timer = setInterval(drawAnimation, 17); drawAnimation(); } function stopAnimation(evt) { button.removeEventListener(evt.type, stopAnimation, false); button.addEventListener("click", startAnimation, false); document.querySelector("strong").innerHTML = "start"; clearInterval(timer); } stopAnimation({type: "click"}); } // Variables to hold the size and velocity of the square. var size = [60, 60], velocity = 3.0; function drawAnimation () { gl.scissor(position[0], position[1], size[0] , size[1]); gl.clear(gl.COLOR_BUFFER_BIT); // Every frame the vertical position of the square is // decreased...
... Math.random()*(gl.drawingBufferWidth - size[0]), gl.drawingBufferHeight ]; // Random velocity between 1.0 and 7.0 velocity = 1.0 + 6.0*Math.random(); color = getRandomColor(); gl.clearColor(color[0], color[1], color[2], 1.0); } } function getRandomColor() { return [Math.random(), Math.random(), Math.random()]; } function getRenderingContext() { var canvas = document.querySelector("canvas"); canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { var paragraph = document.querySelector("p"); paragraph.innerHTML = "Failed to get WebGL context." + "Your browser or device may not support WebGL."; return null; } gl.viewport(0...
Taking still photos with WebRTC - Web APIs
s function's job is to request access to the user's webcam, initialize the output <img> to a default state, and to establish the event listeners needed to receive each frame of video from the camera and react when the button is clicked to capture an image. Getting element references First, we grab references to the major elements we need to be able to access. ...
...er's webcam, initialize the output <img> to a default state, and to establish the event listeners needed to receive each frame of video from the camera and react when the button is clicked to capture an image. Getting element references First, we grab references to the major elements we need to be able to access. ...
...efault state, and to establish the event listeners needed to receive each frame of video from the camera and react when the button is clicked to capture an image. Getting element references First, we grab references to the major elements we need to be able to access. ...
...eeded to receive each frame of video from the camera and react when the button is clicked to capture an image. Getting element references First, we grab references to the major elements we need to be able to access. ...
WebXR permissions and security - Web APIs
es not have permission to enable an immersive session. This permission comes from the xr-spatial-tracking feature policy. Once that check is passed, the request to enter immersive-vr mode is allowed if all of the following are true: The requestSession() call was issued by code executing within the handler for a user event, or the from the startup code for a user-launched web application. The document is considered trustworthy, in that it is responsible and is both currently active and has focus. The user's intent to enter immersive VR mode is well understood; see User intent below for details. If all of that is true, the promise returned by requestSession() is resolved, and the new XRSession object is passed into the fulfillment handler. Otherwise, an appropriate exception is thrown, such ...
...hy, in that it is responsible and is both currently active and has focus. The user's intent to enter immersive VR mode is well understood; see User intent below for details. If all of that is true, the promise returned by requestSession() is resolved, and the new XRSession object is passed into the fulfillment handler. Otherwise, an appropriate exception is thrown, such as SecurityError if the document doesn't have permission to enter immersive mode. Inline presentation When you request an XRSession with the mode set to inline, and any features are required or requested, the browser will only allow the session to be created if the call to requestSession() was made by code which is executing expressly due to user intent. Specifically: If the requestSession() call isn't coming from within t...
...low the session to be created if the call to requestSession() was made by code which is executing expressly due to user intent. Specifically: If the requestSession() call isn't coming from within the handler executed in response to a user event, and is not being issued while launching a web application, the request is denied and false is delivered to the promise's fulfillment handler. If the document making the request isn't the one which is responsible for the script, the request is denied. If the document making the request isn't trustworthy, the request is denied and false is returned through the promise's fulfillment routine. A trustworthy document is one which is both responsible and active, and which currently has focus. If the user's intent to open an inline XR presentation is not we...
...use of something the user intends to do or not. There are two kinds of user intent: implicit and explicit. Explicit user intent (explicit user consent) is granted when the user has specifically and expressly been asked for permission to perform an action. Implicit user intent (implicit user consent) is assumed if either of the following scenarios is the case: The user has interacted with the document in some way which has in turn caused your request to occur. For example, if you have an "Enter XR mode" button, and the user clicks it, calling requestSession() from the button's click event handler will permitted. If your code is executing during the launch of a web application, the runtime may consider the act of launching your web application to qualify as user intent. ...
Using the Web Audio API - Web APIs
d to use the crossorigin attribute; see Cross Origin Resource Sharing (CORS) for more information. To use all the nice things we get with the Web Audio API, we need to grab the source from this element and pipe it into the context we have created. Lucky for us there's a method that allows us to do just that -- AudioContext.createMediaElementSource: // get the audio element const audioElement = document.querySelector('audio'); // pass it into the audio context const track = audioContext.createMediaElementSource(audioElement); Note: The <audio> element above is represented in the DOM by an object of type HTMLMediaElement, which comes with its own set of functionality. All of this has stayed intact; we are merely allowing the sound to be available to the Web Audio API. Controlling sound Whe...
...tput node, you can just connect your other nodes to BaseAudioContext.destination, which handles the situation for you: track.connect(audioContext.destination); A good way to visualise these nodes is by drawing an audio graph so you can visualize it. This is what our current audio graph looks like: Now we can add the play and pause functionality. ...
...ange input: <input type="range" id="volume" min="0" max="2" value="1" step="0.01"> Note: Range inputs are a really handy input type for updating values on audio nodes. You can specify a range's values and use them directly with the audio node's parameters. So let's grab this input's value and update the gain value when the input node has its value changed by the user: const volumeControl = document.querySelector('#volume'); volumeControl.addEventListener('input', function() { gainNode.gain.value = this.value; }, false); Note: The values of node objects (e.g. GainNode.gain) are not simple values; they are actually objects of type AudioParam -- these called parameters. This is why we have to set GainNode.gain's value property, rather than just setting the value on gain directly. This ...
...d by all browsers at this time. The older factory methods are supported more widely. Here our values range from -1 (far left) and 1 (far right). Again let's use a range type input to vary this parameter: <input type="range" id="panner" min="-1" max="1" value="0" step="0.01"> We use the values from that input to adjust our panner values in the same way as we did before: const pannerControl = document.querySelector('#panner'); pannerControl.addEventListener('input', function() { panner.pan.value = this.value; }, false); Let's adjust our audio graph again, to connect all the nodes together: track.connect(gainNode).connect(panner).connect(audioContext.destination); The only thing left to do is give the app a try: Check out the final demo here on Codepen. Summary Great! We have a boom...
Window: blur event - Web APIs
Web › API › Window › blur event
The blur event fires when an element has lost focus. The opposite of blur is focus. Bubbles No Cancelable No Interface 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. ...
...osite of blur is focus. Bubbles No Cancelable No Interface 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. ...
...ent 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. ...
...tListener() 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 Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. Document Object Model (DOM) Level 3 Events Specification Obsolete Initial definition ...
Window: focus event - Web APIs
The focus event fires when an element has received focus. The opposite of focus is blur. Bubbles No Cancelable No Interface 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. ...
...f focus is blur. Bubbles No Cancelable No Interface 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. ...
...nt 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. ...
...tListener() 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 Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. Document Object Model (DOM) Level 3 Events Specification Obsolete Initial definition ...
Window.getComputedStyle() - Web APIs
ugh 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>. ...
...luding 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 wanting to write a testing spec for window and making an API that was also usable in Java. Use with pseudo-elements getComputedStyle can pull style info from pseudo-elements (such as ::after, ::before, ::marker, ::...
...as a combination of folks not wanting to write a testing spec for window and making an API that was also usable in Java. Use with pseudo-elements getComputedStyle can pull style info from pseudo-elements (such as ::after, ::before, ::marker, ::line-marker -- see the pseudo-element spec). <style> h3::after { content: ' rocks!'; } </style> <h3>Generated content</h3> <script> var h3 = document.querySelector('h3'); var result = getComputedStyle(h3, ':after').content; console.log('the generated content is: ', result); // returns ' rocks!' </script> Notes The returned CSSStyleDeclaration object contains active values for CSS property longhand names. For example, border-bottom-width instead of the border-width and border shorthand property names. It is safest to query values with...
...he used value, not the value auto. So if you apply top:auto and bottom:0 on an element with height:30px and a containing block of height:100px, Firefox's computed style for top returns 70px, as 100 - 30 = 70. Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'getComputedStyle()' in that specification. Working Draft Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'getComputedStyle()' in that specification. Obsolete Initial definition ...
Window: load event - Web APIs
Web › API › Window › load event
lass="event-log-contents" rows="8" cols="30"></textarea> </div> CSS body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } JS const log = document.querySelector('.event-log-contents'); const reload = document.querySelector('#reload'); reload.addEventListener('click', () => { log.textContent =''; window.setTimeout(() => { window.location.reload(true); }, 200); }); window.addEventListener('load', (event) => { log.textContent = log.textContent + 'load\n'; }); document.addEventListener('readystatechange', (event) => { log...
... Working Draft HTML Living StandardThe definition of 'load event' in that specification. ...
... Working Draft HTML Living StandardThe definition of 'load event' in that specification. Living Standard This links to ...
...'load' events are fired at many elements too. And note there are many places in the specification that refer to things that can "delays the load event". ...
window.postMessage() - Web APIs
s you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself. [1] targetOrigin Specifies what the origin of targetWindow must be for the event to be dispatched, either as the literal string "*" (indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of targetWindow's document does not match that provided in targetOrigin, the event will not be dispatched; only if all three match will the event be dispatched. This mechanism provides control over where messages are sent; for example, if postMessage() was used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the ...
...trol over where messages are sent; for example, if postMessage() was used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party. Always provide a specific targetOrigin, not *, if you know where the other window's document should be located. Failing to 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 message...
...e on event.source and provide // event.origin as the targetOrigin. event.source.postMessage("hi there yourself! the secret response " + "is: rheeeeet!", event.origin); } window.addEventListener("message", receiveMessage, false); Notes Any window may access this method on any other window, at any time, regardless of the location of the document in the window, to send it a message. Consequently, any event listener used to receive messages must first check the identity of the sender of the message, using the origin and possibly source properties. This cannot be overstated: Failure to check the origin and possibly source properties enables cross-site scripting attacks. As with any asynchronously-dispatched script (timeouts, user-generated...
...ge() schedules the MessageEvent to be dispatched only after all pending execution contexts have finished. For example, if postMessage() is invoked in an event handler, that event handler will run to completion, as will any remaining handlers for that same event, before the MessageEvent is dispatched. The value of the origin property of the dispatched event is not affected by the current value of document.domain in the calling window. For IDN host 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 pro...
Window: resize event - Web APIs
The resize event fires when the document view (window) has been resized. Bubbles No Cancelable No Interface UIEvent Event handler property onresize In some earlier browsers it was possible to register resize event handlers on any HTML element. It is still possible to set onresize attributes or use addEventListener() to set a handler on any element. However, resize events are only fired on the window object (i.e. returned by document.defaultView). Only handlers registered on the window object will receive resize events. There is a proposal to allow all elements to be notified of resize changes. See Resize Observer to read the draft document, and GitHub issues to read the on-going discussions. Examples Window size logger The following exam...
...The following example reports the window size each time it is resized. Bear in mind that since the example is running in an <iframe>, you'll need to actually get the <iframe> to resize before you see an effect. ...
... it is resized. Bear in mind that since the example is running in an <iframe>, you'll need to actually get the <iframe> to resize before you see an effect. ...
... Obsolete CSS Object Model (CSSOM) View ModuleThe definition of 'resize' in that specification. Working Draft ...
Window.scrollX - Web APIs
Web › API › Window › scrollX
The read-only scrollX property of the Window interface returns the number of pixels that the document is currently scrolled horizontally. This value is subpixel precise in modern browsers, meaning that it isn't necessarily a whole number. You can get the number of pixels the document is scrolled vertically from the scrollY property. Syntax var x = window.scrollX; Value In practice, the returned value is a double-precision floating-point value indicating the number of pixels the document is currently scrolled horizontally from the origin, where a positive value means the content is scrolled to the left. ...
... If you need an integer value, you can use Math.round() to round it off. ...
...X; Value In practice, the returned value is a double-precision floating-point value indicating the number of pixels the document is currently scrolled horizontally from the origin, where a positive value means the content is scrolled to the left. If the document is rendered on a subpixel-precise device, then the returned value is also subpixel-precise and may contain a decimal component. If the document isn't scrolled at all left or right, then scrollX is 0. If you need an integer value, you can use Math.round() to round it off. In more technical terms, scrollX returns the X coordinate of the left edge of the current viewport. If there is no viewport, the returned value is 0. Example This example checks the current horizontal scroll position of the document. If it's greater than 400 pixels...
...erty: window.pageXOffset == window.scrollX; // always true For cross-browser compatibility, use window.pageXOffset instead of window.scrollX. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. A fully compatible example: var x = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft; var y = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop; Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'window.scrollX' in that specification. W...
Window.speechSynthesis - Web APIs
voice they want. Inside the inputForm.onsubmit handler, we stop the form submitting with preventDefault(), create a new SpeechSynthesisUtterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the SpeechSynthesis.speak() method. ...
...t handler, we stop the form submitting with preventDefault(), create a new SpeechSynthesisUtterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the SpeechSynthesis.speak() method. ...
...Default(), create a new SpeechSynthesisUtterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the SpeechSynthesis.speak() method. ...
...e <select> element, and start the utterance speaking via the SpeechSynthesis.speak() method. ...
XMLSerializer - Web APIs
provides the serializeToString() method to construct an XML string representing a DOM tree. Methods serializeToString() Returns the serialized subtree of a string. serializeToStream() The subtree rooted by the specified element is serialized to a byte stream using the character set specified. Examples Serializing XML into a string The first, basic, example just serializes an entire document into a string containing XML. var s = new XMLSerializer(); var d = document; var str = s.serializeToString(d); saveXML(str); This involves creating a new XMLSerializer object, then passing the Document to be serialized into serializeToString(), which returns the XML equivalent of the document. Inserting nodes into a DOM based on XML This example uses the Element.insertAdjacentHTML() metho...
...Serializer(); var d = document; var str = s.serializeToString(d); saveXML(str); This involves creating a new XMLSerializer object, then passing the Document to be serialized into serializeToString(), which returns the XML equivalent of the document. Inserting nodes into a DOM based on XML This example uses the Element.insertAdjacentHTML() method to insert a new DOM Node into the body of the Document, based on XML created by serializing an Element object. ...
...ting nodes into a DOM based on XML This example uses the Element.insertAdjacentHTML() method to insert a new DOM Node into the body of the Document, based on XML created by serializing an Element object. Note: In the real world, you should usually instead call importNode() method to import the new node into the DOM, then call one of the following methods to add the node to the DOM tree: The Document and Element methods append() and prepend() The Node.replaceWith() method (to replace an existing node with the new one) The Document.insertAdjacentElement() and Element.insertAdjacentElement() methods. Because insertAdjacentHTML() accepts a string and not a Node as its second parameter, XMLSerializer is used to first convert the node into a string. var inp = document.createElement('input');...
...and Element.insertAdjacentElement() methods. Because insertAdjacentHTML() accepts a string and not a Node as its second parameter, XMLSerializer is used to first convert the node into a string. var inp = document.createElement('input'); var XMLS = new XMLSerializer(); var inp_xmls = XMLS.serializeToString(inp); // First convert DOM node into a string // Insert the newly created node into the document's body document.body.insertAdjacentHTML('afterbegin', inp_xmls); The code creates a new <input> element by calling Document.createElement(), then serializes it into XML using serializeToString(). Once that's done, insertAdjacentHTML() is used to insert the <input> element into the DOM. Specifications Specification Status Comment DOM Parsing and SerializationThe definit...
XPathResult.invalidIteratorState - Web APIs
The read-only invalidIteratorState property of the XPathResult interface signifies that the iterator has become invalid. It is true if XPathResult.resultType is UNORDERED_NODE_ITERATOR_TYPE or ORDERED_NODE_ITERATOR_TYPE and the document has been modified since this result was returned. Note: This feature is available in Web Workers. Syntax var iteratorState = result.invalidIteratorState; Return value A boolean value indicating whether the iterator has become invalid. Example The following example shows the use of the invalidIteratorState property. ...
...ed. Note: This feature is available in Web Workers. Syntax var iteratorState = result.invalidIteratorState; Return value A boolean value indicating whether the iterator has become invalid. Example The following example shows the use of the invalidIteratorState property. ...
...s available in Web Workers. Syntax var iteratorState = result.invalidIteratorState; Return value A boolean value indicating whether the iterator has become invalid. Example The following example shows the use of the invalidIteratorState property. ...
...State; Return value A boolean value indicating whether the iterator has become invalid. Example The following example shows the use of the invalidIteratorState property. HTML <div>XPath example</div> <p>Iterator state: <output></output></p> JavaScript var xpath = "//div"; var result = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null); // Invalidates the iterator state document.querySelector("div").remove(); document.querySelector("output").textContent = result.invalidIteratorState ? "invalid" : "valid"; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathResult.invalidIteratorState' in that specification. Recommendation Initial definition ...
XPathResult.iterateNext() - Web APIs
over a node set result and returns the next node from it or null if there are no more nodes. Syntax var node = result.iterateNext(); Return value The next Node within the node set of the XPathResult. Exceptions TYPE_ERR In case XPathResult.resultType is not UNORDERED_NODE_ITERATOR_TYPE or ORDERED_NODE_ITERATOR_TYPE, an XPathException of type TYPE_ERR is thrown. ...
...YPE, an XPathException of type TYPE_ERR is thrown. INVALID_STATE_ERR If the document is mutated since the result was returned, an XPathException of type INVALID_STATE_ERR is thrown. Example The following example shows the use of the iterateNext() method. ...
... type TYPE_ERR is thrown. INVALID_STATE_ERR If the document is mutated since the result was returned, an XPathException of type INVALID_STATE_ERR is thrown. Example The following example shows the use of the iterateNext() method. ...
...rown. Example The following example shows the use of the iterateNext() method. HTML <div>XPath example</div> <div>Tag names of the matched nodes: <output></output></div> JavaScript var xpath = "//div"; var result = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null); var node = null; var tagNames = []; while(node = result.iterateNext()) { tagNames.push(node.localName); } document.querySelector("output").textContent = tagNames.join(", "); Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathResult.iterateNext()' in that specification. Recommendation Initial definition ...
XPathResult.snapshotItem() - Web APIs
Syntax var node = result.snapshotItem(i); Return value The Node at the given index within the node set of the XPathResult. ...
...he XPathResult. Exceptions TYPE_ERR In case XPathResult.resultType is not UNORDERED_NODE_SNAPSHOT_TYPE or ORDERED_NODE_SNAPSHOT_TYPE, an XPathException of type TYPE_ERR is thrown. Example The following example shows the use of the snapshotItem() method. ...
...ns TYPE_ERR In case XPathResult.resultType is not UNORDERED_NODE_SNAPSHOT_TYPE or ORDERED_NODE_SNAPSHOT_TYPE, an XPathException of type TYPE_ERR is thrown. Example The following example shows the use of the snapshotItem() method. ...
...tem() method. HTML <div>XPath example</div> <div>Tag names of the matched nodes: <output></output></div> JavaScript var xpath = "//div"; var result = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); var node = null; var tagNames = []; for(var i = 0; i < result.snapshotLength; i++) { var node = result.snapshotItem(i); tagNames.push(node.localName); } document.querySelector("output").textContent = tagNames.join(", "); Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathResult.snapshotItem()' in that specification. Recommendation Initial definition ...
XSL Transformations in Mozilla FAQ - Web APIs
us to add a parsing step to our output generation, which we don't. In most cases, there are pretty easy workarounds. The only use cases we have seen are bad XML or bad XSLT. And RSS feeds. The latter is pretty much the only issue to us, and we're sorry that we can't support it. But mixing parsing with XSLT is brittle and we rather not support d-o-e than either crash or be even slower. What about document.write? Just like for XHTML, document.write is not supported during XSLT transformations. Sadly, current builds don't error, but just give unexpected results, like crashes (bug 202765). In most cases, there is no need to actually use it, though. If you need platform dependent code or stylesheets, just do <xsl:if test="system-property('xsl:vendor')='Transformiix'"> <!-- Mozilla spec...
...endor')='Microsoft'"> <!-- IE specific markup --> </xsl:if> Check system-properties.xml for the properties of your favorite system. MSXML has an additional property. <xsl:if xmlns:msxsl="urn:schemas-microsoft-com:xslt" test="system-property('msxsl:version')=3"> <!-- MSXML3 specific markup --> </xsl:if> What about media="print"? When printing a document, Mozilla tries to render the page on paper as closely to what you see as possible. This includes stuff like text entered into textfields and other dynamic changes. This is achieved by printing the current DOM tree. Having XSLT stylesheet specific to particular media would require to retransform the original XML source, which counteracts the expectations of the user. Thus, using media in <?xml-sty...
...hich counteracts the expectations of the user. Thus, using media in <?xml-stylesheet ?> 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 implem...
...mespace 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. ...
Web APIs
Web › API
ng DOMStringList DOMStringMap DOMTimeStamp DOMTokenList DOMUserData DataTransfer DataTransferItem DataTransferItemList DedicatedWorkerGlobalScope DelayNode DeprecationReportBody DeviceLightEvent DeviceMotionEvent DeviceMotionEventAcceleration DeviceMotionEventRotationRate DeviceOrientationEvent DeviceProximityEvent DirectoryEntrySync DirectoryReaderSync DisplayMediaStreamConstraints Document DocumentFragment DocumentOrShadowRoot DocumentTimeline DocumentTouch DocumentType DoubleRange DragEvent DynamicsCompressorNode E EXT_blend_minmax EXT_color_buffer_float EXT_color_buffer_half_float EXT_disjoint_timer_query EXT_float_blend EXT_frag_depth EXT_sRGB EXT_shader_texture_lod EXT_texture_compression_bptc EXT_texture_compression_rgtc EXT_texture_filter_anisotropic EcKeyGenParams EcKeyIm...
...Position GeolocationPositionError GeometryUtils GestureEvent GlobalEventHandlers Gyroscope H HTMLAnchorElement HTMLAreaElement HTMLAudioElement HTMLBRElement HTMLBaseElement HTMLBaseFontElement HTMLBodyElement HTMLButtonElement HTMLCanvasElement HTMLCollection HTMLContentElement HTMLDListElement HTMLDataElement HTMLDataListElement HTMLDetailsElement HTMLDialogElement HTMLDivElement HTMLDocument HTMLElement HTMLEmbedElement HTMLFieldSetElement HTMLFontElement HTMLFormControlsCollection HTMLFormElement HTMLFrameSetElement HTMLHRElement HTMLHeadElement HTMLHeadingElement HTMLHtmlElement HTMLHyperlinkElementUtils HTMLIFrameElement HTMLImageElement HTMLInputElement HTMLIsIndexElement HTMLKeygenElement HTMLLIElement HTMLLabelElement HTMLLegendElement HTMLLinkElement HTMLMapElement HTM...
...useScrollEvent MouseWheelEvent MutationEvent MutationObserver MutationObserverInit MutationRecord N NDEFMessage NDEFReader NDEFReadingEvent NDEFRecord NDEFWriter NameList NamedNodeMap NavigationPreloadManager Navigator NavigatorConcurrentHardware NavigatorID NavigatorLanguage NavigatorOnLine NavigatorPlugins NavigatorStorage NetworkInformation Node NodeFilter NodeIterator NodeList NonDocumentTypeChildNode Notation Notification NotificationAction NotificationEvent NotifyAudioAvailableEvent O OES_element_index_uint OES_fbo_render_mipmap OES_standard_derivatives OES_texture_float OES_texture_float_linear OES_texture_half_float OES_texture_half_float_linear OES_vertex_array_object OVR_multiview2 OfflineAudioCompletionEvent OfflineAudioContext OffscreenCanvas OrientationSensor O...
...hader WebGLShaderPrecisionFormat WebGLSync WebGLTexture WebGLTransformFeedback WebGLUniformLocation WebGLVertexArrayObject WebKitCSSMatrix WebSocket WheelEvent Window WindowClient WindowEventHandlers WindowOrWorkerGlobalScope Worker WorkerGlobalScope WorkerLocation WorkerNavigator Worklet WritableStream WritableStreamDefaultController WritableStreamDefaultWriter X XDomainRequest XMLDocument XMLHttpRequest XMLHttpRequestEventTarget XMLHttpRequestResponseType XMLSerializer XPathEvaluator XPathException XPathExpression XPathNSResolver XPathResult XRBoundedReferenceSpace XREnvironmentBlendMode XREye XRFrame XRFrameRequestCallback XRHandedness XRInputSource XRInputSourceArray XRInputSourceEvent XRInputSourceEventInit XRInputSourcesChangeEvent XRInputSourcesChangeEventInit XRPermissionD...
ARIA: Complementary role - Accessibility
as sidebars or call-out boxes. If possible, use the HTML <aside> element instead. <div role="complementary"> <h2>Our partners</h2> <!-- complementary section content --> </div> This is a sidebar containing links to event sponsors. Description The complementary role is a landmark role. Landmarks can be used by assistive technology to quickly identify and navigate to large sections of the document. Content listed within a container with the complementary landmark role should make sense if separated from the main content of the document. Using the <aside> element will automatically communicate a section has a role of complementary. Developers should always prefer using the correct semantic HTML element over using ARIA. Examples <div role="complementary"> <h2>Trending articles</h2> ...
... <li><a href="#">The time has come to finally decide what we should be calling these foods</a></li> <li><a href="#">17 really good posts we saw on Tumblr this week</a></li> <li><a href="#">10 parent hacks we know work because we tried them</a></li> </ul> </div> Accessibility concerns Landmark roles are intended to be used sparingly, to identify larger overall sections of the document. Using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. Best practices Prefer HTML Using the <aside> element will automatically communicate a section has a role of complementary. If at all possible, prefer using it instead. Labeling landmarks Multiple landmarks If there is more than one complementary landmark rol...
...roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. Best practices Prefer HTML Using the <aside> element will automatically communicate a section has a role of complementary. If at all possible, prefer using it instead. Labeling landmarks Multiple landmarks If there is more than one complementary landmark role or <aside> element in a document, provide a label for each landmark using the aria-label attribute, or, if the aside has an appropriately descriptive title, point to it with the aria-labelledby attribute. This label will allow an assistive technology user to be able to quickly understand the purpose of each landmark. <aside aria-label="Note about usage"> <!-- content --> </aside> ... <aside id="sidebar" aria-label="Sponsors...
...be what the landmark is in its label. For example, a declaration of role="complementary" with an of aria-label="Sidebar" may be announced redundantly as, "complementary sidebar". Added benefits Certain technologies such as browser extensions can generate lists of all landmark roles present on a page, allowing non-screen reader users to also quickly identify and navigate to large sections of the document. Landmarks browser extension Specifications Specification Status Accessible Rich Internet Applications (WAI-ARIA) 1.1The definition of 'ARIA: Complementary role' in that specification. Recommendation WAI-ARIA Authoring PracticesThe definition of 'Complementary landmark role' in that specification. Working Draft Screen reader support TBD ...
ARIA: contentinfo role - Accessibility
role="contentinfo"> <h2>Footer</h2> <!-- footer content --> </div> This is a website footer. Using the <footer> element instead is recommended: <footer> <h2>Footer</h2> <!-- footer content --> </footer> Description The contentinfo role is a landmark used to identify a page footer. Landmarks can be used by assistive technology to quickly identify and navigate to large sections of the document. Pages should only include one top-level contentinfo landmark role per page. Each page should only include one contentinfo landmark, created by either using the <footer> element or by declaring role="contentinfo". contentinfo landmarks present in content embedded via <iframe> elements do not count towards this limit. Using the <footer> element will automatically communicate a section has a rol...
...</li> <li><a href="#">Learn Web Development</a></li> <li><a href="#">About MDN</a></li> <li><a href="#">Feedback</a></li> </ul> <p>(C) 2005-2018 Mozilla and individual contributors. Content is available under <a href="#">these licenses</a>.</p> </div> </body> Accessibility concerns Use sparingly Landmark roles are intended to identify larger overall sections of the document. Using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. One contentinfo landmark per page The <body> element There should be only one contentinfo landmark per document, used as the immediate descendant of the <body> element. Mega-footers Do not nest additional <footer> elements or contentinfo landmarks inside of t...
...sing too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. One contentinfo landmark per page The <body> element There should be only one contentinfo landmark per document, used as the immediate descendant of the <body> element. Mega-footers Do not nest additional <footer> elements or contentinfo landmarks inside of the document's footer. Use other content sectioning elements instead. Labeling landmarks Multiple landmarks If there is more than one contentinfo landmark role or <footer> element in a document, provide a label with the aria-label attribute for each landmark. This label will allow assitive technology users to quickly understand the purpose of each landmark. <body> ... <article> <h2>Everyday Pad ...
...in VoiceOver). If at all possible, prefer using <footer> instead. Note that a footer element nested within an article, aside, main, nav, or section is not considered contentinfo. Added benefits Certain technologies such as browser extensions can generate lists of all landmark roles present on a page, allowing non-screen reader users to also quickly identify and navigate to large sections of the document. Landmarks browser extension Specifications Specification Status Accessible Rich Internet Applications (WAI-ARIA) 1.1The definition of 'contentinfo landmark role' in that specification. Recommendation WAI-ARIA Authoring PracticesThe definition of 'contentinfo landmark role' in that specification. Working Draft Screen reader support ...
ARIA: Main role - Accessibility
The main landmark role is used to indicate the primary content of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application. <div id="main" role="main"> <h1>Avocados</h1> <!-- main section content --> </div> This is the main section of a document that discusses avocados. Subsections of this document could discuss their history, the different types, regions where they grow, etc. Description The main role is a navigational landmark role identifying the main content of a document. Landmarks can be used by assistive technology to quickly identify and navigate to large sections of the document. By classifying and labeling sections of a page, structural information conveyed...
...ument. By classifying and labeling sections of a page, structural information conveyed visually through layout can be represented programmatically. Screen readers use landmark roles to provide keyboard navigation to important sections of a page. For those navigating via landmark roles, the main role is an alternative for "skip to main content" links.There should only be one main landmark role per document. The <main> element has a role of main. Developers should always prefer using the correct semantic HTML element over using ARIA. Documents and applications can be nested in the DOM, which may lead to having more than one main element as DOM descendants. If this is the case, include aria-owns to identify the relationship of the main to it's document or application ancestor. Example <body> <!
...an one main element as DOM descendants. If this is the case, include aria-owns to identify the relationship of the main to it's document or application ancestor. 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 <c...
... Landmarks browser extension Specifications Specification Status Accessible Rich Internet Applications (WAI-ARIA) 1.1The definition of 'ARIA Navigtion Role' in that specification. Recommendation WAI-ARIA Authoring PracticesThe definition of 'Navigation Landmark Role' in that specification. Working Draft Screen reader support TBD ...
Web Accessibility: Understanding Colors and Luminance - Accessibility
some circles. In others, "chroma" and "saturation" are two different concepts. The "L" in the HSL color space is sometimes referred to as "luminosity," other times as "lightness." Even something seemingly simple like naming common colors can be open to debate. For example, the color "crimson red" may be described in hex values as #990000 by some and #DC143C by others. For the purposes of this document, we'll use terminlogy as it is defined in the W3C, in the CSS Color Module Level 3 When working with color, it's important to know which "color space" you are working in, as different color spaces map to different measurement systems. Currently, the RGB color space predominates as the space web developers work in. HEX, RGB and HSL color spaces all are measured differently. Conversions between ...
...pace" you are working in, as different color spaces map to different measurement systems. Currently, the RGB color space predominates as the space web developers work in. HEX, RGB and HSL color spaces all are measured differently. Conversions between the color spaces are usually needed. Because of the current domination of the RGB color space in measuring color output, most calculations in this document are presumed to be in the RGB color space, and very specifically, in the sRGB color space. The sRGB color space The MDN document, <color> notes "The CSS data type represents a color in the sRGB color space." Color has many ways of being defined, including RGB, RGB decimal, RGB percent, HSL, CMYK among others. For digital concerns, much of the technology has historically resided in the RGB ...
...alue of rgb(0,0,0) Where do these numbers of 0 to 255 come from? Historically, graphics engines store the color channels as a single byte; that means a range of integers between 0 and 255. The luminances of the primary colors are different. Yellow has a greater luminance than blue, for example. This was done by way of design, "to achieve white alignment of the monitor" according to the NASA document, "Luminance Contrast in Color Graphics" Once luminance is established, the color contrast ratio can be established. A color contrast ratio is meaningless without its luminance component. Where human perception is concerned, a difference in luminance matters more than a difference in color. This is important, luminance contrast enables the development of content that even those with color-blin...
...urrounding the color. The color will appear differently if the background lighting is dark, or light. One of the greatest gifts to accessibility now in development is the CSS Media Queries Level 5. These queries will allow users to choose contrast levels that is right for them, and enable them to adjust these levels depending upon where they are, and what kind of screen they are using. The MDN document, Ambient Light Events, describes an experimental technology worth watching; this technology would enable a web page to be aware of any change in the light intensity, and consquently, adjust the text accordingly. This would be a great boon to those with motor skills problems, or do not have the use of their hands. To summarize, color is as much about human physiology and perception in the brain ...
Keyboard - Accessibility
to use a keyboard for input whenever possible. Focusable elements should have interactive semantics If an element can be focused using the keyboard, then it should be interactive; that is, the user should be able to do something to it and produce a change of some kind (for example, activating a link or changing an option). Note: One important exception to this rule is if the element has role="document" applied to it, inside an interactive context (such as role="application"). In such a case, focusing the nested document is the only way of returning assistive technology to a non-interactive state (often called "browse mode"). Most interactive elements are focusable by default; you can make an element focusable by adding a tabindex=0 attribute value to it. However, you should only add tabindex...
...lers keyboard events. See also tabindex global HTML attribute Global event handlers: onkeydown Global event handlers: onkeyup Avoid using tabindex attribute greater than zero The tabindex attribute indicates that an element is focusable using the keyboard. A value of zero indicates that the element is part of the default focus order, which is based on the ordering of elements in the HTML document. ...
...ich is based on the ordering of elements in the HTML document. A positive value puts the element ahead of those in the default ordering; elements with positive values are focused in the order of their tabindex values (1, then 2, then 3, etc.). This creates confusion for keyboard-only users when the focus order differs from the logical order of the page. A better strategy is to structure the HTML document so that focusable elements are in a logical order, without the need to re-order them with positive tabindex values. See also tabindex global HTML attribute Understanding focus order Don't use tabindex greater than 0 Clickable elements must be focusable and should have interactive semantics If an element can be clicked with a pointing device, such as a mouse, then it should also be focusa...
...nteractive elements must be focusable If the user can interact with an element (for example, using touch or a pointing device), then it should be focusable using the keyboard. You can make it focusable by adding a tabindex=0 attribute value to it. That will add the element to the list of elements that can be focused by pressing the Tab key, in the sequence of such elements as defined in the HTML document. See also tabindex global HTML attribute Focusable element must have focus styling Any element that can receive keyboard focus should have visible styling that indicates when the element is focused. You can do this with the :focus CSS pseudo-class. Standard focusable elements such as links and input fields are given special styling by the browser by default, so you might not need to speci...
-webkit-text-stroke-color - CSS: Cascading Style Sheets
Living Standard Initial standardization Safari...
... Non-standard unofficia...
...change", function(evt) { document.querySelector("p").style.webkitTextStrokeColor = evt.target.value; }); Results Specifications Specification Status Comment Compatibility StandardThe definition of '-webkit-text-stroke-color' in that specification. Living Standard Initial standardization Safari CSS Reference '-webkit-text-stroke-color' in that document. ...
...uerySelector("p").style.webkitTextStrokeColor = evt.target.value; }); Results Specifications Specification Status Comment Compatibility StandardThe definition of '-webkit-text-stroke-color' in that specification. Living Standard Initial standardization Safari CSS Reference '-webkit-text-stroke-color' in that document. Non-standard unofficial documentation Initial documentation ...
@viewport - CSS: Cascading Style Sheets
Web › CSS › @viewport
It's primarily used for mobile devices, but is also used by desktop browsers that support features like "snap to edge" (such as Microsoft Edge). Lengths specified as percentages are calculated relative to the initial viewport, which is the viewport before any user agent or authored styles have had an opportunity to adjust the viewport. ...
...escriptors Browser support for @viewport is weak at this time, with support being largely available in Internet Explorer and Edge. Even in those browsers, only a small number of descriptors are available. Browsers will ignore @viewport if they don't support it, and will ignore any descriptors that they don't recognize. ...
...nternet Explorer and Edge. Even in those browsers, only a small number of descriptors are available. Browsers will ignore @viewport if they don't support it, and will ignore any descriptors that they don't recognize. min-width Used in the determination of the width of the viewport when the document is first displayed. max-width Used in the determination of the width of the viewport when the document is first displayed. width A shorthand descriptor for setting both min-width and max-width. min-height Used in the determination of the height of the viewport when the document is first displayed. max-height Used in the determination of the height of the viewport when the document is first displayed. height A shorthand descriptor for setting both min-height and max-height. zoom Sets the ...
...d in the determination of the height of the viewport when the document is first displayed. height A shorthand descriptor for setting both min-height and max-height. zoom Sets the initial zoom factor. min-zoom Sets the minimum zoom factor. max-zoom Sets the maximum zoom factor. user-zoom Controls whether or not the user should be able to change the zoom factor. orientation Controls the document's orientation. viewport-fit Controls the display of the document on non-rectangular displays. Formal syntax @viewport { <group-rule-body> } Examples Setting viewport size, zoom, and orientation @viewport { min-width: 640px; max-width: 800px; } @viewport { zoom: 0.75; min-zoom: 0.5; max-zoom: 0.9; } @viewport { orientation: landscape; } Specifications Specificati...
Using CSS animations - CSS: Cascading Style Sheets
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. ...
...nimation-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, false); element.className = "slidein"; This is pretty standard code; you can get details on how it works in the documentation for eventTarget.addEventListener(). The last thing this code does ...
...animation. Why? Because the animationstart event fires as soon as the animation starts, and in our case, that happens before our code runs. So we'll start the animation ourselves by setting the class of the element to the style that gets animated after the fact. Receiving the events The events get delivered to the listener() function, which is shown below. ...
...It simply looks at the event.type to determine which kind of animation event occurred, then adds an appropriate note to the <ul> (unordered list) we're using to log these events. ...
Using the :target pseudo-class in selectors - CSS: Cascading Style Sheets
When a URL points at a specific piece of a document, it can be difficult for the user to notice. Find out how you can use some simple CSS to draw attention to the target of a URL and improve the user's experience. Picking a Target The pseudo-class :target is used to style the target element of a URL containing a fragment identifier. For example, the URL http://developer.mozilla.org/en/docs/Using_the_:target_selector#example contains the fragment identifier #example. In HTML, identifiers are found as the values of either id or name attributes, since the two share the same namespace. Thus, the example URL would point to the heading "example" in this document. Suppose you wish to style any h2 element that is the target of a URL, but do not want any other kind of element to get a target style. Thi...
...This is done using the same identifying value that is found in the URI. ...
...und in the URI. Thus, to add a border to the #example fragment, we would write: #example:target { border: 1px solid black; } Targeting all elements If the intent is to create a "blanket" style that will apply to all targeted elements, then the universal selector comes in handy: :target { color: red; } Example In the following example, there are five links that point to elements in the same document. Selecting the "First" link, for example, will cause <h1 id="one"> to become the target element. Note that the document may jump to a new scroll position, since target elements are placed on the top of the browser window if possible. <h4 id="one">...</h4> <p id="two">...</p> <div id="three">...</div> <a id="four">...</a> <em id="five">...</em> <a href="#one">First</a> <a href="#two">Second</a>...
...ce target elements are placed on the top of the browser window if possible. <h4 id="one">...</h4> <p id="two">...</p> <div id="three">...</div> <a id="four">...</a> <em id="five">...</em> <a href="#one">First</a> <a href="#two">Second</a> <a href="#three">Third</a> <a href="#four">Fourth</a> <a href="#five">Fifth</a> Conclusion In cases where a fragment identifier points to a portion of the document, readers may become confused about which part of the document they're supposed to be reading. By styling the target of a URI, reader confusion can be reduced or eliminated. See also :target Original Document Information Author(s): Eric Meyer, Standards Evangelist, Netscape Communications Original Copyright Information: Copyright (C) 2001-2003 Netscape. All rights reserved. Note: This ...
Introducing the CSS Cascade - CSS: Cascading Style Sheets
Web › CSS › Cascade
ining descriptors, don't participate in the cascade. In these cases, only the at-rule as a whole participates in the cascade: here, the @font-face identified by its font-family descriptor. If several @font-face rules with the same descriptor are defined, only the most appropriate @font-face, as a whole, is considered. While the declarations contained in most at-rules -- such as those in @media, @document, or @supports -- participate in the cascade, declarations contained in @keyframes don't. As with @font-face, only the at-rule as a whole is selected via the cascade algorithm. Finally, note that @import and @charset obey specific algorithms and aren't affected by the cascade algorithm. Origin of CSS declarations The CSS cascade algorithm's job is to select CSS declarations in order to determin...
...t values for CSS properties. CSS declarations originate from different origins: the User-agent stylesheets, the Author stylesheets, and the User stylesheets. Though style sheets come from these different origins, they overlap in scope; to make this work, the cascade algorithm defines how they interact. User-agent stylesheets The browser has a basic style sheet that gives a default style to any document. These style sheets are named user-agent stylesheets. Some browsers use actual style sheets for this purpose, while others simulate them in code, but the end result is the same. Some browsers let users modify the user-agent stylesheet. Although some constraints on user-agent stylesheets are set by the HTML specification, browsers still have a lot of latitude: that means that significant differen...
...process, Web developers often use a CSS reset style sheet, forcing common properties values to a known state before beginning to make alterations to suit their specific needs. Author stylesheets Author stylesheets are the most common type of style sheet. These are style sheets that define styles as part of the design of a given web page or site. The author of the page defines the styles for the document using one or more stylesheets, which define the look and feel of the website -- its theme. User stylesheets The user (or reader) of the web site can choose to override styles in many browsers using a custom user stylesheet designed to tailor the experience to the user's wishes. Cascading order The cascading algorithm determines how to find the value to apply for each property for each documen...
...en to clear the values of the properties entirely. CSS animations and the cascade CSS animations, using @keyframes at-rules, define animations between states. Keyframes don't cascade, meaning that at any given time CSS takes values from only one single @keyframes, and never mixes multiple ones together. When several keyframes are appropriate, it chooses the latest defined in the most important document, but never combined all together. Example Let's look at an example involving multiple sources of CSS across the various origins; here we have a user agent style sheet, two author style sheets, a user stylesheet, and inline styles within the HTML: User-agent CSS: li { margin-left: 10px } Author CSS 1: li { margin-left: 0 } /* This is a reset */ Author CSS 2: @media screen { li { margin-l...
display - CSS: Cascading Style Sheets
Web › CSS › display
rty sets an element's inner and outer display types. The outer type sets an element's participation in flow layout; the inner type sets the layout of children. Some values of display are fully defined in their own individual specifications; for example the detail of what happens when display: flex is declared is defined in the CSS Flexible Box Model specification. See the table at the end of this document for all of the individual specifications. Syntax The CSS display property is specified using keyword values. Keyword values are grouped into six value categories: .container { display: [ <display-outside> || <display-inside> ] | <display-listitem> | <display-internal> | <display-box> | <display-legacy> ; } Outside <display-outside> These keywords specify the element's outer display ty...
...uch as replaced elements. See Appendix B: Effects of display: contents on Unusual Elements for more details. Due to a bug in browsers this will currently remove the element from the accessibility tree -- screen readers will not look at what's inside. See the Accessibility concerns section below for more details. none Turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist). All descendant elements also have their display turned off. To have an element take up the space that it would normally take, but without actually rendering anything, use the visibility property instead. Legacy <display-legacy> CSS 2 used a single-keyword syntax for the display property, requiring separate keywords for block-level and inlin...
... Specifications S...
... Specifications Specification Status Comment CSS Displ...
font - CSS: Cascading Style Sheets
Web › CSS › font
t used to label icons. menu The system font used in menus (e.g., dropdown menus and menu lists). message-box The system font used in dialog boxes. small-caption The system font used for labeling small controls. status-bar The system font used in window status bars. Prefixed system font keywords Browsers often implement several more, prefixed, keywords: Gecko implements -moz-window, -moz-document, -moz-desktop, -moz-info, -moz-dialog, -moz-button, -moz-pull-down-menu, -moz-list, and -moz-field. Formal definition Initial valueas each of the properties of the shorthand:font-style: normalfont-variant: normalfont-weight: normalfont-stretch: normalfont-size: mediumline-height: normalfont-family: depends on user agentApplies toall elements. It also applies to ::first-letter and ::first-line.
...opInputs, .setPropCont { margin-bottom: 1em; } .curCss { border: none; border-bottom: 1px solid black; text-align: center; width: 80px; } .mandatory { border-bottom-color: red; } .cf:before, .cf:after { content: " "; display: table; } .cf:after { clear: both; } .tar { width: 40px; text-align: right; } .fontfamily { display: inline-block; } JavaScript var textAreas = document.getElementsByClassName("curCss"), shortText = "", getCheckedValue, setCss, getProperties, injectCss; getProperties = function () { shortText = getCheckedValue("font_style") + " " + getCheckedValue("font_variant") + " " + getCheckedValue("font_weight") + " " + getCheckedValue("font_size") + getCheckedValue("line_height") + " " + getChecked...
...perties, injectCss; getProperties = function () { shortText = getCheckedValue("font_style") + " " + getCheckedValue("font_variant") + " " + getCheckedValue("font_weight") + " " + getCheckedValue("font_size") + getCheckedValue("line_height") + " " + getCheckedValue("font_family"); return shortText; } getCheckedValue = function(radio_name) { oRadio = document.forms[0].elements[radio_name]; for (var i = 0; i < oRadio.length; i++) { if(oRadio[i].checked) { var propInput = "input_" + radio_name, curElemName = "input_" + radio_name, curElem = document.getElementById(curElemName); curElem.value = oRadio[i].value; return oRadio[i].value; } } } setCss = function () { getProperties(); injectCss(shortText...
...i < oRadio.length; i++) { if(oRadio[i].checked) { var propInput = "input_" + radio_name, curElemName = "input_" + radio_name, curElem = document.getElementById(curElemName); curElem.value = oRadio[i].value; return oRadio[i].value; } } } setCss = function () { getProperties(); injectCss(shortText); } injectCss = function(cssFragment) { old = document.body.getElementsByTagName("style"); if (old.length > 1) { old[1].parentElement.removeChild(old[1]); } css = document.createElement("style"); css.innerHTML = ".fontShortHand{font: " + cssFragment + "}"; document.body.appendChild(css); } setCss(); Specifications Specification Status Comment CSS Fonts Module Level 3The definition of 'font' in that spec...
writing-mode - CSS: Cascading Style Sheets
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
... 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. ...
...or rtl scripts, content flows vertically from top to bottom. All the glyphs, even those in vertical scripts, are set sideways toward the right. sideways-lr For ltr scripts, content flows vertically from top to bottom. For rtl scripts, content flows vertically from bottom to top. All the glyphs, even those in vertical scripts, are set sideways toward the left. lr Deprecated except for SVG1 documents. For CSS, use horizontal-tb instead. lr-tb Deprecated except for SVG1 documents. For CSS, use horizontal-tb instead. rl Deprecated except for SVG1 documents. For CSS, use horizontal-tb instead. tb Deprecated except for SVG1 documents. For CSS, use vertical-lr instead. tb-lr Deprecated except for SVG1 documents. For CSS, use vertical-lr instead. tb-rl Deprecated except for SVG...
...For CSS, use vertical-rl instead. ...
Ajax - Developer guides
Web › Guide › AJAX
e 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 information in the Ajax model. Documentation Getting Started This article guides you through the Ajax basics and gives you two simple hands-on examples to get you started. Using the XMLHttpRequest API The XMLHttpRequest API is the core of Ajax. This article will explain how to use some Ajax techniques, like: Analyzing and manipulating the response of the server Monitoring the progress of a request Submitting forms and upl...
...ge. See also: Using server-sent events. Pure-Ajax navigation example This article provides a working (minimalist) example of a pure-Ajax website composed only of three pages. Sending and Receiving Binary Data The responseType property of the XMLHttpRequest object can be set to change the expected response type from the server. 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 article will show some Ajax I/O techniques. XML The Extensible Markup Language (XML) is a W3C-recommended general-purpose markup language for creating special-purpose markup languages. It is a simplified subset of SGML, capable of describing man...
...tensible Markup Language (XML) is a W3C-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. ...
... 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 FileReader API lets web applicati...
Web Audio playbackRate explained - Developer guides
The playbackRate property of the <audio> and <video> elements allows us to change the speed, or rate, at which a piece of web audio or video is playing. This article explains playbackRate in detail. playbackRate basics Let's starting by looking at a brief example of playbackRate usage: var myAudio = document.createElement('audio'); myAudio.setAttribute('src','audiofile.mp3'); myAudio.playbackRate = 0.5; Here we create an <audio> element, and set its src to a file of our choice. Next we set playbackRate to 0.5, which represents half normal speed (the playbackRate is a multiplier applied to the original rate.) A complete example Let's create a <video> element first, and set up video and playback rate controls in HTML: <video id="myVideo" controls> <source src="https://udn.realityr...
... Note: Try out this example l...
... Note: Try out this example live, and try adjusting the playback rate contr...
... Note: Try out this example live, and try adjusting the playback rate control to see the effect. defaultPlaybackRat...
Media buffering, seeking, and time ranges - Developer guides
It returns a TimeRanges object, which will tell us which chunks of media have been downloaded. This is usually contiguous but if the user jumps about while media is buffering, it may contain holes. This will work with <audio> or <video>; for now let's consider a simple audio example: <audio id="my-audio" controls src="music.mp3"> </audio> We can access these attributes like so: var myAudio = document.getElementById('my-audio'); var bufferedTimeRanges = myAudio.buffered; TimeRanges Object TimeRanges are a series of non-overlapping ranges of time, with start and stop times. (learn more about TimeRanges). A TimeRanges Object consists of the following properties: length: The number of time ranges in the object. start(index): The start time, in seconds, of a time range. end(index): The en...
...art(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.duration; // display TimeRanges myAudio.addEventListen...
... 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) { document.getElementById("buffered-amount").style.width = (myAudio.buffered.end(myAudi...
....start(myAudio.buffered.length - 1 - i) < myAudio.currentTime) { document.getElementById("buffered-amount").style.width = (myAudio.buffered.end(myAudio.buffered.length - 1 - i) / duration) * 100 + "%"; break; } } } }); myAudio.addEventListener('timeupdate', function() { var duration = myAudio.duration; if (duration > 0) { document.getElementById('progress-amount').style.width = ((myAudio.currentTime / duration)*100) + "%"; } }); } The progress event is fired as data is downloaded, this is a good event to react to if we want to display download or buffering progress. The timeupdate event is fired 4 times a second as the media plays and that's where we increment our playing progress bar. This should give you results...
Challenge solutions - Developer guides
the first paragraph blue too. Solution Change the selector of the new rule to be a tag selector using p: p { color: blue; } The rules for the other colors all have more specific selectors, so they override the blue of the paragraph. Readable CSS Commenting out a rule Challenge Comment out part of your stylesheet, without changing anything else, to make the very first letter of your document red. Solution One way to do this is to put comment delimiters around the rule for .carrot: /* .carrot { color: orange; } */ Text styles Big initial letters Challenge Without changing anything else, make all six initial letters twice the size in the browser's default serif font. Solution Add the following style declaration to the strong rule: font: 200% serif; If you use sepa...
...tin) ") "; counter-increment: headnum; } Boxes Ocean border Challenge Add one rule to your stylesheet, making a wide border all around the oceans in a color that reminds you of the sea. Solution The following rule achieves this effect: ul { border: 10px solid lightblue; width: 100px; } Layout Default image position Fixed image position Challenge Change your sample document, doc2.html, adding this tag to it near the end, just before </BODY>: <IMG id="fixed-pin" src="Yellow-pin.png" alt="Yellow map pin"> Predict where the image will appear in your document. Then refresh your browser to see if you were correct. Solution The image appears to the right of the second list. Challenge Add a rule to your stylesheet that places the image in the top right of your docum...
...} 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. ...
...cify it as marginLeft in JavaScript. The following script achieves the desired result: // JavaScript demonstration function doDemo (button) { var square = document.getElementById("square"); square.style.backgroundColor = "#fa4"; square.style.marginLeft = "20em"; button.setAttribute("disabled", "true"); setTimeout(clearDemo, 2000, button); } function clearDemo (button) { var square = document.getElementById("square"); square.style.backgroundColor = "transparent"; square.style.marginLeft = "0em"; button.removeAttribute("disabled"); } SVG and CSS Change color of inner petals Challenge Change the stylesheet so that the inner petals all turn pink when the mouse pointer is over any one of them, without changing the way the outer petals work. Solution Move the position of...
Mutation events - Developer guides
"DOM Mutation Events Replacement: The Story So Far / Existing Points of Consensus" post to public-webapps). Mutation Observers are the proposed replacement for mutation events in DOM4. They are expected to be included in Firefox 14 and Chrome 18. The practical reasons to avoid the mutation events are performance issues and cross-browser support. Performance Adding DOM mutation listeners to a document profoundly degrades the performance of further DOM modifications to that document (making them 1.5 - 7 times slower!). Moreover, removing the listeners does not reverse the damage. The performance effect is limited to the documents that have the mutation event listeners. Cross-browser support These events are not implemented consistently across different browsers, for example: IE prior to v...
... 9 didn't support the mutation events at all and does not implement some of them correctly in version 9 (for example, DOMNodeInserted) WebKit doesn't support DOMAttrModified (see webkit bug 8191 and the workaround) "mutation name events", i.e. DOMElementNameChanged and DOMAttributeNameChanged are not supported in Firefox (as of version 11), and probably in other browsers as well. ... Dottoro documents browser support for mutation events. Mutation events list The following is a list of all mutation events, as defined in DOM Level 3 Events specification: DOMAttrModified DOMAttributeNameChanged DOMCharacterDataModified DOMElementNameChanged DOMNodeInserted DOMNodeInsertedIntoDocument DOMNodeRemoved DOMNodeRemovedFromDocument DOMSubtreeModified Mutation Observers alternatives examp...
...utation events. ...
...}, false); The event object is passed to the listener in a MutationEvent (see its definition in the specification) for most events, and MutationNameEvent for DOMAtt...
XHTML - Developer guides
Web › Guide › HTML › XHTML
XHTML is a term that was historically used to describe HTML documents written to conform with XML syntax rules. The following example shows an HTML document and corresponding "XHTML" document, and the accompanying HTTP Content-Type headers they should be served with. ...
... XHTML is a term that was historically used to describe HTML documents written to conform with XML syntax rules. The following example shows an HTML document and corresponding "XHTML" document, and the accompanying HTTP Content-Type headers they should be served with. ...
... used to describe HTML documents written to conform with XML syntax rules. The following example shows an HTML document and corresponding "XHTML" document, and the accompanying HTTP Content-Type headers they should be served with. HTML document Content-Type: text/html <!DOCTYPE html> <html lang=en> <head> <meta charset=utf-8> <title>HTML</title> </head> <body> <p>I am a HTML document</p> </body> </html> XHTML document Content-Type: application/xhtml+xml <?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>XHTML</title> </head> <body> <p>I am a XHTML document</p> </body> </html> In practice, very few "XHTML" documents are served over the web with a Content-Type: application/xhtml+xml header. Inst...
...> XHTML document Content-Type: application/xhtml+xml <?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>XHTML</title> </head> <body> <p>I am a XHTML document</p> </body> </html> In practice, very few "XHTML" documents are served over the web with a Content-Type: application/xhtml+xml header. Instead, even though the documents are written to conform to XML syntax rules, they are served with a Content-Type: text/html header -- so browsers parse those documents using HTML parsers rather than XML parsers, which can cause a variety of sometimes-very-surprising problems. The problems are described in more details in the following articles: Beware of XHTML by David Hammond Sending XHTML as text/html Considered Harmful b...
Printing - Developer guides
during the print process). Note: You can also use window.onbeforeprint and window.onafterprint to assign handlers for these events, but using EventTarget.addEventListener() is preferred. Examples Here are some common examples. ...
...y 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></html>'); } </script> </head> <body> <p>To try out the <code>afterprint</code> event, click the link below to open the window to prin...
...g it, you can utilize a hidden <iframe> (see: HTMLIFrameElement), automatically removing it after the user prints its contents. ...
...cript type="text/javascript"> function closePrint () { document.body.removeChild(this.__container__); } function setPrint () { this.contentWindow.__container__ = this; this.contentWindow.onbeforeunload = closePrint; this.contentWindow.onafterprint = closePrint; this.contentWindow.focus(); // Required for IE this.contentWindow.print(); } function printPage (sURL) { var oHiddFrame = document.createElement("iframe"); oHiddFrame.onload = setPrint; oHiddFrame.style.position = "fixed"; oHiddFrame.style.right = "0"; oHiddFrame.style.bottom = "0"; oHiddFrame.style.width = "0"; oHiddFrame.style.height = "0"; oHiddFrame.style.border = "0"; oHiddFrame.src = sURL; document.body.appendChild(oHiddFrame); } </script> </head> <body> <p><span onclick="printPage('externalPage.ht...
User input and controls - Developer guides
I can be found in Managing screen orientation. Fullscreen You might need to present an element of your application (such as a <video>, for example) in fullscreen mode. You can achieve this by calling Element.requestFullscreen() on that element. ...
... Drag & Drop Drag & Drop allows your application's users to click and hold the mouse button down over an element, drag it to another location, and release the mouse button to drop the element there. Here is an example that allows a section of content to be dragged. <div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be d...
...aggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')">? This text <strong>may</strong> be dragged. ?</div> in which we: Set the draggable attribute to true on the element that you wish to make draggable Add a listener for the dragstart event and set the drag data within this listener Note: You can find more information in the MDN Drag & Drop documentation. contentEditable In open web apps any DOM element can be made directly editable using the contenteditable attribute. <div contenteditable="true">? This text can be edited by the user. </div> Note: Compatibility information, examples and other resources can be found in the Content Editable guide. Examples Tracking multiple touch points at a time This example tracks multiple to...
...mple 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 Managing screen orientation Using fullscreen mode Dragging and Dropping Multiple Items Drag Operations Guide Reference MouseEvent KeyboardEvent Touch events Pointer_Lock_API Screen Orientation API Fullscreen API Drag & Drop Content Editable ...
HTML attribute reference - HTML: Hypertext Markup Language
ontrols <audio>, <video> Indicates whether the browser should show playback controls to the user. coords <area> A set of values specifying the coordinates of the hot-spot region. crossorigin <audio>, <img>, <link>, <script>, <video> How the element handles cross-origin requests csp <iframe> Specifies the Content Security Policy that an embedded document must agree to enforce upon itself. data <object> Specifies the URL of the resource. data-* Global attribute Lets you attach custom attributes to an HTML element. datetime <del>, <ins>, <time> Indicates the date and time associated with the element. decoding <img> Indicates the preferred method to decode the image. default <tr...
...er"). WIP: WHATWG PR #3752 list <input> Identifies a list of pre-defined options to suggest to the user. loop <audio>, <bgsound>, <marquee>, <video> Indicates whether the media should start playing from the start when it's finished. low <meter> Indicates the upper bound of the lower range. manifest <html> Specifies the URL of the document's cache manifest. Note: This attribute is obsolete, use <link rel="manifest"> instead. max <input>, <meter>, <progress> Indicates the maximum value allowed. maxlength <input>, <textarea> Defines the maximum number of characters allowed in the element. minlength <input>, <textarea> Defines the minimum number of characters allowed in the element.
...area> Indicates whether this element is required to fill out or not. reversed <ol> Indicates whether the list should be displayed in a descending order instead of a ascending. rows <textarea> Defines the number of rows in a text area. rowspan <td>, <th> Defines the number of rows a table cell should span over. sandbox <iframe> Stops a document loaded in an iframe from using certain features (such as submitting forms or opening new windows). scope <th> Defines the cells that the header test (defined in the th element) relates to. scoped <style> selected <option> Defines a value which will be selected on page load. shape <a>, <area> size <input>, <select> Define...
...e first number if other than 1. step <input> style Global attribute Defines CSS styles which will override styles previously set. summary <table> tabindex Global attribute Overrides the browser's default tab order and follows the one specified instead. target <a>, <area>, <base>, <form> Specifies where to open the linked document (in the case of an <a> element) or where to display the response recieved (in the case of a <form> element) title Global attribute Text to be displayed in a tooltip when hovering over the element. translate Global attribute Specify whether an element's attribute values and the values of its Text node children are to be translated when the page is localized, or whethe...
<button>: The Button element - HTML: Hypertext Markup Language
Web › HTML › Element › button
By default, HTML buttons are presented in a style resembling the platform the user agent runs on, but you can change buttons' appearance with CSS. 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. Content categories Flow content, phrasing content, Interactive content, listed, labelable, and submittable form-associated element, palpable content. ...
...icit ARIA role button Permitted ARIA roles checkbox, link, menuitem, menuitemcheckbox, menuitemradio, option, radio, switch, tab DOM interface HTMLButtonElement Attributes This element's attributes include the global attributes. autofocus HTML5 This Boolean attribute specifies that the button should have input focus when the page loads. Only one element in a document can have this attribute. autocomplete This attribute on a <button> is nonstandard and Firefox-specific. Unlike other browsers, Firefox persists the dynamic disabled state of a <button> across page loads. Setting autocomplete="off" on the button disables this feature; see bug 654072. disabled This Boolean attribute prevents the user from interacting with the button: it cannot be pressed or...
...tribute prevents the user from interacting with the button: it cannot be pressed or focused. Firefox, unlike other browsers, persists the dynamic disabled state of a <button> across page loads. Use the autocomplete attribute to control this feature. form HTML5 The <form> element to associate the button with (its form owner). The value of this attribute must be the id of a <form> in the same document. (If this attribute is not set, the <button> is associated with its ancestor <form> element, if any.) This attribute lets you associate <button> elements to <form>s anywhere in the document, not just inside a <form>. It can also override an ancestor <form> element. formaction HTML5 The URL that processes the information submitted by the button. Overrides the action attribute of the button's fo...
...tyle than <input> elements. You can add inner HTML content (think <i>, <br>, or even <img>), and use ::after and ::before pseudo-elements for complex rendering. If your buttons are not for submitting form data to a server, be sure to set their type attribute to button. Otherwise they will try to submit form data and to load the (nonexistent) response, possibly destroying the current state of the document. Example <button name="button">Press me</button> Accessibility concerns Icon buttons Buttons that only show an icon to represent do not have an accessible name. Accessible names provide information for assistive technology, such as screen readers, to access when they parse the document and generate an accessibility tree. Assistive technology then uses the accessibility tree to navigate an...
<input type="password"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › password
nimum 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 expression is applied and this attribute is ignored completely. Tip: U...
...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. ...
...length="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. HTML <label for="userPassword">Password: </label> <input id="userPassword" type="password" size="12"> <button id="selectAll">Select All</button> JavaScript document.getElementById("selectAll").onclick = function() { document.getElementById("userPassword").select(); } Result You can also use selectionStart and selectionEnd to get (or set) what range of characters in the control are currently selected, and selectionDirection to know which direction selection occurred in (or will be extended in, depending on your platform; see its documentation for an explanation). However, given that the text is obscured, the usefu...
...s control must have a value. Finally, autocomplete is set to off to avoid password managers and session restore features trying to set its value, since this isn't a password at all. JavaScript This is just some simple code to display the entered SSN onscreen so you can see it. Obviously this defeats the purpose of a password field, but it's helpful for experimenting with the pattern. var ssn = document.getElementById("ssn"); var current = document.getElementById("current"); ssn.oninput = function(event) { current.innerHTML = ssn.value; } Result Specifications Specification Status Comment HTML Living StandardThe definition of '<input type="password">' in that specification. Living Standard Initial definition HTML 5.1The definition of '<input typ...
<input type="tel"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › tel
ion placeholder An example value to display inside the field when it has no value readonly A Boolean attribute which, if present, indicates that the field's contents should not be user-editable size The number of characters wide the input field should be onscreen list The values of the list attribute is the id of a <datalist> element located in the same document. The <datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. maxlength The maximum number of characters (as UTF-16 code units) the use...
...e 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 expression is applied and this attribute is ignored completely. Tip: U...
...part of number"> <span class="validity"></span> </span> </div> <div> <button>Submit</button> </div> </form> The JavaScript is relatively simple -- it contains an onchange event handler that, when the <select> value is changed, updates the <input> element's pattern, placeholder, and aria-label to suit the format of telephone numbers in that country/territory. ...
...n> </span> </div> <div> <button>Submit</button> </div> </form> The JavaScript is relatively simple -- it contains an onchange event handler that, when the <select> value is changed, updates the <input> element's pattern, placeholder, and aria-label to suit the format of telephone numbers in that country/territory. ...
<kbd>: The Keyboard Input element - HTML: Hypertext Markup Language
Web › HTML › Element › kbd
he names of menus and menu items, or the names of buttons displayed on the screen. See the example under Representing onscreen input options below. You can define a custom style to override the browser's default font selection for the <kbd> element, although the user's preferences may potentially override your CSS. Examples Basic example <p>Use the command <kbd>help mycommand</kbd> to view documentation for the command "mycommand".</p> Representing keystrokes within an input To describe an input comprised of multiple keystrokes, you can nest multiple <kbd> elements, with an outer <kbd> element representing the overall input and each individual keystroke or component of the input enclosed within its own <kbd>. Unstyled First, let's look at what this looks like as just plain HTML. HTM...
...".</p> Representing keystrokes within an input To describe an input comprised of multiple keystrokes, you can nest multiple <kbd> elements, with an outer <kbd> element representing the overall input and each individual keystroke or component of the input enclosed within its own <kbd>. Unstyled First, let's look at what this looks like as just plain HTML. HTML <p>You can also create a new document using the keyboard shortcut <kbd><kbd>Ctrl</kbd>+<kbd>N</kbd></kbd>.</p> This wraps the entire key sequence in an outer <kbd> element, then each individual key within its own, in order to denote the components of the sequence. Note: You don't need to do all this wrapping; you can choose to simplify it by leaving out the external <kbd> element. In other words, simplifying this to just <kbd>Ctrl...
... <p>If a syntax error occurs, the tool will output the initial command you typed for your review:</p> <blockquote> <samp><kbd>custom-git ad...
...r your review:</p> <blockquote> <samp><kbd>custom-git ad my-new-file.cpp</kbd></samp> </blockquote> Representing onscreen input options Nesting a <samp> element inside a <kbd> element represents input which is based on text presented by the system, such as the names of menus and menu items, or the names of buttons displayed on the screen. For example, you can explain how to choose the "New Document" option in the "File" menu using HTML that looks like this: <p>To create a new file, choose the menu option <kbd><kbd><samp>File</samp></kbd>=><kbd><samp>New Document</samp></kbd></kbd>.</p> <p>Don't forget to click the <kbd><samp>OK</samp></kbd> button to confirm once you've entered the name of the new file.</p> This does some interesting nesting. For the menu option description, the entire i...
<object> - HTML: Hypertext Markup Language
Web › HTML › Element › object
te, interactive content; listed, submittable form-associated element. Permitted content zero or more <param> elements, then transparent. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts embedded content. Implicit ARIA role No corresponding role Permitted ARIA roles application, document, image DOM interface HTMLObjectElement Attributes This element includes the global attributes. archiveHTML 4 onlyObsolete since HTML5 A space-separated list of URIs for archives of resources for the object. borderDeprecated since HTML4.01Obsolete since HTML5 The width of a border around the control, in pixels. classidHTML 4 onlyObsolete since HTML5 The URI of the objec...
...since HTML5 The width of a border around the control, in pixels. classidHTML 4 onlyObsolete since HTML5 The URI of the object's implementation. It can be used together with, or in place of, the data attribute. codebaseHTML 4 onlyObsolete since HTML5 The base path used to resolve relative URIs specified by classid, data, or archive. If not specified, the default is the base URI of the current document. codetypeHTML 4 onlyObsolete since HTML5 The content type of the data specified by classid. data The address of the resource as a valid URL. At least one of data and type must be defined. declareHTML 4 onlyObsolete since HTML5 The presence of this Boolean attribute makes this element a declaration only. The object must be instantiated by a subsequent <object> element. In HTML5, repeat the <...
...presence of this Boolean attribute makes this element a declaration only. The object must be instantiated by a subsequent <object> element. In HTML5, repeat the <object> element completely each that that the resource is reused. formHTML5 The form element, if any, that the object element is associated with (its form owner). The value of the attribute must be an ID of a <form> element in the same document. height The height of the displayed resource, in CSS pixels. -- (Absolute values only. NO percentages) name The name of valid browsing context (HTML5), or the name of the control (HTML 4). standbyHTML 4 onlyObsolete since HTML5 A message that the browser can show while loading the object's implementation and data. tabindexHTML 4 onlyObsolete since HTML5 The position of the element in the ...
...source, in CSS pixels. -- (Absolute values only. NO percentages) name The name of valid browsing context (HTML5), or the name of the control (HTML 4). standbyHTML 4 onlyObsolete since HTML5 A message that the browser can show while loading the object's implementation and data. tabindexHTML 4 onlyObsolete since HTML5 The position of the element in the tabbing navigation order for the current document. type The content type of the resource specified by data. At least one of data and type must be defined. typemustmatchHTML5 This Boolean attribute indicates if the type attribute and the actual content type of the resource must match to be used. usemap A hash-name reference to a <map> element; that is a '#' followed by the value of a name of a map element. width The width of the display r...
itemprop - HTML: Hypertext Markup Language
a property can also introduce multiple properties at once, to avoid duplication when some of the properties have the same value. An item with two properties, "favorite-color" and "favorite-fruit", both set to the value "orange" <div itemscope> <span itemprop="favorite-color favorite-fruit">orange</span> </div> Note: There is no relationship between the microdata and the content of the document where the microdata is marked up. Same structured data marked up in two different ways There is no semantic difference between the following two examples <figure> <img src="castle.jpeg"> <figcaption><span itemscope><span itemprop="name">The Castle</span></span> (1986)</figcaption> </figure> <span itemscope><meta itemprop="name" content="The Castle"></span> <figure> <img src...
...<span itemscope><meta itemprop="name" content="The Castle"></span> <figure> <img src="castle.jpeg"> <figcaption>The Castle (1986)</figcaption> </figure> Both have a figure with a caption, and both, completely unrelated to the figure, have an item with a name-value pair with the name "name" and the value "The Castle". The only difference is that if the user drags the figcaption out of the document, the item will be included in the drag-and-drop data. The image associated with the item won't be included. Names and values A property is an unordered set of unique tokens that are case-sensitive and represent the name-value pairs. The property value must have at least one token. In the example below, each data cell is a token. Names examples Item itemprop name item...
...as an itemscope attribute The value is the item created by the element. ...
...The value is the resulting URL string that results from parsing the value of the element's src attribute relative to the node document (part of the Microdata DOM API) of the element at the time the attribute is set If the element is an a, area, or link element The value is the resulting URL string that results from parsing the value of the element's href attribute relative to the node document of the element at the time the attribute is set If the element is an object element The value is the resulting URL string that results from parsing the value of the element's data attribute relative to the node document of the element at the time the attribute is set If the element is a data element The value is the value of the element's value attribute If the eleme...
Quirks Mode and Standards Mode - HTML: Hypertext Markup Language
Navigator 4 and Internet Explorer 5. This is essential in order to support websites that were built before the widespread adoption of web standards. In full standards mode, the behavior is (hopefully) the behavior described by the HTML and CSS specifications. In almost standards mode, there are only a very small number of quirks implemented. How do browsers determine which mode to use? For HTML documents, browsers use a DOCTYPE in the beginning of the document to decide whether to handle it in quirks mode or standards mode. To ensure that your page uses full standards mode, make sure that your page has a DOCTYPE like in this example: <!DOCTYPE html> <html lang="en"> <head> <meta charset=UTF-8> <title>Hello World!</title> </head> <body> </body> </html> The DOCTYPE shown in the e...
...the HTML standard recommended other variants, but all existing browsers today will use full standards mode for this DOCTYPE, even the dated Internet Explorer 6. There are no valid reasons to use a more complicated DOCTYPE. If you do use another DOCTYPE, you may risk choosing one which triggers almost standards mode or quirks mode. Make sure you put the DOCTYPE right at the beginning of your HTML document. Anything before the DOCTYPE, like a comment or an XML declaration will trigger quirks mode in Internet Explorer 9 and older. In HTML5, the only purpose of the DOCTYPE is to activate full standards mode. Older versions of the HTML standard gave additional meaning to the DOCTYPE, but no browser has ever used the DOCTYPE for anything other than switching between quirks mode and standards mode. Se...
...nal meaning to the DOCTYPE, but no browser has ever used the DOCTYPE for anything other than switching between quirks mode and standards mode. See also a detailed description of when different browsers choose various modes. XHTML If you serve your page as XHTML using the application/xhtml+xml MIME type in the Content-Type HTTP header, you do not need a DOCTYPE to enable standards mode, as such documents always use full standards mode. Note however that serving your pages as application/xhtml+xml will cause Internet Explorer 8 to show a download dialog box for an unknown format instead of displaying your page, as the first version of Internet Explorer with support for XHTML is Internet Explorer 9. If you serve XHTML-like content using the text/html MIME type, browsers will read it as HTML, and ...
... the first version of Internet Explorer with support for XHTML is Internet Explorer 9. If you serve XHTML-like content using the text/html MIME type, browsers will read it as HTML, and you will need the DOCTYPE to use standards mode. How do I see which mode is used? In Firefox, select View Page Info from the context menu, and look for Render Mode. In Internet Explorer, press F12, and look for Document Mode. What are the differences between the modes? See the list of quirks and almost standards mode for the differences between the modes. ...
Data URLs - HTTP
They were formerly known as "data URIs" until that name was retired by the WHATWG. Note: Data URLs are treated as unique opaque origins by modern browsers, rather than inheriting the origin of the settings object responsible for the navigation. Syntax Data URLs are composed of four parts: a prefix (data:), a MIME type indicating the type of data, an optional base64 token if non-textual, and the data itself: data:[<mediatype>][;base64],<data> The mediatype is a MIME type string, such as 'image/jpeg' for a JPEG image file. ...
...a:), a MIME type indicating the type of data, an optional base64 token if non-textual, and the data itself: data:[<mediatype>][;base64],<data> The mediatype is a MIME type string, such as 'image/jpeg' for a JPEG image file. If omitted, defaults to text/plain;charset=US-ASCII If the data is textual, you can simply embed the text (using the appropriate entities or escapes based on the enclosing document's type). Otherwise, you can specify base64 to embed base64-encoded binary data. You can find more info on MIME types here and here. A few examples: data:,Hello%2C%20World! Simple text/plain data. Note the use of percent-encoding (URL-encoding) for the quote and space characters. Also, for CSV data (MIME type "text/csv"), percent-encoding is needed to preserve the line endings that delimit ro...
...%20World! Simple text/plain data. Note the use of percent-encoding (URL-encoding) for the quote and space characters. 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 charact...
... HTML resource whose contents are: lots of text...<p><a name="bottom">bottom</a>?arg=val Syntax The format for data URLs is very simple, but it's easy to forget to put a comma before the "data" segment, or to incorrectly encode the data into base64 format. Formatting in HTML A data URL provides a file within a file, which can potentially be very wide relative to the width of the enclosing document. As a URL, the data should be formatable with whitespace (linefeed, tab, or spaces), but there are practical issues that arise when using base64 encoding. Length limitations Although Firefox supports data URLs of essentially unlimited length, browsers are not required to support any particular maximum length of data. For example, the Opera 11 browser limited URLs to 65535 characters long which ...
Identifying resources on the Web - HTTP
Each resource is identified by a Uniform Resource Identifier (URI) used throughout HTTP for identifying resources. The identity and the location of resources on the Web are mostly given by a single URL (Uniform Resource Locator, a kind of URI). There are sometimes reasons identity and location are not given by the same URI: HTTP uses a specific HTTP header, Alt-Svc when the resource requested wants the client to access it at another location. ...
...eveloper.mozilla.org/docs/Learn/ https://developer.mozilla.org/search?q=URL Any of those URLs can be typed into your browser's address bar to tell it to load the associated page (resource). A URL is composed of different parts, some mandatory and others are optional. A more complex example might look like this: http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument URNs A Uniform Resource Name (URN) is a URI that identifies a resource by name in a particular namespace. urn:isbn:9780141036144 urn:ietf:rfc:7230 The two URNs correspond to the book Nineteen Eighty-Four by George Orwell, the IETF specification 7230, Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing. Syntax of Uniform Resource Identifiers (URIs) Scheme or protocol ...
...o the Web server. Those parameters are a list of key/value pairs separated with the & symbol. The Web server can use those parameters to do extra stuff before returning the resource to the user. Each Web server has its own rules regarding parameters, and the only reliable way to know how a specific Web server is handling parameters is by asking the Web server owner. Fragment #SomewhereInTheDocument is an anchor to another part of the resource itself. An anchor represents a sort of "bookmark" inside the resource, giving the browser the directions to show the content located at that "bookmarked" spot. On an HTML document, for example, the browser will scroll to the point where the anchor is defined; on a video or audio document, the browser will try to go to the time the anchor represents. It...
...Increasingly, browsers are removing support for using FTP to load subresources, for security reasons. FTP is still acceptable at the top level (such as typed directly into the browser's URL bar, or the target of a link), although some browsers may delegate loading FTP content to another application. ...
Using Feature Policy - HTTP
Feature Policy allows you to control which origins can use which features, both in the top-level page and in embedded frames. Essentially, you write a policy, which is an allowed list of origins for each feature. For every feature controlled by Feature Policy, the feature is only enabled in the current document or frame if its origin matches the allowed list of origins. For each policy-controlled feature, the browser maintains a list of origins for which the feature is enabled, known as an allowlist. If you do not specify a policy for a feature, then a default allowlist will be used. The default allowlist is specific to each feature. The Feature-Policy header is still in an experimental state, and is subject to change at any time. Be wary of this when implementing Feature Policy on your webs...
...icy A policy is described using a set of individual policy directives. A policy directive is a combination of a defined feature name, and an allowlist of origins that can use the feature. Features within a policy are separated by semicolons. allowlist An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': T...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Specifying your policy Feature Policy provides two ways to specify policies to control features: The Feature-Policy HTTP header. The allow attribute on <iframe>s. The primary difference between the HTTP header and the allow attribute is that the allow attribute only controls features...
...the same time by specifying a semicolon-separated list of policy directives. For example, this blocks the <iframe> from using the camera and microphone: <iframe allow="camera 'none'; microphone 'none'"> Inheritance of policy for embedded content Scripts inherit the policy of their browsing context, regardless of their origin. That means that top-level scripts inherit the policy from the main document. All iframes inherit the policy of their parent page. If the iframe has an allow attribute, the policies of the parent page and the allow attribute are combined, using the most restrictive subset. For an iframe to have a feature enabled, the origin must be in the allowlist for both the parent page and the allow attribute. Disabling a feature in a policy is a one-way toggle. If a feature has bee...
Content-Language - HTTP
The Content-Language entity header is used to describe the language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language. For example, if "Content-Language: de-DE" is set, it says that the document is intended for German language speakers (however, it doesn't indicate the document is written in German. For example, it might be written in English as part of a language course for German speakers. If you want to indicate which language the document is written in, use the lang attribute instead). If no Content-Language is specified, the default is that the content is intended for all language audiences. Multiple language tags are also possible, as well as applying the Content-Language header to various media types and not only to tex...
... Header type Entity header Forbidden header name no CORS-safelisted response header yes CORS-safelisted request header yes, with the additional restriction that values can only be 0-9, A-Z, a-z, space or *,-.;=. ...
...ted languages (e.g., "en" = English), which is optionally followed by a series of subtags that refine or narrow that language's range (e.g., "en-CA" = the variety of English as communicated in Canada). Note: Language tags are formaly defined in RFC 5646, which rely on the ISO 639 standard (quite often the ISO 639-1 code list) for language codes to be used. ...
...anguage's range (e.g., "en-CA" = the variety of English as communicated in Canada). Note: Language tags are formaly defined in RFC 5646, which rely on the ISO 639 standard (quite often the ISO 639-1 code list) for language codes to be used. Examples Indicating the language a document is written in The global lang attribute is used on HTML elements to indicate the language of an entire HTML document or parts of it. <html lang="de"> Do not use this meta element like this for stating a document language: <!-- /!\ This is bad practice --> <meta http-equiv="content-language" content="de"> Indicating a target audience for a resource The Content-Language header is used to specify the intended audience of the page, and can indicate that this is more than one language. Content-Language: de, e...
CSP: base-uri - HTTP
If this value is absent, then any URI is allowed. If this directive is absent, the user agent will use the value in the <base> element. CSP version 2 Directive type Document directive default-src fallback No. Not setting this allows any URL. ...
...Not setting this allows any URL. ...
... as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
...urity-Policy "base-uri 'self'"; </IfModule> Nginx configuration add_header Content-Security-Policy "base-uri 'self';" Violation case Since your domain isn't example.com, a <base> element with its href set to https://example.com will result in a CSP violation. <meta http-equiv="Content-Security-Policy" content="base-uri 'self'"> <base href="https://example.com/"> // Error: Refused to set the document's base URI to 'https://example.com/' // because it violates the following Content Security Policy // directive: "base-uri 'self'" Specifications Specification Status Comment Content Security Policy Level 3The definition of 'base-uri' in that specification. Working Draft No changes. Content Security Policy Level 2The definition of 'base-uri' in that specifi...
CSP: navigate-to - HTTP
Note: If the form-action directive is present, the navigate-to directive will not act on navigations that are form submissions. CSP version 3 Directive type Navigation directive default-src fallback No. Not setting this allows anything. ...
... Note: If the form-action directive is present, the navigate-to directive will not act on navigations that are form submissions. CSP version 3 Directive type Navigation directive default-src fallback No. Not setting this allows anything. ...
... Note: If the form-action directive is present, the navigate-to directive will not act on navigations that are form submissions. CSP version 3 Directive type Navigation directive default-src fallback No. Not setting this allows anything. ...
... as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
Feature-Policy: fullscreen - HTTP
This directive allows or prevents cross-origin frames from using fullscreen mode. This includes same-origin frames. If both this directive (i.e. via the allow attribute) and the allowfullscreen attribute are present on an <iframe> element, this directive takes precedence. ...
...akes precedence. There was a bug whereby the fullscreen directive didn't work unless the allowfullscreen attribute was also present, but this has been fixed as of Firefox 80 (bug 1608358). Syntax Feature-Policy: fullscreen <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': T...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The default value is 'self'. Examples General example SecureCorp Inc. wants to disable the Fullscreen API within all browsing contexts except for its own origin and those whose origin is https://example.com. It can do so by delivering the following HTTP response header t...
...for a specific <iframe>. It can do so by delivering the following HTTP response header to define a feature policy: Feature-Policy: fullscreen 'self' Then include an allow attribute on the <iframe> element: <iframe src="https://other.com/videoplayer" allow="fullscreen"></iframe> iframe attributes can selectively enable features in certain frames, and not in others, even if those frames contain documents from the same origin. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. Fullscreen APIThe definition of 'Fullscreen' in that specification. Editor's Draft Defines the fullscreen policy. ...
Feature-Policy: geolocation - HTTP
The HTTP Feature-Policy header geolocation directive controls whether the current document is allowed to use the Geolocation Interface. When this policy is enabled, calls to getCurrentPosition() and watchPosition() will cause those functions' callbacks to be invoked with a PositionError code of PERMISSION_DENIED. By default, the Geolocation API can be used within top-level documents and their same-origin child frames. This directive allows or prevents cross-origin frames from accessing geolocation. This includes same-origin frames. ...
...n be used within top-level documents and their same-origin child frames. This directive allows or prevents cross-origin frames from accessing geolocation. This includes same-origin frames. Syntax Feature-Policy: geolocation <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': T...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. The default value is 'self'. Examples General example SecureCorp Inc. wants to disable the Geolocation API within all browsing contexts except for its own origin and those whose origin is https://example.com. It can do so by delivering the following HTTP response header to define a featur...
...xcept for a specific <iframe>. It can do so by delivering the following HTTP response header to define a feature policy: Feature-Policy: geolocation 'self' Then include an allow attribute on the <iframe> element: <iframe src="https://other.com/map" allow="geolocation"></iframe> iframe attributes can selectively enable features in certain frames, and not in others, even if those frames contain documents from the same origin. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Referrer-Policy - HTTP
TP->HTTP, HTTPS->HTTPS) or improves (HTTP->HTTPS), but isn't sent to less secure destinations (HTTPS->HTTP). There is effort from browsers in moving to a stricter default value, namely strict-origin-when-cross-origin (see https://github.com/whatwg/fetch/pull/952), consider using this value (or a stricter one), if possible, when changing the Referrer-Policy. origin Only send the origin of the document as the referrer. For example, a document at https://example.com/page.html will send the referrer https://example.com/. origin-when-cross-origin Send the origin, path, and query string when performing a same-origin request, but only send the origin of the document for other cases. same-origin A referrer will be sent for same-site origins, but cross-origin requests will send no referrer inform...
...://example.com/page.html will send the referrer https://example.com/. origin-when-cross-origin Send the origin, path, and query string when performing a same-origin request, but only send the origin of the document for other cases. same-origin A referrer will be sent for same-site origins, but cross-origin requests will send no referrer information. strict-origin Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS->HTTPS), but don't send it to a less secure destination (HTTPS->HTTP). strict-origin-when-cross-origin Send the origin, path, and querystring when performing a same-origin request, only send the origin when the protocol security level stays the same while performing a cross-origin request (HTTPS->HTTPS), and send no header t...
...HTTP). unsafe-url Send the origin, path, and query string when performing any request, regardless of security. This policy will leak potentially-private information from HTTPS resource URLs to insecure origins. Carefully consider the impact of this setting. Integration with HTML You can also set referrer policies inside HTML. ...
... <a href="http://example.com" rel="noreferrer"> Integration with CSS CSS can fetch resources referenced from stylesheets. These resources follow a referrer policy as well: External CSS stylesheets use the default policy (no-referrer-when-downgrade), unless it's overwritten via a Referrer-Policy HTTP header on the CSS stylesheet's response. For <style> elements or style attributes, the owner document's referrer policy is used. Examples Policy Document Navigation to Referrer no-referrer https://example.com/page anywhere (no referrer) no-referrer-when-downgrade https://example.com/page https://example.com/otherpage https://example.com/page https://mozilla.org https://example.com/page http://example.org (no refe...
Planned changes to shared memory - JavaScript
s to create SharedArrayBuffer objects again, but changes are needed in order to be use these across threads (i.e., postMessage() for SharedArrayBuffer objects throws by default). These changes provide further isolation between sites and help reduce the impact of attacks with high-resolution timers, which can be created with shared memory. ...
...dArrayBuffer objects throws by default). These changes provide further isolation between sites and help reduce the impact of attacks with high-resolution timers, which can be created with shared memory. Starting with Firefox 79, the features described in this document are enabled by default. Chrome intends to implement similar restrictions. New HTTP header bonanza As a baseline requirement, documents will need to be in a secure context. ...
... further isolation between sites and help reduce the impact of attacks with high-resolution timers, which can be created with shared memory. Starting with Firefox 79, the features described in this document are enabled by default. Chrome intends to implement similar restrictions. New HTTP header bonanza As a baseline requirement, documents will need to be in a secure context. ...
...op-level documents, two headers will need to be set: Cross-Origin-Opener-Policy with same-origin as value (protects your origin from attackers) Cross-Origin-Embedder-Policy with require-corp as value (protects victims from your origin) With these two headers set, postMessage() will no longer throw for SharedArrayBuffer objects and shared memory across threads is therefore available. Nested documents and dedicated workers will need to set the Cross-Origin-Embedder-Policy header as well with the same value. No further changes are needed for same-origin nested documents and subresources. Same-site (but cross-origin) nested documents and subresources will need to set the Cross-Origin-Resource-Policy header with same-site as value. And their cross-origin (and cross-site) counterparts need to set...
Property accessors - JavaScript
s", 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'; // SyntaxError console.log(object.1); // SyntaxError Here, the method named createElement is retrieved from document and is called. document.createElement('pre') If you use a method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave white-space(s) before the dot preceding the method call, so that the dot is not interpreted as a decimal point. 77 .toExponential() // or 77 .toExponential() // or ;(77).toExponential() // or 77..toExponential() // or 77.0.toExp...
...) // or 77..toExponential() // or 77.0.toExponential() // because 77. === 77.0, no ambiguity Bracket notation In the object[property_name] syntax, the property_name is just a string or Symbol. So, it can be any string, including '1foo', '!bar!', or even ' ' (a space). const variable = object[property_name] object[property_name] = value; This does the exact same thing as the previous example. document['createElement']('pre') A space before bracket notation is allowed. document ['createElement']('pre') Property names Property names are string or Symbol. 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 ...
... is not fixed in a method. Put another way, this does not necessarily refer to the object containing a method. Instead, this is "passed" by the function call. See method binding. Examples Bracket notation vs. eval JavaScript novices often make the mistake of using eval() where the bracket notation can be used instead. For example, the following syntax is often seen in many scripts. ...
...acket notation can be used instead. 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. Also, strFormControl would have to hold an identifier, which is not required for names and ids of form controls. It is better to use bracket notation instead: x = document.forms['form_name'].elements[strFormControl].value Specifications Specification ECMAScript (ECMA-262)The definition of 'Property Accessors' in that specification. ...
Performance fundamentals - Web Performance
What is performance? Ultimately, user-perceived performance is the only performance that matters. Users provide inputs to the system through touch, movement, and speech. In return, they perceive outputs through sight, touch, and hearing. Performance is the quality of system outputs in response to user inputs. All other things being equal, code optimized for some target besides user-perceived performance (hereafter UPP) loses when competing against code optimized for UPP. ...
...telligently allocating memory to user state is an important concern that we go over in more detail below. Power usage The final metric discussed here is power usage. Like memory usage, users perceive power usage only indirectly, by how long their devices can maintain all other UPP goals. In service of meeting UPP goals, the system must use only the minimum power required. The remainder of this document will discuss performance in terms of these metrics. Platform performance optimizations 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 ...
...The critical path is exactly and only the code that must run to produce the event. For example, to paint an application's first frame that comprises visually some HTML and CSS to style that HTML: The HTML must be parsed The DOM for that HTML must be constructed Resources like images in that part of the DOM have to be loaded and decoded The CSS styles must be applied to that DOM The styled document has to be reflowed Nowhere in that list is "load the 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 simpl...
...efficient data structures and ensure resources like images are optimized well. Modern CPUs can enter a lower-power mode when mostly idle. Applications that constantly fire timers or keep unnecessary animations running prevent CPUs from entering low-power mode. Power-efficient applications shouldn't do that. When applications are sent to the background, a visibilitychange event is fired on their documents. This event is a developer's friend; applications should listen for it. Applications that drop as many loaded resources as possible when sent to the background use less memory and are less likely discarded, in the case of Firefox OS (see the note below). This in turn means they "start up" faster (since they are already running) and have better UPP. Specific coding tips for application performan...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
tifications -- they can work without push, but are very useful when combined with them. Let's look at them in isolation to begin with. Request permission To show a notification, we have to request permission to do so first. Instead of showing the notification immediately though, best practice dictates that we should show the popup when the user requests it by clicking on a button: var button = document.getElementById("notifications"); button.addEventListener('click', function(e) { Notification.requestPermission().then(function(result) { if(result === 'granted') { randomNotification(); } }); }); This shows a popup using the operating system's own notifications service: When the user confirms to receive notifications, the app can then show them. The result ...
...idKey }); Now let's move to the subscription part -- the app first sends the subscription details as JSON to the server using Fetch. ...
...he subscription details as JSON to the server using Fetch. ...
...ster', { method: 'post', headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ subscription: subscription }), }); Then the GlobalEventHandlers.onclick function on the Subscribe button is defined: document.getElementById('doIt').onclick = function() { const payload = document.getElementById('notification-payload').value; const delay = document.getElementById('notification-delay').value; const ttl = document.getElementById('notification-ttl').value; fetch('./sendNotification', { method: 'post', headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ subscription: subscription, payload: payload, delay: delay, ttl: ttl, ...
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
Modern browsers support using SVG within CSS styles to apply graphical effects to HTML content. You may specify SVG in styles either within the same document or an external style sheet. There are 3 properties you can use: mask, clip-path, and filter. Note: References to SVG in external files must be to the same origin as the referencing document. Using embedded SVG To apply an SVG effect using CSS styles, you first need to create the CSS style that references the SVG to apply. <style>p { mask: url(#my-mask); }</style> In the above example, all paragraphs are masked by an SVG <mask> with the ID my-mask. ...
...edded SVG To apply an SVG effect using CSS styles, you first need to create the CSS style that references the SVG to apply. <style>p { mask: url(#my-mask); }</style> In the above example, all paragraphs are masked by an SVG <mask> with the ID my-mask. ...
...pping area made of a circle and rectangle, assigns it the ID #clipping-path-1, then references it in the CSS. The clip path can be assigned to any element with the target class. You can make changes to the SVG in real time and see them immediately affect the rendering of the HTML. For example, you can resize the circle in the clip path established above: function toggleRadius() { var circle = document.getElementById("circle"); circle.r.baseVal.value = 0.40 - circle.r.baseVal.value; } Example: Filtering This demonstrates applying a filter to HTML content using SVG. It establishes several filters, which are applied with CSS to three elements in both the normal and mouse hover states. <p class="target" style="background: lime;"> Lorem ipsum dolor sit amet, consectetur adipisicing elit...
... elements combined with HTML you can make a variety of different text effects. You can rotate the text: <svg height="60" width="200"> <text x="0" y="15" fill="blue" transform="rotate(30 20,50)">Example text</text> </svg> Using external references SVG used for clipping, masking, and filtering can be loaded from an external source, as long as that source comes from the same origin as the HTML document to which it's applied. For example, if your CSS is in a file named default.css, it can look like this: .target { clip-path: url(resources.svg#c1); } The SVG is then imported from a file named resources.svg, using the clip path with the ID c1. ...
href - SVG: Scalable Vector Graphics
Web › SVG › Attribute › href
e target of this animation element and which therefore will be modified over time. The URL must point to exactly one target element which is capable of being the target of the given animation element. If the URL points to multiple target elements, if the given target element is not capable of being a target of the given animation element, or if the given target element is not part of the current document, then the animation element will not affect any target element. However, the animation element will still operate normally with regard to its timing properties. Specifically, TimeEvents are dispatched and the animation element can be used as syncbase in an identical fashion to when the URL refers to a valid target element. If the href attribute or the deprecated xlink:href attribute is not provi...
... None Animatable No discard For <discard>, href defines a URL referring the target element to discard. See the definition of href on animation elements for details on identifying a target element. Note: Unlike other animation elements, the <discard> element does not support the deprecated xlink:href attribute. Note that if the target element is not part of the current SVG document fragment, then whether the target element will be removed or not is defined by the host language. If the href attribute is not provided, then the target element will be the immediate parent element of the <discard> element. Value <url> Default value None Animatable No feImage For <feImage>, href defines a URL referring to an image resource or to an el...
... Value <url> Default value None Animatable Yes mpath For <mpath>, href defines a URL referring to the <path> element or basic shape which defines the motion path. Value <url> Default value None Animatable No pattern For <pattern>, href defines a URL referring to a different <pattern> element within the current SVG document. Any attributes which are defined on the referenced element which are not defined on this element are inherited by this element. If this element has no children, and the referenced element does (possibly due to its own href attribute), then this element inherits the children from the referenced element. Inheritance can be indirect to an arbitrary level; thus, if the referenced element inherits at...
... textPath For <textPath>, href defines a URL referring to the <path> element or basic shape onto which the text will be rendered if no path attribute is provided. On the <textPath> element, the href attribute is animatable. Value <url> Default value None Animatable Yes use For <use>, href defines a URL referring to an element or fragment within an SVG document to be cloned. The <use> element can reference an entire SVG document by specifying an href value without a fragment. Such references are taken to be referring to the root element of the referenced document. Value <url> Default value None Animatable Yes Specifications Specification Status Comment Scalable Vector Graphics (SV...
textLength - SVG: Scalable Vector Graphics
pan 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. ...
...> 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. ...
...rol 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. ...
... 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. ...
<foreignObject> - SVG: Scalable Vector Graphics
Sed mollis mollis mi ut ultricies. Nullam magna ipsum, porta vel dui convallis, rutrum imperdiet eros. Aliquam erat volutpat. </div> </foreignObject> </...
... Sed mollis mollis mi ut ultricies. Nullam magna ipsum, porta vel dui convallis, rutrum imperdiet eros. Aliquam erat volutpat. </div> </foreignObject> </svg> Attributes height The height of the foreignObject. Value type: <length>|<percentage> ; Defa...
...ing with SVG2, x, y, width, and height are Geometry Properties, meaning those attributes can also be used as CSS properties for that element. ...
... and height are Geometry Properties, meaning those attributes can also be used as CSS properties for that element. ...
Subresource Integrity - Web security
Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match. Note: For subresource-integrity verification of a resource served from an origin other than the document in which it's embedded, browsers additionally check the resource using Cross-Origin Resource Sharing (CORS), to ensure the origin serving the resource allows it to be shared with the requesting origin. How Subresource Integrity helps Using Content Delivery Networks (CDNs) to host files such as scripts and stylesheets that are shared among multiple sites can improve site performance and conserve bandwidth. However...
...DNs also comes with a risk, in that if an attacker gains control of a CDN, the attacker can inject arbitrary malicious content into files on the CDN (or replace the files completely) and thus can also potentially attack all sites that fetch files from that CDN. Subresource Integrity enables you to mitigate some risks of attacks such as this, by ensuring that the files your web application or web document fetches (from a CDN or anywhere) have been delivered without a third-party having injected any additional content into those files -- and without any other changes of any kind at all having been made to those files. Using Subresource Integrity You use the Subresource Integrity feature by specifying a base64-encoded cryptographic hash of a resource (file) you're telling the browser to fetch, in ...
...nsequences if the filename happens to have valid hex characters in it -- because xxd will also decode that and pass it to base64. Additionally, the SRI Hash Generator at https://www.srihash.org/ is an online tool you can use to generate SRI hashes. Cross-Origin Resource Sharing and Subresource Integrity For subresource-integrity verification of a resource served from an origin other than the document in which it's embedded, browsers additionally check the resource using Cross-Origin Resource Sharing (CORS), to ensure the origin serving the resource allows it to be shared with the requesting origin. Therefore, the resource must be served with an Access-Control-Allow-Origin header that allows the resource to be shared with the requesting origin; for example: Access-Control-Allow-Origin: * Exa...
...following: When a browser encounters a <script> or <link> element with an integrity attribute, before executing the script or before applying any stylesheet specified by the <link> element, the browser must first compare the script or stylesheet to the expected hash given in the integrity value. Note: For subresource-integrity verification of a resource served from an origin other than the document in which it's embedded, browsers additionally check the resource using Cross-Origin Resource Sharing (CORS), to ensure the origin serving the resource allows it to be shared with the requesting origin. If the script or stylesheet doesn't match its associated integrity value, the browser must refuse to execute the script or apply the stylesheet, and must instead return a network error indicatin...
Axes - XPath
Web › XPath › Axes
Path specification. An axis represents a relationship to the context node, and is used to locate nodes relative to that node on the tree. The following is an extremely brief description of the thirteen available axes and the degree of support available in Gecko. For further information on using XPath expressions, please see the For Further Reading section at the end of Transforming XML with XSLT document. Also see the 'axes' section in the xpath spec. ancestor Indicates all the ancestors of the context node beginning with the parent node and traveling through to the root node. ancestor-or-self Indicates the context node and all of its ancestors, including the root node. attribute Indicates the attributes of the context node. Only elements have attributes. This axis can be abbreviated wi...
...odes are not included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents. following Indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes. following-sibling Indicates all the nodes that have the same parent as the context node and appear after the context node in the source document. ...
... self Indicates the context node itself. ...
...nt node. parent Indicates the single node that is the parent of the context node. It can be abbreviated as two periods (..). preceding Indicates all the nodes that precede the context node in the document except any ancestor, attribute and namespace nodes. preceding-sibling Indicates all the nodes that have the same parent as the context node and appear before the context node in the source document. self Indicates the context node itself. It can be abbreviated as a single period (.). ...
XPath
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes XPath stands for XML Path Language. It uses a non-XML syntax to provide a flexible way of addressing (pointing to) different parts of an XML document. It can also be used to test addressed nodes within a document to determine whether they match a pattern or not. XPath is mainly used in XSLT, but can also be used as a much more powerful way of navigating through the DOM of any XML-like language document using XPathExpression, such as HTML and SVG, instead of relying on the Document.getElementById() or ParentNode.querySelectorAll() methods, the Node.childNodes properties, and other DOM Core features. XPath uses a path notation (as in URLs) for navigating through the hierarchical structure of an XML doc...
...hical structure of an XML document. It uses a non-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 segment...
...roduction 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. 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...
... 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... Tools ChroPath XPath panel that integrates tightly into FireBug, providing an editor and inspector (FireFox Add-On). XMLQuire (formerly known as SketchPath) A Graphical X...
<xsl:output> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › output
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The <xsl:output> element controls the characteristics of the output document. To function correctly in Netscape, this element, with the method attribute, must be used. As of 7.0, method="text" works as expected. Syntax <xsl:output method="xml" | "html" | "text" version=STRING encoding=STRING omit-xml-declaration="yes" | "no" standalone="yes" | "no" doctype-public=STRING doctype-system=STRING cdata-section-elements=LIST-OF-NAMES indent="yes" | "no" media-type=STRING /> Required Attributes None. Optional Attributes method Specifies output format. version Specifies the value of the version attribute of the XML or HTML declaration in the output document. This attribute is only used...
...ments=LIST-OF-NAMES indent="yes" | "no" media-type=STRING /> Required Attributes None. Optional Attributes method Specifies output format. version Specifies the value of the version attribute of the XML or HTML declaration in the output document. This attribute is only used when method="html" or method="xml". encoding Specifies the value of the encoding attribute in the output document. omit-xml-declaration Indicates whether or not to include an XML declaration in the output. Acceptable values are "yes" or "no". standalone (Not supported.) If present, indicates that a standalone declaration should occur in the output document and gives its value. Acceptable values are "yes" or "no". doctype-public Specifies the value of the PUBLIC attribute of the DOCTYPE declara...
...aration Indicates whether or not to include an XML declaration in the output. Acceptable values are "yes" or "no". standalone (Not supported.) If present, indicates that a standalone declaration should occur in the output document and gives its value. Acceptable values are "yes" or "no". doctype-public Specifies the value of the PUBLIC attribute of the DOCTYPE declaration in the output document. doctype-system Specifies the value of the SYSTEM attribute of the DOCTYPE declaration in the output document. cdata-section-elements Lists elements whose text contents should be written as CDATA sections. Elements should be whitespace separated. indent (Not supported.) Specifies if the output should be indented to indicate its hierarchic structure. media-type (Not supported.) ...
... Type Top-level, must be the child <xsl:stylesheet> or <xsl:transform>. Defined XSLT, section 16. ...
WebAssembly Concepts - WebAssembly
, such as: WasmFiddle WasmFiddle++ WasmExplorer These are great resources for people who are trying to figure out where to start, but they lack some of the tooling and optimizations of Emscripten. The Emscripten tool is able to take just about any C/C++ source code and compile it into a .wasm module, plus the necessary JavaScript "glue" code for loading and running the module, and an HTML document to display the results of the code. In a nutshell, the process works as follows: Emscripten first feeds the C/C++ into clang+LLVM -- a mature open-source C/C++ compiler toolchain, shipped as part of XCode on OSX for example. Emscripten transforms the compiled result of clang+LLVM into a .wasm binary. By itself, WebAssembly cannot currently directly access the DOM; it can only call JavaScr...
...emented in terms of Web APIs and thus each one requires some JavaScript glue code to connect WebAssembly to the underlying Web API. So part of the glue code is implementing the functionality of each respective library used by the C/C++ code. The glue code also contains the logic for calling the above-mentioned WebAssembly JavaScript APIs to fetch, load and run the .wasm file. ...
...ve-mentioned WebAssembly JavaScript APIs to fetch, load and run the .wasm file. The generated HTML document loads the JavaScript glue file and writes stdout to a <textarea>. If the application uses OpenGL, the HTML also contains a <canvas> element that is used as the rendering target. It's very easy to modify the Emscripten output and turn it into whatever web app you require. You can find full documentation on Emscripten at emscripten.org, and a guide to implementing the toolchain and compiling your own C/C++ app across to wasm at Compiling from C/C++ to WebAssembly. Writing WebAssembly directly Do you want to build your own compiler, or your own tools, or make a JavaScript library that generates WebAssembly at runtime? In the same fashion as physical assembly languages, the WebAssembly bina...
...program to a WebAssembly npm package, and using that in a sample web app, over at our Compiling from Rust to WebAssembly article. Using AssemblyScript For web developers who want to try WebAssembly without needing to learn the details of C or Rust, AssemblyScript will be the best option. It generates a small bundle and it's performance is slightly slower compared to C or Rust. You can check its documentation on https://assemblyscript.org/. Summary This article has given you an explanation of what WebAssembly is, why it is so useful, how it fits into the web, and how you can make use of it. ...
2015 MDN Fellowship Program - Archive of obsolete content
mation. We expect this to be between 5-10 hours of your time per week. Specific projects (we encourage you to target one of these in your application): TestTheWebForward Brief project description Mozilla participates in an important W3C open testing initiative, TestTheWebForward.com. To support our efforts, the Fellow will review various technical specifications 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...
...mal workspace. The Fine Print Mozilla will provide coaching, direction and training on teaching best practices. Subject to Mozilla's travel reimbursement policies, Mozilla will cover Fellows travel, room, per diem food costs and visa costs up to $3,000 to attend the Orientation. Fellows are responsible for obtaining their own visas if any are required (Mozilla will provide reasonable supporting documentation). The Fellows will meet the stated deliverables of their projects and meet weekly with their mentor, the program lead and their other Fellows. The Fellow will also share the results of their projects at 1-2 events agreed upon by the Fellow and the Program Director, as well as on their personal channels (blog, social media, etc). The Fellow is responsible for any related visas (Mozilla can p...
...he stated deliverables of their projects and meet weekly with their mentor, the program lead and their other Fellows. The Fellow will also share the results of their projects at 1-2 events agreed upon by the Fellow and the Program Director, as well as on their personal channels (blog, social media, etc). The Fellow is responsible for any related visas (Mozilla can provide any necessary supporting documentation). Fellows will be required to sign Mozilla's Fellowship agreement in order to participate. If you've read all of this and still have a question, contact Diane Tate at diane@mozilla.com. If you don't have specific questions and just want to introduce yourself, please use the application form. Applications are closed. The application period has ended. Watch this space for information about ...
Cross-domain Content Scripts - Archive of obsolete content
Cross-...
... Cross-domain XMLHttpRequest The following add-on creates a panel whose content is the summar...
...ecast: // panel-script.js var url = "http://datapoint.metoffice.gov.uk/public/data/txt/wxfcs/regionalforecast/json/500?key=YOUR-API-KEY"; self.port.on("show", function () { var request = new XMLHttpRequest(); request.open("GET", url, true); request.onload = function () { var jsonResponse = JSON.parse(request.responseText); var summary = getSummary(jsonResponse); var element = document.getElementById("forecast_summary"); element.textContent = summary; }; request.send(); }); function getSummary(forecast) { return forecast.RegionalFcst.FcstPeriods.Period[0].Paragraph[0].$; } Finally, we need to add the "cross-domain-content" key to "package.json": "permissions": { "cross-domain-content": ["http://datapoint.metoffice.gov.uk"] } Content Permissions and unsafeWindo...
SDK API Lifecycle - Archive of obsolete content
ncompatible changes, we will go through the formal deprecation process. Deprecated We plan to change this module, and backwards compatibility should not be expected. Don't start using it, and plan to migrate away from this module to its replacement. The stability index for each module is written into that module's metadata structure, and is displayed at the top of each module's documentation page. Deprecation Process Deprecation In the chosen release, the SDK team will communicate the module's deprecation: update the module's stability index to be "deprecated" include a deprecation notice in the release notes, the Add-ons blog, and the Jetpack Google group. The deprecation notice should point developers at a migration guide. Migration The deprecation period defaults to...
...ation The deprecation period defaults to 18 weeks (that is, three releases) although in some cases, generally those out of our control, it might be shorter than this. During this time, the module will be in the deprecated state. The SDK team will track usage of deprecated modules on addons.mozilla.org and support developers migrating their code. The SDK will continue to provide warnings: API documentation will inform users that the module is deprecated. Attempts to use a deprecated module at runtime will log an error to the error console. The AMO validator will throw errors when deprecated modules are used, and these add-ons will therefore fail AMO review. All warnings should include links to further information about what to use instead of the deprecated module and when the module will b...
...d. Removal The target removal date is 18 weeks after deprecation. In preparation for this date the SDK team will decide whether to go ahead with removal: this will depend on how many developers have successfully migrated from the deprecated module, and on how urgently the module needs to be removed. If it's OK to remove the module, it will be removed. The SDK team will remove the corresponding documentation, and communicate the removal in the usual ways: the release notes, the Add-ons blog, and the Jetpack Google group. If it's not OK to remove it, the team will continue to support migration and aim to remove the module in the next release. ...
windows - Archive of obsolete content
close Private windows If your add-on has not opted into private browsing, then you won't see any private browser windows. Private browser windows won't appear in the browserWindows property, you won't receive any window events, and you won't be able to open private windows. To learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module. Converting to chrome windows To convert from the BrowserWindow objects used in this API to the chrome window objects used in the window/utils API, use the viewFor() function exported by the viewFor module. To convert back the other way, from a chrome window to a BrowserWindow object, use the modelFor() function, exported by the modelFor module. Here's an ...
...dow, and then back the other way: var { modelFor } = require("sdk/model/core"); var { viewFor } = require("sdk/view/core"); var browserWindows = require("sdk/windows").browserWindows; function convertToChromeAndBack(browserWindow) { // get the chrome window for this BrowserWindow var chromeWindow = viewFor(browserWindow); // now we can use the chrome window API console.log(chromeWindow.document.location.href); // -> "chrome://browser/content/browser.xul" // convert back to the high-level window var highLevelWindow = modelFor(chromeWindow); // now we can use the SDK's high-level window API console.log(highLevelWindow.title); } browserWindows.on("open", convertToChromeAndBack); Note that directly accessing low-level chrome objects like this means you're no longer protected by...
...ameters options : object Required options: Name Type url string String URL to be opened in the new window. This is a required property. isPrivate boolean Boolean which will determine whether the new window should be private or not. If your add-on does not support private browsing this will have no effect. See the private-browsing documentation for more information. Optional options: Name Type onOpen function A callback function that is called when the window has opened. This does not mean that the URL content has loaded, only that the window itself is fully functional and its properties can be accessed. This is an optional property. onClose function A cal...
frame/utils - Archive of obsolete content
Experimental Provides helper functions for working with platform internals like frames and browsers. Usage Module exports create function that takes the nsIDOMDocument of a privileged document and creates a browser element in its documentElement: let { open } = require('sdk/window/utils'); let { create } = require('sdk/frame/utils'); let window = open('data:text/html,Foo'); let frame = create(window.document); Optionally create can be passed set of options to configure created frame even further. 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>', allowJavascript:...
...ssed 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>', allowJavascript: true }); } Globals Functions create(document, options) Creates a XUL browser element in a privileged document. ...
...sily 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>', allowJavascript: 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 documentation on MDN uri String URI of the document to be loaded into the new frame. Defaults to about:blank. ...
platform/xpcom - Archive of obsolete content
e, 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 wrappedJSObject() this, hello: function() {retur...
... 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 documentation for Unknown.QueryInterface(). Properties interfaces The set of interfaces supported by this object. Factory sets this to nsIFactory. id This factory's class ID. contract This factory's contract ID. Service Use this class to register an XPCOM service. To register a service for a component, construct a Service, giving it: a constructor for the object implementing the service a con...
... ...
Creating annotations - Archive of obsolete content
Because this code uses jQuery, you'll need to download that as well, and save it in...
..., so each time the user loads a page the page-mod emits the attach event, which will call the listener function we've assigned to onAttach. The handler is passed a worker object. Each worker represents a channel of communication between the add-on code and any content scripts running in that particular page context. For a more detailed discussion of the way page-mod uses workers, see the page-mod documentation. In the attach handler we do three things: send the content script a message with the current activation status add the worker to an array called selectors so we can send it messages later on assign a message handler for messages from this worker. If the message is show we will just log the content for the time being. If the message is detach we remove the worker from the selectors arr...
...annotation-box'> </textarea> </body> </html> Save this inside data/editor as annotation-editor.html. Annotation editor content script In the corresponding content script we do two things: handle a message from the add-on code by giving the text area focus listen for the return key and when it is pressed, send the contents of the text area to the add-on. Here's the code: var textArea = document.getElementById('annotation-box'); textArea.onkeyup = function(event) { if (event.keyCode == 13) { self.postMessage(textArea.value); textArea.value = ''; } }; self.on('message', function() { var textArea = document.getElementById('annotation-box'); textArea.value = ''; textArea.focus(); }); Save this inside data/editor as annotation-editor.js. Updating main.js Again Now we'l...
Modifying Web Pages Based on URL - Archive of obsolete content
fy. A simple code snippet where content script is supplied as contentScript option and URL pattern is given as include option is as follows: // Import the page-mod API var pageMod = require("sdk/page-mod"); // Create a page-mod // It will run a script whenever a ".org" URL is loaded // The script replaces the page contents with a message pageMod.PageMod({ include: "*.org", contentScript: 'document.body.innerHTML = ' + ' "<h1>Page matches ruleset</h1>";' }); Do as follows: Create a new directory and navigate to it. Run jpm init, accepting all the defaults Open the file index.js and add the code above Run jpm run Open ietf.org in the browser window that opens. Below is what you should see. Specifying the Match Pattern Match pattern uses match-pattern syntax. Y...
...ender calls port.emit() and receiver listens using port.on(). In the content script, port is a property of the global self object. In the add-on script, you need to listen for the onAttach event to get passed a worker object that contains port. Let's rewrite the example above to pass a message from the add-on to the content script. The message will contain the new content to insert into the document. The content script now needs to look like this: // "self" is a global object in content scripts // Listen for a message, and replace the document's // contents with the message payload. self.port.on("replacePage", function(message) { document.body.innerHTML = "<h1>" + message + "</h1>"; }); In the add-on script, we'll send the content script a message inside onAttach. // Import the page-m...
...eMod({ include: "*", contentStyleFile: "./my-style.css" }); Learning More To learn more about page-mod, see its API reference page. In particular, the PageMod constructor takes several additional options to control its behavior: By default, content scripts are not attached to any tabs that are already open when the page-mod is created, and are attached to iframes as well as top-level documents. To control this behavior use the attachTo option. Define read-only values accessible to content scripts using the contentScriptOptions option. By default, content scripts are attached after all the content (DOM, JS, CSS, images) for the page has been loaded, at the time the window.onload event fires. To control this behavior, use contentScriptWhen option. To learn more about con...
Bootstrapped extensions - Archive of obsolete content
s to: Make your add-on's content available via a chrome:// URL (using the content, locale, and skin instructions in the manifest). Replace existing chrome:// URIs with your content (using the override instruction). Not all chrome.manifest instructions are supported in bootstrapped add-ons, for example you still cannot register XUL Overlays from a bootstrapped add-on. See the chrome.manifest documentation for details. In Firefox 10 and later the chrome.manifest file located in the root of the add-on's XPI (i.e. a sibling of the install.rdf) is loaded automatically. In Firefox 8 and 9 you had to load/unload the manifest manually using nsIComponentManager.addBootstrappedManifestLocation() and nsIComponentManager.removeBootstrappedManifestLocation(). This feature was unavailable in Firefox vers...
...and nsIComponentManager.removeBootstrappedManifestLocation(). This feature was unavailable in Firefox versions before 8. Adding user interface manually If you decide to go ahead and try to develop a bootstrapped extension that modifies the application's user interface, here are a few suggestions to get you started. You need to look up the relevant application UI elements by their ID by calling document.getElementById(), then manipulate them to inject your UI. For example, you can get access to the menu bar in Firefox with document.getElementById("main-menubar"). Be sure that at shutdown time, you remove any user interface you've added. Creating a bootstrapped extension To mark an extension as bootstrappable, you need to add the following element to its install manifest: <em:bootstrap>true</...
... ...
HTML in XUL for rich tooltips - Archive of obsolete content
TMLTip"> <html:div id="myHTMLTipDiv" type="content"/> </tooltip> </popupset> </overlay> Insert your version of the following into the JavaScript overlay. Our customized tooltipHTML attribute for each element can be set at any time. ...
... </overlay> Insert your version of the following into the JavaScript overlay. Our customized tooltipHTML attribute for each element can be set at any time. ...
...</font>") document.getElementById("htmltip2").setAttribute("tooltipHTML", "<font color='green'>green foo</font>") }, onMouseTooltip: function(event) { //get the HTML tooltip string assigned to the element that the mouse is over (which will soon launch the tooltip) var txt = event.target.getAttribute("tooltipHTML"); // get the HTML div element that is inside the custom XUL tooltip var div = document.getElementById("myHTMLTipDiv"); //clear the HTML div element of any prior shown custom HTML while(div.firstChild) div.removeChild(div.firstChild); //safely convert HTML string to a simple DOM object, stripping it of JavaScript and more complex tags var injectHTML = Components.classes["@mozilla.org/feed-unescapehtml;1"] .getService(Components.interfaces.nsIScriptableUnescapeHTML) .parseFragment...
LookupNamespaceURI - Archive of obsolete content
Here is an implementation of Node.lookupNamespaceURI which should work cross-browser. Note that all Gecko-based browsers (including Firefox) support Node.lookupNamespaceURI. This function is not necessary for Gecko-based browsers (though the function will quickly return the standard value for Mozilla browsers) when used to reflect on static documents. However, due to bug 312019, this method does not work with dynamically assigned namespaces (e.g., those set with Node.prefix). /*globals Document, HTMLDocument */ (function () { 'use strict'; var Doc = typeof Document !== 'undefined' ? Document : HTMLDocument; // Support HTMLDocument if Document not present // If Document is present, is this method also present? addLookupNamespaceURI(Doc); addLookupNamespaceURI(Element); function addLookupNa...
...amespaceURI) { type.prototype.lookupNamespaceURI = lookupNamespaceURI; } function lookupNamespaceURI (prefix) { return lookupNamespaceURIHelper(this, prefix); } function lookupNamespaceURIHelper (node, prefix) { // adapted directly from http://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespaceURIAlgo var i, att, htmlMode = document.contentType, // Mozilla only xmlnsPattern = /^xmlns:(.*)$/; switch (node.nodeType) { case 1: // ELEMENT_NODE (could also just test for Node.ELEMENT_NODE, etc., if supported in all browsers) if (node.namespaceURI != null && node.prefix === prefix) { // Note: prefix could be "null" in the case we are looking for default namespace...
... return null; // unknown } } } if (node.parentNode && node.parentNode.nodeType !== 9) { // EntityReferences may have to be skipped to get to it return lookupNamespaceURIHelper(node.parentNode, prefix); } return null; case 9: // DOCUMENT_NODE return lookupNamespaceURIHelper(node.documentElement, prefix); case 6: // ENTITY_NODE case 12: // NOTATION_NODE case 10: // DOCUMENT_TYPE_NODE case 11: // DOCUMENT_FRAGMENT_NODE return null; // unknown case 2: // ATTRIBUTE_NODE if (node.ownerElement) { return lookup...
Tabbox - Archive of obsolete content
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. ...
.... Try to avoid using it. ...
...Event Assuming the tabbox, tabs, and tabpanels widgets with id's the same as their nodeName, this function will correctly remove the current tab and tab panel for the onclosetab tabs event: function removeTab(){ var tabbox = document.getElementById("tabbox"); var currentIndex = tabbox.selectedIndex; if(currentIndex>=0){ var tabs=document.getElementById("tabs"); var tabpanels=document.getElementById("tabpanels"); tabpanels.removeChild(tabpanels.childNodes[currentIndex]); tabs.removeItemAt(currentIndex); /*Work around If last tab is removed, widget fails to advance to next tab*/ if(-1 == tabbox.selectedIndex && tabs.childNodes.length>0){ tabbox.selectedIndex=0; } } Creating a close tab button To have a tab close button, you must configure the styl...
Tree - Archive of obsolete content
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; var sel = view.selection.currentIndex; //returns -1 i...
...> 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>. ...
...alue, col.value); alert(cellText); } Getting the selected indices of a multiselect tree var start = {}, end = {}, numRanges = tree.view.selection.getRangeCount(), selectedIndices = []; for (var t = 0; t < numRanges; t++){ tree.view.selection.getRangeAt(t, start, end); for (var v = start.value; v <= end.value; v++) selectedIndices.push(v); } Other resources XUL: Tree documentation XUL tutorial: Tree selection ...
View Source for XUL Applications - Archive of obsolete content
Importing gViewSourceUtils XUL applications wanting to show the source code for documents should import the viewSourceUtils.js script instead of attempting to open the viewSource.xul window themselves: <script type="application/javascript" src="chrome://global/content/viewSourceUtils.js"/> viewSourceUtils.js exposes a gViewSourceUtils global into the scope of the window that imports that script. Method overview gViewSourceUtils exposes several methods, but the only one you should be using directly is the viewSource method. The rest of those methods should be considered private, and might become inaccessible in the future. void viewSource(aObject); Methods viewSource Opens a viewer to the source code for some document or URI. Parameters The viewSource method takes an Obje...
.... The rest of those methods should be considered private, and might become inaccessible in the future. void viewSource(aObject); Methods viewSource Opens a viewer to the source code for some document or URI. Parameters The viewSource method takes an Object as its first and only parameter. The Object can include the following properties: URL (required) A string URL for the document to view the source of. browser (optional) The browser containing the document that we would like to view the source of. This is optional if outerWindowID is not passed. outerWindowID (optional) The outerWindowID of the content window containing the document that we want to view the source of. Pass this if you want to attempt to load the document source out of the network cache. lineNumber (o...
...iew the source of. Pass this if you want to attempt to load the document source out of the network cache. lineNumber (optional) The line number to focus on once the source has loaded. Deprecated API This API is likely to go away in the future, and should no longer be used. The viewSource method will also accept the following arguments in place of the Object: aURL A string URL for the document to view the source of. aPageDescriptor (optional) A "descriptor" that allows the source to be retrieved from the network cache. This is usually gotten from the nsIWebPageDescriptor interface via currentDescriptor. aDocument (optional) The content document that we're attempting to load the source from. aLineNumber (optional) The line number to focus on once the source has loaded. ...
xml:base support in old browsers - Archive of obsolete content
to keep going up the chain if still a relative URL!!!!! ...
... URL!!!!! ...
...3 : 2; // If the file protocol has an extra slashe, prepare to also skip it in the ...
Communication between HTML and your extension - Archive of obsolete content
ension to "look" for what is on the page. What I tried My first attempt was trying to create an XBL component. From what I gather, XBL components are more designed for creating custom components and their specific 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 ...
...ript 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, DOMInsertNodeIntoDocument, DOMActivate) and I tried them all in many different ways. Some of the events only apply to certain types of elements so I included trying to modify the result of the AJAX request to be of the appropriate element type (img, which supports "onLoad," rather than span, which doesn't, for example). The problem with the events is the timing. I wasn't sure about the difference between the capture or bu...
...lp. I started to research custom events on Google but everything that I found was far too complicated for what I wanted to achieve. Eventually I put the creation of the custom event into the stateChanged function that was handling the receipt of the AJAX request. After the HTML component was update with the result of the AJAX request, I created and dispatched the event like this: var event = document.createEvent("Events"); event.initEvent("my-custom-event", true, true); document.body.dispatchEvent(event); In the code of the extension that catches the loading of a new page I added this code: var doc = aEvent.originalTarget; // doc is document that triggered "onload" event // do something with the loaded page. // doc.location is a Location object (see below for a link). // Yo...
How to convert an overlay extension to restartless - Archive of obsolete content
your chrome.manifest to load XUL overlays anymore with a restartless add-on. You could look into dynamically loading and unloading your overlay, however dynamically manipulating the DOM of your XUL window is usually the more straightforward route. Figure out what XUL elements you need to create for your add-on to add your interface, where it needs to go into a XUL window, and how to do it. Docs: document.getElementByID(), document.createElement(), Element reference, Node reference (DOM elements are also nodes). You'll need to write two functions. One to take a XUL window object and then create and add your elements, and then another to find your elements and remove them from the window object. The former will need to be run on add-on startup and the later on add-on shutdown. Until you get your b...
...nents.interfaces.nsIDOMWindow)); } var WindowListener = { onOpenWindow: function(xulWindow) { var window = xulWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIDOMWindow); function onWindowLoad() { window.removeEventListener("load",onWindowLoad); if (window.document.documentElement.getAttribute("windowtype") == "navigator:browser") loadIntoWindow(window); } window.addEventListener("load",onWindowLoad); }, onCloseWindow: function(xulWindow) { }, onWindowTitleChange: function(xulWindow, newTitle) { } }; As mentioned above, Components.utils.unload() will not work properly if the JSM file it is unloading is in a JAR.
... if the JSM file it is unloading is in a JAR. Also make sure to only unload your own JSM files to avoid accidentally breaking things horribly. For tearing down and cleaning up on a per-window basis, there is another route you can take. Instead of directly calling your tear down function, make your unloadFromWindow() something like this: function unloadFromWindow(window) { var event = window.document.createEvent("Event"); event.initEvent("myAddonName-unload",false,false); window.dispatchEvent(event); } In each window you can then register on startup to listen for your custom "myAddonName-unload" event and just tear down and clean up when that event or a regular "unload" event comes in. Step 10: Bypass cache when loading properties files The above will get you a working add-on that...
Listening to events in Firefox extensions - Archive of obsolete content
It also provides some use cases that may be of specific interest. ...
...) Where b is the browser or tabbrowser you wish to watch for events from. Keep in mind that the events may come from any frame within the browser or, for a tabbrowser, any of the browsers within it. Some of the more interesting DOM events you may wish to monitor are listed here: Event Description DOMLinkAdded Dispatched when a new HTML <link> element is detected in the document. DOMTitleChanged Dispatched when the title of the page changes. DOMContentLoaded Dispatched when the initial DOM for the page is completely loaded. load Dispatched after the page--including images--has first finished loading. unload Dispatched when the user has navigated away from the page. pageshow Dispatched when a page is newly displa...
... This property is set to false if the page is not cached by the browser and set to true if the page is cached by the browser. When this property is set to false, the unload handler, if present, fires immediately after the pagehide event. Firefox 1.5 tries to simulate load events in the same order they would occur when the page is initially loaded. Frames are treated the same way as the top-level document. If the page contains frames, then when the cached page is loaded: pageshow events from each frame fire before the pageshow event in the main document fires. When the user navigates away from the cached page, the pagehide event from each frame fires before the pagehide event in the main document. For navigation that occurs inside a single frame, events fire only in the affected frame. Web ...
JavaScript Object Management - Archive of obsolete content
ter the DOM on the window has loaded completely, but before it's displayed to the user. This allows you to manipulate and possibly change elements in the window without the user noticing the changes. /** * Controls the browser overlay for the Hello World extension. */ <Namespace>.BrowserOverlay = { /** * Initializes this object. */ init : function(aEvent) { this._stringBundle = document.getElementById("xulschoolhello-string-bundle"); // you can make changes to the window DOM here. } // more stuff }; window.addEventListener( "load", function() { <Namespace>.BrowserOverlay.init(); }, false); There are some things you can't (or shouldn't) do inside load handlers, such as closing the window being loaded, or opening new windows, alerts or dialogs. The window has to fin...
...osing the window being loaded, or opening new windows, alerts or dialogs. The window has to finish loading before it can do any of these things. They are bad UI practices anyway and you should avoid them. If you really need to do something like this anyway, one way to do it is to have a timeout execute the code after a delay: init : function(aEvent) { let that = this; this._stringBundle = document.getElementById("xs-hw-string-bundle"); window.setTimeout( function() { window.alert(that._stringBundle.getString("xulschoolhello.greeting.label")); }, 0); } The setTimeout function executes the function in the first parameter, after a delay in miliseconds specified by the second parameter. In this case we set the delay to 0, which means the function should be executed as soon as p...
...ow). Include the Cc and Ci constants in all XUL windows that are not overlays, all JSM files, and all XPCOM components (see further ahead). Do this even if you don't need them now. It's better to just make a habit out of it. This is a point that is worth highlighting: modules work outside of the window scope. Unlike scripts in the chrome, modules don't have access to objects such as window, document, or other global functions, such as openUILink. These are all UI components and UI operations anyway, so they are better done in the chrome. As a general guideline, we keep all of our business logic in JSM, available through service objects, and chrome scripts are limited to handle presentation logic. We handle most of our code through static objects, singleton objects that don't require in...
Updating addons broken by private browsing changes - Archive of obsolete content
After reading this document, contact Josh Matthews with further questions or clarifications, or file a bug if your extension has stopped working due to a change described here and you are having trouble updating it. How do I know if my addon is affected by these changes? If your code refers to any of the following interfaces: FF 15: nsIDOMStorageManager FF 16: nsITransferable FF 18: imgICache mozIAsyncFavicons nsIFaviconService nsIWebBrowserPersist FF 19: nsIContentPrefService nsIDownloadManager nsIDownload nsIHttpAuthManager nsIStrictTransportSecurityService FF 20: nsIPrivateBrowsingService nsIRecentBadCertService Furthermore, if your code uses any of these common chrome APIs: FF 19: saveURL saveInternal openLinkIn FF 20: OpenBrowserWindow gPrivateBrowsingUI Finally, if your ...
...cate desired properties of the window. Passing {private: true} will cause a private window to open, otherwise the window will always be non-private. Use {private: PrivateBrowsingUtils.isWindowPrivate(window)} to open a window that matches the current window's privacy status. openLinkIn: Can receive an extra private boolean property in the parameter object. internalSave: Takes a new required Document argument (prior to the optional boolean and string arguments) indicating the document that originated the save action. gPrivateBrowsingUI: Can no longer be used to control private browsing of any kind. Any new private browsing session should be opened using OpenBrowserWindow, and any queries for private browsing status should use PrivateBrowsingUtils.isWindowPrivate(win) on a relevant window o...
... and string arguments) indicating the document that originated the save action. gPrivateBrowsingUI: Can no longer be used to control private browsing of any kind. Any new private browsing session should be opened using OpenBrowserWindow, and any queries for private browsing status should use PrivateBrowsingUtils.isWindowPrivate(win) on a relevant window object. saveURL: Takes a new required Document argument indicating the source of the URL being saved. ...
Defining Cross-Browser Tooltips - Archive of obsolete content
ge format used; if either of these is not true, and the image cannot be displayed, then the alt text should be displayed in place of the missing image. On the other hand, the HTML 4.01 definition of the title attribute states: title = text CS This attribute offers advisory information about the element for which it is set. Unlike the TITLE element, which provides information about an entire document and may only appear once, the title attribute may annotate any number of elements. Please consult an element's definition to verify that it supports this attribute... Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an obje...
...nts showed that title attribute contents were displayed as a "tooltip" in: Gecko-based browsers (Mozilla Firefox, Netscape 6+, etc.) Internet Explorer 5.5+/Win Internet Explorer 5.x/Mac Safari Opera 6.x+ Of these, only IE/Win treated alt text as a "tooltip"; the other browsers did not reproduce this behavior. Authors who are faced with the prospect of editing a large collection of legacy documents should be able to convert their documents using a batch find-and-replace operation, for example substituting alt= for title=. If such a find-and-replace operation is somehow not feasible, authors with the ability to run proxy servers can use the approach proposed by Christian Jensen (cf. bug 25537#c73, which is to run a proxy server that rewrites HTML source on the fly, as it is sent to the use...
... attribute (instead of alt) to ensure desired tooltip behavior in multiple browsers. Authors able to run content-rewriting proxy servers can use them to dynamically alter outgoing content to ensure both the title and alt attributes are present. Related Links HTML 4.01 Specification: 13.8 How to specify alternate text HTML 4.01 Specification: 7.4.3 The title attribute bug 25537 Original Document Information Author(s): Eric A. Meyer, Netscape Communications Last Updated Date: Published 16 Aug 2002 Copyright Information: Copyright (C) 2001-2003 Netscape. All rights reserved. Note: This reprinted article was originally part of the DevEdge site. ...
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
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. Although it is designed to retrieve XML content and parse it into a DOM, it can retrieve (but not parse) other kinds of content as well. In this case we use it to retrieve an HTML page containing a brief summary of the current tinderbox state. That document gets updated by the tinderbox server every time a build finishes. It displays a list of active tinderbox clients along with the re...
... Notice that we defined the instance of XMLHttpRequest as a global variable. ...
...active tinderbox clients along with the result of their last build attempt. XMLHttpRequest is easy to use in the simple case we have here. We use new to create a new instance of it, set the instance's onload property to updateTinderboxStatus(), the function we want to execute when the document finishes loading, call its open method with the type of HTTP request we want to make and the URL of the document to retrieve, and then call its send method to send the request. XMLHttpRequest will retrieve the document located at the given URL and call the updateTinderboxStatus() function when it is done. Notice that we defined the instance of XMLHttpRequest as a global variable. This is because we need to reference it in the updateTinderboxStatus() function as well as the current function, and we can't p...
Drag and Drop - Archive of obsolete content
deprecated the newer, simpler, portable API should be used in their place. This section describes how to implement objects that can be dragged around and dropped onto other objects. The Drag and Drop Interface Many user interfaces allow one to drag particular objects around within the interface. For example, dragging files to other directories, or dragging an icon to another window to open the document it refers to. Mozilla and XUL provide a number of events that can handle when the user attempts to drag objects around. A user can start dragging by holding down the mouse button and moving the mouse. The drag stops when the user releases the mouse. Event handlers are called when the user starts and ends dragging, and at various points in-between. Mozilla implements dragging by using a drag ses...
...ribed earlier. This can be used to provide extra feedback to the user. numDropItems The number of items being dragged. For example, this will be set to 5 if five bookmarks are being dragged. getData(transfer,index) Get the data being dragged. The first argument should be an nsITransferable object to hold the data. ...
...This can be used to provide extra feedback to the user. numDropItems The number of items being dragged. For example, this will be set to 5 if five bookmarks are being dragged. getData(transfer,index) Get the data being dragged. The first argument should be an nsITransferable object to hold the data. The second argument, index, should be the index of the item to return. sourceDocument The document where the drag started. sourceNode The DOM node where the drag started. isDataFlavorSupported(flavor) Returns true if the data being dragged contains data of the specified flavor. Next >> Original Document Information Author(s): Neil Deakin Original Document: Copyright Information: Copyright (C) Neil Deakin ...
Embedding FAQ - Archive of obsolete content
FAQ mozilla.dev.embedding How to start Embedding You can find a examples, FAQs, and the API from mozilla itself. You can get more detailed information on what interfaces are required and which are optional to impelement here. Scroll down to "Initalization and Teardown. How to customize document retrieval One method is to implement your own protocol method. You can find more information on adding new protocols here How to embedding mozilla inside of Java There hasn't been any good code examples found. However, there is a stripped down, uncommented code with eclipse libraries in this thread. Here is the code : import org.eclipse.swt.SWT; import org.eclipse.swt.browser.MozillaBrowser; import org.eclipse.swt.browser.ProgressEvent; import org.eclipse.swt.browser.ProgressListener; import ...
...es found. However, there is a stripped down, uncommented code with eclipse libraries in this thread. ...
... final MozillaBrowser browser = new MozillaBrowser(shell,WT.BORDER); browser.setUrl("http://www.google.com"); browser.addProgressListener(new ProgressListener() { public void changed(ProgressEvent event) { } public void completed(ProgressEvent event) { nsIDOMDocument doc = browser.getDocument(); System.out.println(doc); } }); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } How to map a Javascript function to a C++ function Define ...
Repackaging Firefox - Archive of obsolete content
You will need the following to get started: A Macintosh computer (even for repackaging Windows or Linux only); it may be either PowerPC or Intel based. The repackager tool. Currently that page mentions only Firefox 1.5.x, but it supports Firefox 2. The pristine Firefox 2 installer files (Windows .exe, Mac .dmg, or Linux .tar.gz) for each of the locales you need. At the time of writing this document, the latest builds are here. A "distro" extension that makes the changes you desire. Once you have all the ingredients, the customization process is quite easy: Download the Firefox installer. Install the repackager tool like you would any Mac application. Make sure it starts up and launches the GUI. Put together your extension that customizes Firefox. The distro extension All the chan...
...e it is used to create a new "distribution" of Firefox, with different branding, etc. Using an extension makes it far easier to keep track of your changes easily when the time comes to upgrade to new versions of Firefox, and also ensures, when set-up correctly, that users are able to safely receive Firefox updates from Mozilla. More about this below. While the aim of this article is not to fully document how to make an extension (for that, try this section of the Mozilla Developer Center), here is a basic tutorial to get you started, and some tips specific for creating a DEX. If you already have an extension that you want to bundle with Firefox, and don't want to bundle an extra extension solely to set a few defaults, you can do everything you need to do in your existing extension. However, it's...
...ike this: pref("localizable.preference.name", "data:text/plain,localizable.preference.name=Some value."); Then, a properties file is not used (or needed at all) for that preference. Therefore, if *all* of your preferences can use the same values, you do not need to include any properties files at all. Note that you must know which preferences are localizable and which ones aren't. See the MDC documentation for more information on them. Important Extension Preferences There is a small set of preferences which will be given to you by Mozilla. They help Mozilla track your distribution, and plan upgrades accordingly. They allow for upgrades to be delivered by Mozilla specifically for your distribution, if need be, and because of that they are the most important preferences you need to set. Mozi...
Using microformats - Archive of obsolete content
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. ...
...at 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 search the entire document, specify content.document. options Optional. If provided, this is a JavaScript object that contains zero or more of the fol...
... the specified microformat object. get() Returns an array of microformat objects 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 de...
Microsummary XML grammar reference - Archive of obsolete content
Warning: Microsummary support was removed in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) This article provides detailed information about the XML grammar used to build microsummary generators, describing each element and their attributes. For an introduction to how to create a microsummary, read the article Creating a Microsummary. ...
...w.w3.org/1999/XSL/Transform" version="1.0"> <output method="text"/> <template match="/"> <value-of select="id('download-count')"/> <text> Fx downloads</text> </template> </transform> </template> <pages> <include>http://(www\.)?spreadfirefox\.com/(index\.php)?</include> </pages> </generator> Namespace The namespace URI for microsummary generator XML documents is: http://www.mozilla.org/microsummaries/0.1 All elements in a microsummary generator document should be in this namespace except the descendants of the <template> element, which should be in the XSLT namespace: http://www.w3.org/1999/XSL/Transform The <generator> element The <generator> element is the root tag for all microsummary generators, and should contain the remainder of the XML code ...
...tes. Its value must be a number greater than or equal to 1. Fractional values (e.g. 5.5 minutes) are permitted, although they probably aren't useful. The <update> element may contain any number of <condition> child elements. Firefox determines which interval to apply to a microsummary generated by a generator according to the following rules: Firefox processes each <condition> child element in document order. For each one, Firefox evaluates the element's XPath boolean expression against the page being summarized. If the expression evaluates to true, Firefox applies that element's interval and stops processing child elements. Thus, the first matching <condition> determines the update interval. If there are no <condition> child elements, or if none of their expressions evaluate to true, Firefox...
Plugin Architecture - Archive of obsolete content
The described sequences are subject to change at any time. Classes There are some classes involved in plugins: nsObjectLoadingContent embed, object and applet nodes inherit from that class, which provides services for loading various kinds of objects. ...
...The described sequences are subject to change at any time. Classes There are some classes involved in plugins: nsObjectLoadingContent embed, object and applet nodes inherit from that class, which provides services for loading various kinds of objects. ...
...ding various kinds of objects. It takes care of most of the work involved in loading the data and instantiating plugins. nsObjectFrame The frame responsible for displaying plugins nsPluginInstanceOwner Glue between plugin code (modules/plugin) and layout code (layout/generic). A refcounted object, contrary to nsObjectFrame. Note that while nsObjectLoadingContent also deals with images and documents, this document concentrates on plugins. Sequence of events In content A content node for a plugin DOM element gets created In BindToTree (usually) or another function, it calls LoadObject LoadObject either notices directly that it is dealing with a plugin, or it starts a network request and notices this in OnStartRequest When it realizes that, it tries to create a frame, if aNotify is t...
Porting NSPR to Unix Platforms - Archive of obsolete content
For certain more "standard" Unix platforms, this may be all you have to do. ...
...</tt> preprocessor directives we inserted For a pthreads port, you need to modify the following files: <tt>mozilla/nsprpub/pr/include/md/_pth.h</tt> Files in mozilla/nsprpub/pr/src/pthreads, most likely <tt>ptthread.c</tt> and <tt>ptio.c</tt> Testing Your Port We have some unit tests in <tt>mozilla/nsprpub/pr/tests</tt>. First a warning: some of the tests are broken. Further, we don't have documentation of our unit tests, so you often need to resort to read the source code to understand what they do. Some of them respond to the <tt>-h</tt> command line option and print a usage message. <strike>Henry Sobotka of the OS/2 Mozilla porting project has a web page at http://www.axess.com/users/sobotka/n.../warpztjs.html with good documentation of the NSPR unit tests</strike>. Here are my favorite ...
.... ...
Space Manager Detailed Design - Archive of obsolete content
nsSpaceManager The Space Manager is the central class is a group of classes that manage the occupied and available space that exists in horizontal bands across a canvas. ...
... Overview The Space Manager and related classes and structures are an important of the Gecko Layout system, specifically Block Layout. See the High Level Design document for an overview of the Space Manager, and as an introduction to the classes, structures and algorithms container in this, the Detailed Design Document. nsSpaceManager The Space Manager is the central class is a group of classes that manage the occupied and available space that exists in horizontal bands across a canvas. The primary goal of the Space Manager is to provide information about those bands of space to support the CSS notion of floated elements. There are three important parts to the Space Manager API: the parts that deal with the coordinate space of the Space Manager, the parts that deal with the regions man...
...same frame list, then make the current bandRect cover the previous bandRect's full region (adjust the left edge to be that of the previous bandRect) and remove the previous bandRect. if the current band or prior band had a rect occupied by the frame,then try to join the two bands via JoinBands Finally, destroy the frameInfo for the frame. Cross-Component Algorithms Tech Notes Original Document Information Author(s): Marc Attinasi Other Contributors: David Baron, Josh Soref Last Updated Date: November 25, 2005 ...
Supporting private browsing mode - Archive of obsolete content
s in effect. Detecting whether private browsing mode is permanent Requires Gecko 2.0(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Firefox 4 added support for having private browsing mode permanently enabled. The theme looks different in this scenario. ...
...ks different in this scenario. To determine whether or not the browser is permanently in private browsing mode, you can look at the privatebrowsingmode attribute on the document root. Its value is "permanent" if private browsing is permanently enabled for the session, "temporary" if private browsing is temporarily enabled, or not defined at all if private browsing mode isn't active. ...
...ent in this scenario. To determine whether or not the browser is permanently in private browsing mode, you can look at the privatebrowsingmode attribute on the document root. Its value is "permanent" if private browsing is permanently enabled for the session, "temporary" if private browsing is temporarily enabled, or not defined at all if private browsing mode isn't active. ...
Tamarin - Archive of obsolete content
ion 3) and is embedded within the Adobe(R) Flash(R) Player versions 9 and later. Tamarin's jit-compiler, NanoJIT, is also used in TraceMonkey ergo SpiderMonkey, which is Mozilla's JavaScript engine in Firefox. 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. Tamarin Build Documentation How to get, build, and use Tamarin. Tamarin Build System Documentation Documentation on how the Tamarin build system works and how to modify. ...
...se Tamarin. Tamarin Build System Documentation Documentation on how the Tamarin build system works and how to modify. Tamarin commit hook Instructions for installing and using the mercurial hook for Tamarin. Tamarin Acceptance Testing Instructions on how to validate changes to the Tamarin source code. Tamarin pages at wiki.mozilla.org More documentation. MMgc overview An overview of the Tamarin garbage collector. Nanojit LIR In Nanojit, LIR is the source language for compilation to machine code. Tamarin strings documentation The implementation of Tamarin strings has changed. This page is a how-to about the changes, and what can be done to adapt source code to the changes. ...
...overview An overview of the Tamarin garbage collector. Nanojit LIR In Nanojit, LIR is the source language for compilation to machine code. Tamarin strings documentation The implementation of Tamarin strings has changed. This page is a how-to about the changes, and what can be done to adapt source code to the changes. Tamarin doxygen documentation Documentation for the latest release. Get Involved! log a bug against Tamarin tamarin-devel mailing list #tamarin channel on irc.mozilla.org Blogroll Mason Chang David Mandelin Related Topics JavaScript SpiderMonkey ActionMonkey Tamarin on mozilla.org ...
The new nsString class implementation (1999) - Archive of obsolete content
Disclaimer: I absolutely hate string classes. ...
... has served us well so far, but it's in need of a facelift. And XPCOM has really taken off, so nsString needs to be brought into alignment. Justification The nsString class is a wide character string class used throughout all of Gecko (and other modules) as the default implementation. However, it suffers from a few implementation details which need to be addressed and that are the subject of this document. The deficiencies of the current implementation are: Class based -- making it unsuitable for cross-dll usage due to fragility Little intrinsic i18n support Few efficiencies, notably a lack of support for narrow (1-byte) character strings No support for external memory management policy Lack of XPCOM interface Notable features of the new nsStrImpl implementation are: Intrinsic support for...
...r of ways. To wit: They want to ensure that the underlying buffers cannot be corrupted or altered erroneously They want to ensure that the appropriate set of conversion functions get applied They want some control over the usage pattern of strings, such that the 2-byte (UCS2) form is used whenever possible, and some restrictions are applied to the use of 1-byte (ASCII) nsCStrings. Original Document Information Author: Rick Gessner Last Updated Date: January 20, 1999 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Treehydra Manual - Archive of obsolete content
dra 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 provides the following callb...
...s 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 provides the following callbacks to analysis scripts: process_tree_decl, process_tree, process_tree_type, and process_cp_pre_genericize. FIXME document all these callbacks. C++ ASTs C++ ASTs are provided via the process_cp_pre_genericize callback. This is called just before GCC converts the C++-specific AST to the GENERIC (language-independent) representation. Example Treehydra script: function process_cp_pre_genericize(fn) { // fn is a FUNCTION_DECL, DECL_SAVED_TREE(fn) is AST print(fn); } GIMPLE ASTs GIMPLE ASTs are provided via the pr...
... 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 for double-locking in a simple mutex API in test/esp_lock.js. Abstract interpretation is a big topic, which is not yet fully documented here. For now, here is an explanation of some of the terminology that is often confusing: concrete value. A value in the programming language being analyzed. E.g., (int) 3. abstract value. A value used in the analysis script that represents a set of concrete values. E.g., nonzero. In ESP, these are user-defined. concrete state. A memory state in the programming language being analyzed. In other...
browser.type - Archive of obsolete content
<< XUL Reference home type Type: one of the values below. The type of browser, which can be used to set access of the document loaded inside the browser. If this is not set, the loaded document has the same access as the window containing the browser. More precisely: The document loaded into a chrome window is always of chrome type. Subdocuments of chrome documents are of chrome type, unless the container element (one of iframe, browser or editor) has one of the special type attribute values (the common ones are content, content-targetable and content-primary) indicating that the subdocument is of content type. ...
... content A browser for content. ...
...re of chrome type, unless the container element (one of iframe, browser or editor) has one of the special type attribute values (the common ones are content, content-targetable and content-primary) indicating that the subdocument is of content type. This boundary has a number of special effects, such as making window.top == window (unless the browser is added to a chrome document), and preventing documents from inheriting the principal of the parent document. The type attribute on all frames in content documents is ignored; subdocuments of content documents are always content documents. Warning: The type attribute must be set before the element is inserted into the document. content A browser for content. The content that is loaded inside the browser is not allowed to access the chrom...
label - Archive of obsolete content
pear on the element. If this is left out, no text appears. For an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. ...
...d to the menulist.value property upon user selection of the menuitem. ...
...e-big-label" command="the-big-button"/> <button id="the-big-button" label="Click me" oncommand="alert(document.getElementById('the-big-label').value)"/> <label id="myLabel" value="My label"/> <button label="Click me" oncommand="document.getElementById('myLabel').setAttribute('value','Value changed');" /> <checkbox label="my Checkbox" id="myCheckboX"/> <button label="Another click" oncommand="document.getElementById('myCheckboX').setAttribute('label','Still not checked');"/> <button label="Show label of checkbox" oncommand="alert( document.getElementById('myCheckboX').getAttribute('label') )"/> ...
XUL Events - Archive of obsolete content
you can retrieve the attribute that was modified using the event's attrName property, and you can retrieve the old and new values of the attribute using the event's prevValue and newValue properties. DOMNodeInserted This event is sent when a node is added as a child of a element. ...
... modified using the event's attrName property, and you can retrieve the old and new values of the attribute using the event's prevValue and newValue properties. DOMNodeInserted This event is sent when a node is added as a child of a element. If you capture this event at the document level, you can be notified of document changes. ...
... DOMNodeInserted This event is sent when a node is added as a child of a element. If you capture this event at the document level, you can be notified of document changes. DOMNodeRemoved This event is sent when a node is removed from an element. If you capture this event at the document level, you can be notified of document changes Warning: It should be noted that the addition of any mutation event listeners to a document degrades the performance of subsequent DOM operations in that document, and that removing the listeners later does not mitigate or reverse the effect. See Mutation events for more details and Mutation obser...
MenuButtons - Archive of obsolete content
the button is pressed by itself. This is accomplished by dividing the button into two parts, one with the label and image to carry out the default command and the second to show the menu. To create a button of this type, set the type attribute of the button to 'menu-button'. <toolbarbutton type="menu-button" label="Save" oncommand="alert('Save');"> <menupopup> <menuitem label="Save This Document"/> <menuitem label="Save All" oncommand="alert('Save All'); event.stopPropagation();"/> </menupopup> </toolbarbutton> Here, the 'Save' button has a type of 'menu-button', so a small arrow button will appear which will open the menu when pressed. Pressing the label part of the button will invoke the command event on the button, so the 'Save' alert will appear. However, we can associate a d...
...Save' button has a type of 'menu-button', so a small arrow button will appear which will open the menu when pressed. Pressing the label part of the button will invoke the command event on the button, so the 'Save' alert will appear. However, we can associate a different command with the items on the submenu. When the command is fired, it bubbles up through the chain of elements to the top of the document. When the first item on the menu ('Save This Document') is activated, it will also display the 'Save' alert as the command event bubbles up to the button. In this situation, this menuitem performs the same operation as pressing the regular part of the button. The second menu item ('Save All') has a command event of its own that displays a different alert with the text 'Save All'. The stopPropagat...
...s used to stop the bubbling effect so that the command event on the button does not get called as well. The effect is a button that performs one command with a menu for other commands. As with this example, the 'menu-button' type of button is usually used when the menu provides more specific options pertaining to the operation. We might want to extend this example to insert a list of the unsaved documents to the Save button menu so that each could be saved individually. You might want to set the first item in the example above as the default button, so it indicates to the user that the command is carried out when the main button is pressed. This can be done by setting the default attribute on the item to true. <menuitem label="Save This Document" default="true"/> See Indicating_the_Default_It...
MenuModification - Archive of obsolete content
Modifying a Menu Menus have a number of methods which may be used to add and remove items. Adding Items to a Menu The appendItem method may be used to append a new item to the end of the popup associated with a menu. This method will create a new menuitem element and insert it into the popup. This method may only be used with the menu element. <script> function addToMenu() { var menu = document.getElementById("edit-menu"); menu.appendItem("Insert", "insert"); } </script> <menu id="edit-menu"/> <button label="Add" oncommand="addToMenu()"/> In this example, the addToMenu function is called when the button is pressed. This function appends a new item to the menu's popup with the label Insert. The first argument to appendItem is the label of the menuitem, and the second argument is a v...
...u.appendItem("Insert", "insert"); item.accessKey = "I"; Appending Submenus There is no built-in method to append submenus to a menu. To do this, we instead need to use the inherited node modification methods available for all elements. First, we need to retrieve the menupopup for the menu, and then use the appendChild method to append a new item. <script> function addSubMenu() { var popup = document.getElementById("file-popup"); var newmenu = document.createElement("menu"); popup.appendChild(newmenu); newmenu.label = "New"; newmenu.appendItem("Document", "doc"); newmenu.appendItem("Image", "image"); } </script> <menu label="File" onpopupshowing="addSubMenu()"> <menupopup id="file-popup"/> </menu>. Comment: appendItem not working in TB 52.7.0. Workaround: add menupopup to menu.
...would also want to make sure to remove the items again in a popuphiding event listener. Otherwise, a new submenu would be added every time the menu is opened, which is clearly not desirable. Another possibility is to ensure that the menu is only added once. The following shows how the addSubMenu function above might be rewritten to handle this case. <script> function addSubMenu() { var popup = document.getElementById("file-popup"); if (popup.hasChildNodes()) return; var newmenu = document.createElement("menu"); popup.appendChild(newmenu); newmenu.label = "New"; newmenu.appendItem("Document", "doc"); newmenu.appendItem("Image", "image"); } </script> The hasChildNodes method may be used to check if a node has any children. The first time the function is called, the hasChildNode...
Panels - Archive of obsolete content
fferent technique as in the following example. <label value="Search" popup="search-panel"/> <panel id="search-panel"> <label control="search" value="Terms:"/> <textbox id="search"/> </panel> To attach a panel to an non-button element, for instance to have a panel open when a label is clicked, use the popup attribute. The popup attribute should be set to the id of a panel within the same document. When the left mouse button is pressed on the element with the popup attribute, the corresponding panel will be displayed. For instance, to attach the popup defined above to a label, use the following code: <label value="Search" popup="search-panel"/> The result is a search button which opens a panel for entering the search term. When using the popup attribute, the panel will appear with the t...
...details about both methods, see Opening and Closing Popups. Closing a panel A panel is closed automatically when the user clicks outside of the panel. It is quite common however, to have an element such as a button within the panel to close it as well. For instance, using the search panel example above, we could add a button which closes the panel when pressed: <script> function doSearch() { document.getElementById("search-panel").hidePopup(); } </script> <toolbarbutton label="Search" type="panel"> <panel id="search-panel" position="after_start"> <textbox id="search"/> <button label="Search" oncommand="doSearch();"/> </panel> </toolbarbutton> In this example, the doSearch() function is called when the "Search" button is pressed. This function retrieves the popup and calls the h...
...red at it. Although no element within the popup panel is focused by default, the user may focus the first element within the panel by pressing the Tab key. If you want to set the focus to an element by default when a panel is opened, adjust the focus within a popupshown event handler. For instance, to have the textbox initially focused in the example above: <panel id="search-panel" onpopupshown="document.getElementById('search').focus()"> To disable the adjusting of focus when a panel is opened, set the noautofocus attribute to true: <panel noautofocus="true"> This will cause the focus to remain on the element within the main window that has focus when the panel is opened. Note that this will also keep the focus within the panel when it is closed. When a panel is closed, the focus is remove...
Sorting and filtering a custom tree view - Archive of obsolete content
this is useful if this is an editable table //to prevent the user from losing the row they edited var topVisibleRow = null; if (table) { topVisibleRow = getTopVisibleRow(); } if (data == null) { //put object loading co...
...for strings, lowercases them function prepareForComparison(o) { if (typeof o == "string") { return o.toLowerCase(); } return o; } function getTopVisibleRow() { return tree.treeBoxObject.getFirstVisibleRow(); } function setTopVisibl...
..."string") { return o.toLowerCase(); } return o; } function getTopVisibleRow() { return tree.treeBoxObject.getFirstVisibleRow(); } function setTopVisibleRow(topVisibleRow) { return tree.treeBoxObject.scrollToRow(topVisibleRow); } function inputFilter(event) { //do this now rather than doing it at every comparison var value = prepareForComparison(event.target.value); setFilter(value); document.getElementById("clearFilter").disabled = value.length == 0; } function clearFilter() { document.getElementById("clearFilter").disabled = true; var filterElement = document.getElementById("filter"); filterElement.focus(); filterElement.value = ""; setFilter(""); } function setFilter(text) { filterText = text; loadTable(); } ...
Actions - Archive of obsolete content
content to generate in a template is specified using the <xul:action> element which should either be the next sibling of the <xul:query> element (if no rules need be specified) or be a direct child of a <xul:rule> element. The content to generate goes directly inside the action element. This content will be copied for each matching result (though see below for an exception) and inserted into the document. Let's look at a simple example first. <vbox datasources="http://www.xulplanet.com/ds/sample.rdf" ref="http://www.xulplanet.com/rdf/A"> <template> <query> <content uri="?start"/> <triple subject="?start" predicate="http://www.xulplanet.com/rdf/relatedItem" object="?relateditem"/> </query> <action> <button uri="?relateditem" labe...
...'s look at the results again: (?start = http://www.xulplanet.com/rdf/A, ?relateditem = http://www.xulplanet.com/rdf/B) (?start = http://www.xulplanet.com/rdf/A, ?relateditem = http://www.xulplanet.com/rdf/C) (?start = http://www.xulplanet.com/rdf/A, ?relateditem = http://www.xulplanet.com/rdf/D) The builder will start with the first result. The button element will be copied and inserted into the document after the template. The id attribute of the new element will be set to the same value of the member variable, ?relateditem. You could think of this as changing the uri attribute to the id attribute, and replacing the variable. Since the first result has a value of 'http://www.xulplanet.com/rdf/B' for the ?relateditem variable, the id will be set to this value. Then, the remaining attributes on th...
...lly, you wouldn't use an id attribute inside a template action since the id would be replaced anyway. In fact, any ids you put inside a template action will be ignored. However, you may use ids on the other parts of the template, such as within the query statements, if you wish to change the statements and rebuild the template. You can use getElementById to get at particular results, for instance document.getElementById("http://www.xulplanet.com/rdf/C") would retrieve the second generated button. After all the results have been examined, the DOM tree will look like the following: <vbox datasources="http://www.xulplanet.com/ds/sample.rdf" ref="http://www.xulplanet.com/rdf/A"> <template> <query> <content uri="?start"/> <triple subject="?start" predicate="http...
textbox (Toolkit autocomplete) - Archive of obsolete content
ed in different ways for different XUL Input Elements as listed below: onchange Type: script code TextBox When Enter key is pressed Radio/Check Box When the state is changed Select List When the selected item is changed What is accessible The script context at this point can only access the following things: Global Values/Functions i.e. ...
...s a character. If the user types another character, the timer resets. type Type: one of the values below You can set the type attribute to one of the values below for a more specialized type of textbox. Don't set the type if you wish to use a regular textbox. autocomplete A textbox that supports autocomplete. For more information about autocomplete textboxes, see the autocomplete documentation (XPFE [Thunderbird/SeaMonkey]) (Firefox) number A textbox that only allows the user to enter numbers. In addition, arrow buttons appear next to the textbox to let the user step through values. There are several attributes that allow the number textbox to be configured, including decimalplaces, min, max, increment, wraparound, hidespinbuttons, and textbox.value. password A textbox th...
... to the value autocomplete to have an autocomplete textbox. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
Textbox (XPFE autocomplete) - Archive of obsolete content
ed in different ways for different XUL Input Elements as listed below: onchange Type: script code TextBox When Enter key is pressed Radio/Check Box When the state is changed Select List When the selected item is changed What is accessible The script context at this point can only access the following things: Global Values/Functions i.e. ...
...s a character. If the user types another character, the timer resets. type Type: one of the values below You can set the type attribute to one of the values below for a more specialized type of textbox. Don't set the type if you wish to use a regular textbox. autocomplete A textbox that supports autocomplete. For more information about autocomplete textboxes, see the autocomplete documentation (XPFE [Thunderbird/SeaMonkey]) (Firefox) number A textbox that only allows the user to enter numbers. In addition, arrow buttons appear next to the textbox to let the user step through values. There are several attributes that allow the number textbox to be configured, including decimalplaces, min, max, increment, wraparound, hidespinbuttons, and textbox.value. password A textbox th...
... string Gets and sets the value of the userAction attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
) using overlays. Its intended audience is extension developers with a basic knowledge of XUL and CSS. We assume that you're also familiar with the basics of creating Firefox extensions and have the Hello World extension working. Another tutorial, which walks you through the entire process from the beginning, is also available. Creating an overlay The first step is to create an overlay for the document containing the toolbar you wish to enhance. Explaining overlays is beyond the scope of this tutorial -- you can read about them in the XUL Tutorial. To overlay a document, you need to know its URI. You can find a list of URIs for the most commonly overlaid documents at the bottom of this page. Note: Some people overlay chrome://messenger/content/mailWindowOverlay.xul. that should cause the butt...
...se 1: // Middle click break; case 2: // Right click break; } } To add more buttons, put more <toolbarbutton> elements inside the <toolbarpalette> element. Wrap elements other than <toolbarbutton> in <toolbaritem>. Adding the Button Bootstrap Style Adding a button to the BrowserPalette on runtime in a Bootstrap addon is a bit different because the BrowserPalette is indirectly reached. A simple document.getElementById('BrowserToolbarPalette') will not work. This is the code to create and add it in. let button = doc.createElement("toolbarbutton"); button.setAttribute("id", BUTTON_ID); button.setAttribute("label", "Replace Bookmark"); button.setAttribute("class", "toolbarbutton-1 chromeclass-toolbar-additional"); button.setAttribute("tooltiptext", "Replace an existing bookmark"); button.style.lis...
...nd then run on Gists@GitHub here: _ff-addon-snippet-AddToolbarButtonToPalette.js . It is based on the code from the repo above. Here are some discussions at Mozillazine about adding a toolbar button in a Bootstrap addon: Programmatically add a button to toolbar palette? The advantage to adding the toolbar button to the palette rather than creating an element and then appendChild to the toolbar (document.getElementById('nav-bar')) or appendChild to the addon bar (document.getElementById('addon-bar')) is that once in the toolbar palette, users can configure it through the customize menu. They can drag it to the addon bar or to the toolbar. Styling the button Most toolbar buttons have icons. To attach an image to the button we use standard Mozilla skinning facilities. If you're unfamiliar with ho...
Content Panels - Archive of obsolete content
Sometimes, you will want to change part of the window. A good example is a step-by-step wizard that guides you through a number of screens, asking a set of questions. Each time the user clicks the Next button, the next screen of the wizard is displayed. You could create a wizard interface by opening a different window for each screen. ...
... better if just the content area of the wizard changed. Third, it would be difficult to co-ordinate scripts when running in different windows. Note that XUL does have a wizard element which may be used to create wizard interfaces. This will be described in a later section. Another approach is to use the iframe element, which works much like the HTML element of the same name. It creates a separate document within the window. It has the advantage that it can be placed anywhere and the contents can be loaded from a different file. Set the URL to appear in the frame with the src attribute. This URL may point to any kind of file, although it will usually point to an HTML file or another XUL file. You can use a script to change the contents of the iframe without affecting the main window. In the Mozilla...
...appear in the frame with the src attribute. This URL may point to any kind of file, although it will usually point to an HTML file or another XUL file. You can use a script to change the contents of the iframe without affecting the main window. In the Mozilla browser window, the area where the web page is displayed is created by using an iframe. When the user enters a URL or clicks on a link in a document, the source of the frame is changed. iframe example Example 1 : Source View <toolbox> <toolbar id="nav-toolbar"> <toolbarbutton label="Back" /> <toolbarbutton label="Forward" /> <textbox id="urlfield" /> </toolbar> </toolbox> <iframe id="content-body" src="http://www.mozilla.org/index.html" flex="1" /> The example here has created a very simple interface for a web browser. ...
Creating a Window - Archive of obsolete content
will put this line at the top of every XUL file. You can also import other style sheets using a similar syntax. Note that you would normally import the global style sheet from within your own style sheet file. <window This line declares that you are describing a window. Each user interface window is described in a separate file. This tag is much like the HTML tag which surrounds an entire HTML document, except that a user interface window is described instead of a document. Several attributes can be placed in the window tag -- in this case there are four. In the example, each attribute is placed on a separate line but they do not have to be. id="findfile-window" The id attribute is used as an identifier so that the window can be referred to by scripts. You will usually put an id attribute on...
...type the URL (whether a chrome:, file: or other URL type) into the location bar in a Mozilla browser window. You should also be able to double-click the file in your file manager, assuming that XUL files are associated with Mozilla. The XUL window will appear in the browser 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 additi...
...This will open the window without the toolbars and menus and so forth that a normal browser window has. ...
Skinning XUL Files by Hand - Archive of obsolete content
global changes when the application is dynamically reskinned. To keep your XUL looking consistent and to avoid breaking skins altogether (when your styles have some dependency on a part of the global skin that changes, such as an image), use the style rules in the global skin by importing it into your stylesheet with the following instruction: @import url("chrome://global/skin/"); Refer to the document Writing Skinnable XUL and CSS for guidelines on how to make your skins friendly to the global skin, to XUL, and to Mozilla. Stylesheet Syntax To familiarize yourself with the global skin, open up the text file called global.css in the chrome/classic.jar!/skin/classic/global directory of the Mozilla application. In a cascading stylesheet, the style definitions have the following basic form: ele...
...ed as: <toolbar class="nav-bar" id="nav3"> <toolbarbutton label="Click me" /> <toolbarbutton label="Don't click me" /> ... </toolbar> will be styled with the CSS rules that appear in the block after the toolbar.nav-bar selector in the CSS example above. Similarly, the next item uses the ID selector to apply style information to a single XUL element. Since id attribute must be unique in a document, there can only be a single element with the ID "navbar", and it will pick up the style information in the block. The third type of selector, thepseudo-class, is one you may have seen in the in-line style definitions for hyperlinks which commonly appear in HTML documents. The pseudo-class is connected to an element (or not: you can also define styles that apply to any element in the state specif...
...ratized, in other words; the consumption and distribution of these interfaces is equally democratic. ...
Writing Skinnable XUL and CSS - Archive of obsolete content
Mozilla can have any number of installed UI packages, from Navigator to Sidebar to Editor. Each package has its own skin, CSS files and images that determine the appearance of that package. In our particular Mozilla skin, there is a special package calledglobal. This package contains a special skin called theglobal skin. If you wish for your package to blend in with the other packages, then the skin for your package should inherit information from the global skin in order to reduce the amount of duplication across packages and in order to make the UI as a whole easier to skin. ...
...c tag names, can be positively grotesque. I'll show you the evil rule I put into the global skin a few months back that was making trees slow. treehead treerow treecell { BAD! EVIL! YUCK! ... } This evil rule caused the style system, for every treecell that wasn't in a treehead (which is practically every treecell in a typical tree), to crawl up the whole parent chain to the root of the document in order to determine that the style rule wasn't a match. I'm usually seeing this rule misused by people who really wanted to use the child selector instead. That was my mistake with the above rule. I should have used treehead > treerow > treecell. After all, that's what I meant anyway. Never use an attribute selector rule for the class attribute. This is inefficient and you should just use...
... skin, then use <titledbutton> and style it rather than using <html:img>. ...
XUL Template Primer - Bindings - Archive of obsolete content
Warning: The content of this article may be out of date. See XUL:Template Guide for up to date documentation. Overview This document expands on the XUL Template Primer by introducing the <bindings> element in the extended XUL template syntax. The <bindings> element is used to create additional,optional variable bindings, in addition to those that are specified in a rule's <conditions>. This is different from the variables specified in the rule's conditions, where a value must be found for each variable for the rule to match. If a <binding> can't be matched, the rule will still fire. Example To illustrate how <bindings> work, we'll examine this XUL document, which builds a simple content model an RDF/XML file. <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin" t...
...mpy. However, in Lumpy's case, we won't be able to bind the ?addr variable because Lumpy has no home! (Well, there are no statements with Lumpy as the subject and a nc:address as the predicate, anyway.) Nevertheless, the rule still matches. In the content that's built for Lumpy's <hbox>, the second <label>'s value attribute (which should contain the value of ?street) is just left blank. Related Documents XUL Template Primer XUL template basics. XUL Template Primer - Multiple Rules Illustrates how to write templates with multiple <rule> elements. XUL Template Primer - Nested Content Illustrates how a template can be used recursively to build nested content. XUL Template Primer - Outliner Illustrates how a template can be used as a view for a XUL outliner. XUL Template Reference Descri...
...rimer - Outliner Illustrates how a template can be used as a view for a XUL outliner. XUL Template Reference Describes the simple XUL template syntax in detail. Notes 1. As of this writing, it is necessary to order <binding> elements carefully. Specifically, if a binding depends on a variable in another binding, it must appear after the binding it depends on. For example, the sample in this document wouldn't work if the two <binding> elements were reversed, because of the dependency on the ?addr variable. Fortunately, this is the natural way one would write bindings, so in practice this should not be a burden. Original Document Information Author: Chris Waterson ...
XUL accessibility tool - Archive of obsolete content
Information The XUL Accessibility Tool is a Firefox extension designed by Aaron Andersen of WebAIM as part of a Mozilla Foundation accessibility minigrant in the spring of 2007. It is designed to test (insofar as automated testing is possible) the guidelines and requirement for creating accessible XUL as set forth in the XUL accessibility guidelines, and to report on any problems found in tested documents. While not meant to be a comprehensive test suite (meaning that passing all included tests does not guarantee that an application is free of accessibility bugs or issues), many of the most common accessibility mistakes will be found and reported. Availability The XUL Accessibility Tool can currently be obtained from [http://www.xulplanet.com/aaron/files...bilitytool.xpi]. Future versions of the...
....0a+ Recent Sunbird builds Recent Songbird builds. It probably also works on Seamonkey, but I haven't verified this. Use To launch the tool after installation, look for an entry in the Tools menu of the host application, or hit Ctrl+Alt+Shift+F12. Once the tool window has loaded, select either a local file, web url, or currently open window from the File menu to generate a XUL report for that document. Be aware that the report might take a little while to be ready depending on the complexity of the application being analyzed and the speed of your machine. Future Work The following things have been suggested or are planned for a future version of the tool: New Tests: (aaronlev) Warning: hardcoded color and pixel sizings (aaronlev) Error: Duplicate accesskey in a dialog (already have this ...
... New Features: (aaronlev) Automatically test any new windows as they are opened. (aaronandy) Highlight or blink source element in original XUL app upon click of referencing line in report. (aaronlev) Compatibility with more XUL Applications. (aaronandy) Maybe an on...
XUL Coding Style Guidelines - Archive of obsolete content
d portable across user agents, we need to have a set of coding style guidelines to ensure our objectives are achievable. The author has collected a set of guidelines from various sources listed in the References section. While some of 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 localiz...
...lar, but use the pound sign instead of <!--<var>xxxxx</var>-->: # LOCALIZATION NOTE entity name : content We recognize that translation is a subset of localization even though we've consistently referred to our notes as "LOCALIZATION NOTE". Files not to be localized? Some files live in the tree but aren't really part of the build; they're just there as programming examples or a kind of source documentation. To prevent them from being localized, you may insert a line of comment following the XML declaration as follows. <?xml version="1.0" encoding='UTF-8'?> <!-- DO NOT localize this file: [reason...] it isn't part of the build; --> When translators see this line, they won't bother to look at the rest of the file. References XUL is discussed in depth in XUL Language Spec and XUL Window Langu...
...he file. References XUL is discussed in depth in XUL Language Spec and XUL Window Language. ...
listbox - Archive of obsolete content
istitem label="Ruby"/> <listitem label="Emerald"/> <listitem label="Sapphire" selected="true"/> <listitem label="Diamond"/> </listbox> <listbox id="theList" rows="10" width="400"> <listhead> <listheader label="1ct Gem" width="240"/> <listheader label="Price" width="150"/> </listhead> <listcols> <listcol/> <listcol flex="1"/> </listcols> </listbox> var theList = document.getElementById('theList'); gems = [ {gem: "Ruby", Price: "$3,500 - $4,600"}, {gem: "Emerald", Price: "$700 - 4,250"}, {gem: "Blue Sapphire", Price: "$3,400 - $4,500"}, {gem: "Diamond", Price: "$5,600 - $16,000"} ]; for (var i = 0; i < gems.length; i++) { var row = document.createElement('listitem'); var cell = document.createElement('listcell'); ...
...If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actio...
...er Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
menupopup - Archive of obsolete content
ing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. triggerNode Type: nsIDOMNode This read-only property holds the DOM node that generated the event triggering the opening of the popup. The value is null if the popup isn't open. ...
...gerEvent ) Return type: no return value Opens the popup relative to a specified node at a specific location. anchor The popup may be either anchored to another node or opened freely. To anchor a popup to a node, supply an anchor node and set the position to a string indicating the manner in which the popup should be anchored. The anchor node does not need to be in the same document as the popup. Unanchored popups may be created by supplying null as the anchor node. The direction in which the popup is oriented depends on the direction of the anchor. position Possible values for position are: before_start, before_end, after_start, after_end, start_before, start_after, end_before, end_after, overlap, and after_pointer. Check Positioning of the Popup Guide for a p...
...d_after, overlap, and after_pointer. Check Positioning of the Popup Guide for a precise description of the effect of the different values. x, y For an anchored popup, the x and y arguments may be used to offset the popup from its anchored position by some number, measured in CSS pixels. An unanchored popup appears at the position specified by x and y, relative to the viewport of the document containing the popup node. In this case, the position and attributesOverride arguments are ignored. isContextMenu The isContextMenu argument should be true for context menus and false for all other types of popups. It affects menu item highlighting; that is, while a context menu is open, menus opened earlier do not highlight or execute their items. attributesOverride I...
panel - Archive of obsolete content
Archive › Mozilla › XUL › panel
open: The popup is open and visible on screen. showing: A request has been made to open the popup, but it has not yet been shown. This state will occur during the popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. ...
...gerEvent ) Return type: no return value Opens the popup relative to a specified node at a specific location. anchor The popup may be either anchored to another node or opened freely. To anchor a popup to a node, supply an anchor node and set the position to a string indicating the manner in which the popup should be anchored. The anchor node does not need to be in the same document as the popup. Unanchored popups may be created by supplying null as the anchor node. The direction in which the popup is oriented depends on the direction of the anchor. position Possible values for position are: before_start, before_end, after_start, after_end, start_before, start_after, end_before, end_after, overlap, and after_pointer. Check Positioning of the Popup Guide for a p...
...d_after, overlap, and after_pointer. Check Positioning of the Popup Guide for a precise description of the effect of the different values. x, y For an anchored popup, the x and y arguments may be used to offset the popup from its anchored position by some number, measured in CSS pixels. An unanchored popup appears at the position specified by x and y, relative to the viewport of the document containing the popup node. In this case, the position and attributesOverride arguments are ignored. isContextMenu The isContextMenu argument should be true for context menus and false for all other types of popups. It affects menu item highlighting; that is, while a context menu is open, menus opened earlier do not highlight or execute their items. attributesOverride I...
preference - Archive of obsolete content
ed in different ways for different XUL Input Elements as listed below: onchange Type: script code TextBox When Enter key is pressed Radio/Check Box When the state is changed Select List When the selected item is changed What is accessible The script context at this point can only access the following things: Global Values/Functions i.e. ...
...ement) Returns true, if the given element is "editable" (see below). void setElementValue(in DOMElement element); Initializes the supplied element from the value stored in the preference. This function calls onsyncfrompreference. void updateElements(); Update all elements that observe this preference. ...
...rAll(), removeAttribute(), removeAttributeNode(), removeAttributeNS(), removeChild(), removeEventListener(), replaceChild(), setAttribute(), setAttributeNode(), setAttributeNodeNS(), setAttributeNS(), setUserData Events change When a preference value changes, an onchange/change event is fired on the <preference> element. You can handle this if you wish to. Related Preferences System documentation: Introduction: Getting Started | Examples | Troubleshooting Reference: prefwindow | prefpane | preferences | preference | XUL attributes ...
prefwindow - Archive of obsolete content
the id of the last selected pane. It will be opened by default the next time the preferences dialog is opened. preferencePanes Type: DOM NodeList Holds a list of all the prefpane elements in the window. type Type: string Gets and sets the value of the type attribute. ...
...s="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="my-config-dialog" title="My application: configuration" onunload="onUnload(event.target)"> </prefwindow> function onUnload(prefwindow) { // Do actions there like saving values, password setting (that is not handled as a preference), etc. return true; } Opening a modal sub dialog A sub dialog can only be opened via document.documentElement and not via window. Therefore, an example call to openSubDialog() would look like this: document.documentElement.openSubDialog("chrome://myextension/content/options-sub.xul", "", null) Issues when using prefpanes in prefwindow When you wish to put non-<prefpane> elements to prefwindow, you should place them after all of <prefpane>s. If you put other elements before the first <p...
...ut switching panes. This is due to bug 296418. ...
tooltip - Archive of obsolete content
open: The popup is open and visible on screen. showing: A request has been made to open the popup, but it has not yet been shown. This state will occur during the popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. ...
...gerEvent ) Return type: no return value Opens the popup relative to a specified node at a specific location. anchor The popup may be either anchored to another node or opened freely. To anchor a popup to a node, supply an anchor node and set the position to a string indicating the manner in which the popup should be anchored. The anchor node does not need to be in the same document as the popup. Unanchored popups may be created by supplying null as the anchor node. The direction in which the popup is oriented depends on the direction of the anchor. position Possible values for position are: before_start, before_end, after_start, after_end, start_before, start_after, end_before, end_after, overlap, and after_pointer. Check Positioning of the Popup Guide for a p...
...d_after, overlap, and after_pointer. Check Positioning of the Popup Guide for a precise description of the effect of the different values. x, y For an anchored popup, the x and y arguments may be used to offset the popup from its anchored position by some number, measured in CSS pixels. An unanchored popup appears at the position specified by x and y, relative to the viewport of the document containing the popup node. In this case, the position and attributesOverride arguments are ignored. isContextMenu The isContextMenu argument should be true for context menus and false for all other types of popups. It affects menu item highlighting; that is, while a context menu is open, menus opened earlier do not highlight or execute their items. attributesOverride I...
window - Archive of obsolete content
It is by default a horizontally oriented box. As it is a box, all box attributes can be used. By default, the window will have a platform-specific frame around it. To set an icon for the window, create a platform-specific icon file <windowid>.ico and/or <windowid>.xpm and place or install these files into the <mozilla-directory>/chrome/icons/default/ directory. The <windowid> is the value of the id attribute on the window. ...
...ue to disable chrome in the window. This is used to hide chrome when showing in-browser UI such as the about:addons page, and causes the toolbars to be hidden, with only the tab strip (and, if currently displayed, the add-on bar) left showing. Note: This has no effect if the tabs on top preference is turned off. disablefastfindType: booleanPut disablefastfind="true" on the root element of a XUL document, which is intended to be loaded in a tab, to disable the find bar for the tab with this document. This is used to prevent the find bar from being displayed when it's not supported by the content (such as in the Add-ons manager tab). drawintitlebar Type: boolean If this attribute is true, the top of the window's content area will begin at the top edge of the title bar, instead of below the tit...
...ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
How to enable locale switching in a XULRunner application - Archive of obsolete content
selectedItem = listitem;...
...Code to ...
...plication must be restarted to activate the new choice. Here is an example event handler which is fired when the user clicks on the button to change the locale. It saves the new locale to the user application preferences (thereby overriding the default prefs.js above) and then asks XULRunner to restart. function changeLocale() { try { // Which locale did the user select? var localeListbox = document.getElementById("locale-listbox"); var newLocale = localeListbox.selectedItem.value; // Write preferred locale to local user config var prefs = Components.classes["@mozilla.org/preferences-service;1"]. getService(Components.interfaces.nsIPrefBranch); prefs.setCharPref("general.useragent.locale", newLocale); // Restart application var appStartup = Components.cl...
Mozprofile - Archive of obsolete content
Mozprofile is a python tool for creating and managing profiles for Mozilla's applications (Firefox, Thunderbird, etc.). In addition to creating profiles, mozprofile can install addons and set preferences. Mozprofile can be utilized from the command line or as an API. Command Line Usage mozprofile may be used to create profiles, set preferences in profiles, or install addons into profiles. The profile to be operated on may be specified with the --profile switch. ...
... preferences from an .ini file or the --pref switch, the value will be interpolated as an integer or a boolean (true/false) if possible. Setting Permissions mozprofile also takes care of adding permissions to the profile. ...
... profile. See https://github.com/mozilla/mozbase/b...permissions.py Resources Other Mozilla programs offer additional and overlapping functionality for profiles. There is also substantive documentation on profiles and their management. ProfileManager : XULRunner application for managing profiles. ...
Adobe Flash - Archive of obsolete content
Scriptability refers to the ability of plugins to interact with JavaScript. In particular, the Macromedia(R) Flash(TM) plugin exposes certain plugin functionality for access via JavaScript. It can also access JavaScript methods from within the plugin. This article explains how JavaScript can be used to access methods from within the Flash plugin, as well as how a feature called FSCommands can be used to access JavaScript functions from within the Flash animation. The focus of this article is to present tips on scripting Flash within Gecko(TM)-based web browsers. Detecting the Right Flash Plugin (and browser) Adobe Flash has exposed the scriptability feature in Netscape Gecko browsers since Flash 6r49 and later. ...
... to the HTML element that spawns the plugin. This may be the embed element or the object element's name or ID attribute respectively. Treat the handle to the HTML element as a handle to the actual Flash plugin and invoke the published methods on it. The illustrative code snippet below shows this idea: <object id="myFlash" ..... > <param name="movie" value="somefile.swf" /> .... var myFlash = document.getElementById("myFlash").SetVariable("myVar", sendText); A more expanded code example that shows how Example 2 was created is shown in this source listing. FSCommands: Accessing JavaScript from Flash Note: FSCommand may not work with Flash Player versions older than version 8 if the user has installed multiple Mozilla based browsers onto the same machine (see bug 32048 and bug 233533). In...
... In the above code listing, the JavaScript function handles what Flash sends it, and is named the same as the embed element's name attribute, concatenated with "_DoFSCommand". The source listing flash-to-js.html shows a source for this example. ...
Common Firefox theme issues and solutions - Archive of obsolete content
Operating system specific issues Windows 7 Windows 7 Aero missing right-hand title bar buttons When tabs are on top and the menu bar is disabled, Firefox is missing the min/max/restore/close button on the right side of the title bar. ...
... Operating system specific issues Windows 7 Windows 7 Aero missing right-hand title bar buttons When tabs are on top and the menu bar is disabled, Firefox is missing the min/max/restore/close button on the right side of the title bar. ...
...oz-transition style property. Use CSS standard transition property instead (supported by Firefox since Firefox 4). Resources AMO Editors Theme Testing Guidelines When developing and testing your themes, please refer to the theme testing guidelines AMO editors use to review themes. This guide will help you thoroughly test your theme to find and fix issues before you push updates to AMO. This is document is a work in progress so feedback and/or suggestions is appreciated. MDN CSS Reference Mozilla's Developer Network maintains a great CSS reference. AMO Themes Forum We'd like to encourage you to participate in the AMO (addons.mozilla.org) forums theme forum. MozillaZine Themes Forum MozillaZine is NOT an official Mozilla website, but it does have the largest community of Firefox theme deve...
CSS - Archive of obsolete content
Archive › Web › CSS
.-ms-content-zoomingThe -ms-content-zooming CSS property is a Microsoft extension that specifies whether zooming is enabled.-ms-filterThe -ms-filter CSS property is a Microsoft extension that sets or retrieves the filter or collection of filters applied to an object.-ms-flow-fromThe -ms-flow-from CSS property is a Microsoft extension that gets or sets a value identifying a region container in the document that accepts the content flow from the data source.-ms-flow-intoThe -ms-flow-into CSS property is a Microsoft extension that gets or sets a value identifying an iframe container in the document that serves as the region's data source.-ms-high-contrast-adjustThe -ms-high-contrast-adjust CSS property is a Microsoft extension that gets or sets a value indicating whether to override any CSS propertie...
...However, those elements' ancestors have this pseudo-class applied to them.:-moz-system-metric()This page was auto-generated because a user created a sub-page to this page.::-ms-browseThe ::-ms-browse CSS pseudo-element is a Microsoft extension that represents the button that opens the file picker of <input type="file">.::-ms-checkThe ::-...
...er shapes.-ms-wrap-throughThe -ms-wrap-through CSS property is a Microsoft extension that specifies how content should wrap around an exclusion element.:-moz-full-screen-ancestorThe :-moz-full-screen-ancestor CSS pseudo-class is a Mozilla extension that represents all ancestors of the full-screen element, except containing frames in parent documents, which are the full-screen element in their own documents. However, those elements' ancestors have this pseudo-class applied to them.:-moz-system-metric()This page was auto-generated because a user created a sub-page to this page.::-ms-browseThe ::-ms-browse CSS pseudo-element is a Microsoft extension that represents the button that opens the file picker of <input type="file">.::-ms-checkThe ::-ms-check CSS pseudo-element is a Microsoft extension that ...
ActiveXObject - Archive of obsolete content
t(servername.typename[, location]) Parameters servername The name of the application providing the object. typename The type or class of the object to create. location Optional The name of the network server where the object is to be created. Remarks Automation servers provide at least one type of object. For example, a word-processing application may provide an application object, a document object, and a toolbar object. You may be able to identify servername.typename values on a host PC in the HKEY_CLASSES_ROOT registry key. For example, here are a few examples of values you may find there, depending on which programs are installed: Excel.Application Excel.Chart Scripting.FileSystemObject WScript.Shell Word.Document Important: ActiveX objects may ...
...y settings in Internet Explorer for the relevant security zone. For example, for the local intranet zone, you typically need to change a custom setting to "Initialize and script ActiveX controls not marked as safe for scripting." To identify members of an automation object that you can use in your code, you may need to use a COM object browser, such as the OLE/COM Object Viewer, if no reference documentation is available for the Automation object. To create an Automation object, assign the new ActiveXObject to an object variable: var ExcelApp = new ActiveXObject("Excel.Application"); var ExcelSheet = new ActiveXObject("Excel.Sheet"); This code starts the application creating the object (in this case, a Microsoft Excel worksheet). Once an object is created, you refer to it in code using the o...
...ake Excel visible through the Application object. ExcelSheet.Application.Visible = true; // Place some text in the first cell of the sheet. ExcelSheet.ActiveSheet.Cells(1,1).Value = "This is column A, row 1"; // Save the sheet. ExcelSheet.SaveAs("C:\\TEST.XLS"); // Close Excel with the Quit method on the Application object. ExcelSheet.Application.Quit(); 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. Not supported in Windows 8.x Store apps. Note: Creating an ActiveXObject on a remote server is not supported in Internet Explorer 9 standards mode, Internet Explorer 10 standards mode, Internet ...
Enumerator - Archive of obsolete content
s, you can move the current item pointer only to the first or next element of a collection. The Enumerator object provides a way to access any member of a collection and behaves similarly to the For...Each statement in VBScript. ...
... Methods Enumerator.atEnd Returns a Boolean value indicating if the enumerator is at the end of the collection. Enumerator.item Returns the current item in the collection. Enumerator.moveFirst Resets the current item in the collection to the first item. Enumerator.moveNext Moves the...
...o properties. Methods Enumerator.atEnd Returns a Boolean value indicating if the enumerator is at the end of the collection. Enumerator.item Returns the current item in the collection. Enumerator.moveFirst Resets the current item in the collection to the first item. Enumerator.moveNext Moves the current item to the next item in the collection. 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. ...
LiveConnect - Archive of obsolete content
Script 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 Liveconnect. LiveConn...
...introduced by the decline of the original LiveConnect (e.g., java.lang.String and arrays not working properly). ...
...jects, and scripts may directly call applet methods (using the syntax document.applets.name.methodName()). Standard Java objects are also available for creation and manipulation by Javascript code (e.g. by writing code like "new java.lang.String('javascript string')" for classes in the java.* package hierarchy, or using a new "Packages" object for classes outside this hierarchy). Old LiveConnect documents, broken links: Java Method Overloading and LiveConnect 3 The technique that LiveConnect uses to invoke overloaded Java methods from JavaScript. LiveConnect Exceptions How do Java and JavaScript catch exceptions generated by the other party? Liveconnect Testcases Determine that applets within different html tags work properly. NOTE: LiveConnect Blocked under Some Conditions Li...
XForms Custom Controls Examples - Archive of obsolete content
xamples. A full example showing a complete form can be found on XForms:Custom_Controls. ...
...ame="_domparser">null</field> <property name="domparser" readonly="true"> <getter> if (!this._domparser) this._domparser = new DOMParser(); return this._domparser; </getter> </property> <method name="refresh"> <body> // Get new value, parse, and import it. ...
...mparser) this._domparser = new DOMParser(); return this._domparser; </getter> </property> <method name="refresh"> <body> // Get new value, parse, and import it. ...
Troubleshooting XForms Forms - Archive of obsolete content
re 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, make sure that has .xhtml or .xml as the file ending. If you are loading the form from a server, make sure that it serves the files as either application/xhtml+xml or text/xml. Che...
...f the namespace is not the empty namespace. If your binding expression starts with a /, make sure the first thing is the name of the root node of the instance. If your binding expression contains a /, look for any containing xf:group, xf:repeat, xf:input or other elements that set the context node. instance(...) Not Working Be aware that the instance(...) returns an element node, and not the document node. So with an instance like this: <xf:instance id="ins2" xmlns=""> <data> <value>42</value> </data> </xf:instance> You should use <output ref="instance('ins2')/value"/> to show the contents of the value element. (specification). Repeat And Tables Not Working Unfortunately you cannot do: <table> <xf:repeat nodeset="..."> <tr> ... </tr> </xf:repeat> </ta...
...eat nodeset="..."> <tr> ... </tr> </xf:repeat> </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 cro...
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
at do we follow). Organizations implement internal procedural standards so they are able to operate efficiently. They may also incorporate external procedural and/or technical standards. Technical standards have traditionally been pioneered through consortiums or standards bodies. The technical standards can be either public, standards-based or a proprietary de facto standard. The purpose of this document is to discuss and emphasize the importance of conforming to open technology standards that are external to the organization. Let's begin the discussion, however, by looking inward to internal procedures, processes and standards. Why should organizations have standard procedures at every level? Following standards is certainly not a new organizational phenomenon; organizations require their emplo...
...d 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. With processes, organizations can make release schedules, implement marketing plans, analyze resource allocations, and m...
...n organization vulnerable and open to obsolescence when the owner of the de facto changes focus or direction, or abandons the de facto altogether and renders the standard stagnate. On the other hand, by adopting open technology standards and participating in the development and direction of those standards, an organization is providing a path for future development, growth and revenue. Original Document Information Author(s): Beth Epperson Last Updated Date: 7 November 2014 ...
Fixing Table Inheritance in Quirks Mode - Archive of obsolete content
In version 4 browsers such as Netscape Navigator 4.x and Internet Explorer 4.x, tables generally "broke" the inheritance of font styling. If the author had set a font size on the body element, for example, the font size of text within a table would match the user's default, not the body style. ...
... -moz-initial; font-variant: -moz-initial; } This rule sets all aspects of a table's font, except for the font family, to match the user's preferences setting, thus emulating the behavior of old browsers. This only happens when Gecko is in "quirks" mode; in "standards" mode, all styles are inherited by tables as permitted by the CSS specification. In those cases where it is necessary to author documents in "quirks" mode, but the breaking of table inheritance is not desired, authors can use Gecko's standards support to overcome the table-font rule shown above. The value -moz-initial is a proprietary value used to apply the user's (or browser's) default setting for a given property to an element. Because it is not actually part of CSS, it is marked with the prefix -moz- in order to avoid confusi...
...avior */ table, caption { font-size: inherit; font-weight: inherit; font-style: inherit; font-variant: inherit; } This rule will override the rule in quirk.css and thus allow the author to have reliable inheritance of font styles into tables when in "quirks" mode. It is also fully valid CSS2 and so will validate without incident. Recommendations In situations where authors must put a document into "quirks" mode but wish to enforce correct font inheritance into tables, use the demonstrated rule. Related Resources Mozilla's DOCTYPE sniffing Original Document Information Author(s): Eric A. Meyer, Netscape Communications Last Updated Date: Published 26 Nov 2002 Copyright Information: Copyright (C) 2001-2003 Netscape. All rights reserved. Note: This reprinted article was orig...
Mozilla's DOCTYPE sniffing - Archive of obsolete content
Obsolete since Gecko 2 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) 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. This page describes behavior of the old HTML parser in Firefox 3.6 and older. It has been replaced by a new HTML 5 parser in Firefox 4 and newer. This document describes how Mozilla uses the DOCTYPE declaration to determine strict mode vs. quirks mode. The code that makes this determination is currently in DetermineParseMode() in nsParser.cpp. See bug 1312 and bug 55264 for some of the history of the mode determination. See bug 153032 for the creation of the Almost-Standards mode around Mozilla 1.0. The goals that led to choosing this behavior were the following...
... trigger strict mode. Pages written using any public identifiers in DOCTYPE declarations that appear in the future should be displayed using strict mode. In other words, the algorithm is the best approximation we can find for determining which pages were written after Mozilla became a known important user-agent on the Web. Full Standards Mode The following trigger full standards mode: Any document sent with an XML MIME type such as text/xml, application/xml, or application/xhtml+xml (since sniffing only occurs for documents sent as text/html). Any "DOCTYPE HTML SYSTEM" as opposed to "DOCTYPE HTML PUBLIC", except for the IBM doctype noted below A DOCTYPE declaration without a DTD, i.e., <!DOCTYPE HTML>. A DOCTYPE declaration with an internal subset. Any unknown doctype, which should inc...
...HTML//EN". The public identifier "-//Metrius//DTD Metrius Presentational//EN". ...
Popup Window Controls - Archive of obsolete content
Detecting Suppressed Popups Windows ...
...an notify the user and ask them to add your site to the list of sites which are allowed to use unsolicited popup windows. You can also provide a hyperlink which can be used to open a popup window even in the event that the user has suppressed unsolicited popups on your site. Replacements for Popup Windows If your popup was created during the time the web page was loading, you may consider using document.write() to emit appropriate HTML which will contain the same information as the popup window. You can also use either the advanced features in the Document Object Model (DOM) or innerHTML to create the appropriate HTML. Example The example tag links to devedge-temp.mozilla.org This example illustrates detecting suppressed popup windows as well as an approach for replacing popup windows with inl...
...ch will contain the same information as the popup window. You can also use either the advanced features in the Document Object Model (DOM) or innerHTML to create the appropriate HTML. Example The example tag links to devedge-temp.mozilla.org This example illustrates detecting suppressed popup windows as well as an approach for replacing popup windows with inline HTML using innerHTML. Original Document Information Author(s): Bob Clary Last Updated Date: December 5th, 2002 Copyright (C) 2001-2003 Netscape. ...
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
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 been added to the DOM code asking a plugin to return a scriptable iid and a pointer to a scriptable instance object. The old Plugin API call NPP_GetValue is used to retrieve this information from the plugin. So the plugin project should be aware of two new ...
... 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 nsITestPlugin.idl with the ...
...Ranganathan Last Updated Date: October 26, 2001 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Building up a basic demo with A-Frame - Game development
lable 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). ...
.... (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"> <title>MDN Games: A-Frame demo</title> <script src="aframe.min.js"></script> </head> <body> <!-- HTML goes here --> </body> </html> This contains some basic information like the document charset and <title>. The <script> element include...
...ions than a smooth material) and metalness (how metallic the material is). Adding some JavaScript to the mix It is possible to populate the scene with entities created using JavaScript too, so let's use it to add a third shape, a cylinder. Add a new <script> element at the end of the <body> element, just after the <a-scene> element, then add the following JavaScript code inside it: var scene = document.querySelector('a-scene'); var cylinder = document.createElement('a-cylinder'); cylinder.setAttribute('color', '#FF9500'); cylinder.setAttribute('height', '2'); cylinder.setAttribute('radius', '0.75'); cylinder.setAttribute('position', '3 1 0'); scene.appendChild(cylinder); We're getting a reference to the scene handler first, then we create the cylinder element as an A-Frame entity. After that ...
Mobile touch controls - Game development
t 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. ...
...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. ...
... a mobile device. We will use two events: touchstart and,touchmove both handled by one function. ...
Create the Canvas and draw on it - Game development
PreviousNext >> This is the 1st step out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson1.html. Before we can start writing the game's functionality, we need to create a basic structure to render the game inside. This can be done using HTML and the <canvas> element. ...
... lesson at Gamedev-Canvas-workshop/lesson1.html. Before we can start writing the game's functionality, we need to create a basic structure to render the game inside. This can be done using HTML and the <canvas> element. The game's HTML The HTML document structure is quite simple, as the game will be rendered entirely on the <canvas> element. ...
...o 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 a reference to it in JavaScript. 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. Then we're creating the ctx variable to store the 2D rendering context -- the actual tool we can use to paint on the Canvas. Let's see an example piece of code that prints a red square on the canvas. Add this below your previous lines of JavaScript, then ...
Initialize the framework - Game development
n how to use Gamedev Phaser. After completing this tutorial you can find the source code for this section at Gamedev-Phaser-Content-Kit/demos/lesson01.html. Before we can start writing the game's functionality, we need to create a basic structure to render the game inside. This can be done using HTML -- the Phaser framework will generate the required <canvas> element. ...
... writing the game's functionality, we need to create a basic structure to render the game inside. This can be done using HTML -- the Phaser framework will generate the required <canvas> element. The game's HTML The HTML document structure is quite simple, as the game will be rendered entirely on the <canvas> element generated by the framework. ...
...</script> </head> <body> <script> var game = new Phaser.Game(480, 320, Phaser.CANVAS, null, { preload: preload, create: create, update: update }); function preload() {} function create() {} function update() {} </script> </body> </html> Downloading the Phaser code Next, we need to go through the process of downloading the Phaser source code and applying it to our HTML document. This tutorial uses Phaser V2 -- it won't work with the current version on Phaser (V3). The V2 library is still available on the Phaser download page, below the links for the V3 download. Go to the Phaser download page. Choose an option that suits you best -- I would recommend the min.js option as it keeps the source code smaller, and you are unlikely need to go through the source code anyway...
Plug-in Development Overview - Gecko Plugin API Reference
owser calls the plug-in to inform it that the stream was created and to push more data. In streams produced by the plug-in, by contrast, the plug-in calls Netscape functions to create a stream, push data into it, and delete it. Working with URLs The Plug-in API provides methods that plug-ins can use to retrieve data from or post data to a URL anywhere on the network, provide hyperlinks to other documents, post form data to CGI scripts using HTTP, or upload files to a remote server using FTP. Use NPN_GetURL to request the browser to load a URL into a particular browser window or frame for display, or to deliver the data of that URL to the plug-in instance in a new stream. The NPN_GetURLNotify function operates like NPN_GetURL, except that it notifies the plug-in of the result when the operati...
...articular browser window or frame for display, or delivered to the plug-in instance in a new stream. The NPN_PostURLNotify function operates like NPN_PostURL, except that it notifies the plug-in of the result when the operation completes. For information about using these methods, see URLs. Starting in Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7), you can get the origin of the document in a secure, convenient way by calling NPN_GetValue() to retrieve the value of the variable NPNVdocumentOrigin. The returned value is the Unicode serialization of the document's origin converted to NFKC-encoded (that is, normalized) UTF-8. Your plug-in must free the returned string's memory by calling NPN_MemFree() when you're done with it. Getting Version and UI Information The Netscape group ...
...d 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 && thePlugin.advanceToNextSong) thePlugin.advanceToNextSong(); else alert("Plugin not installed correctly"); </script> In the past, LiveConnect and later XPConnect were used to make plug-ins scriptable. See the Wikipedia article for historical information. Both technologies are now obsolete for the purposes of plug-in scriptability, and th...
Normal Flow - Learn web development
efore we begin to make changes. As detailed in the last lesson introducing layout, elements on a webpage lay out in the normal flow, if you have not applied any CSS to change the way they behave. And, as we began to discover, you can change how elements behave either by adjusting their position in that normal flow, or removing them from it altogether. ...
... that normal flow, or removing them from it altogether. Starting with a solid, well-structured document that is readable in normal flow is the best way to begin any webpage. It ensures that your content is readable, even if the user is using a very limited browser or a device such as a screen reader that reads out the content of the page. In addition, as normal flow is designed to make a readable document, by starting in this way you are working with the document rather than fighting against it as you make changes to the layout. Before digging deeper into different layout methods, it is worth revisiting some of the things you will have studied in previous modules with regard to normal document flow. How are elements laid out by default? First of all, individual element boxes are laid out by tak...
...block level element. If there isn't space, then the overflowing text or elements will move down to a new line. If two adjacent elements both have the margin set on them and the two margins touch, the larger of the two remains, and the smaller one disappears -- this is called margin collapsing, and we have met this before too. Let's look at a simple example that explains all of this: <h1>Basic document flow</h1> <p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p> <p>By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p> <p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one...
CSS basics - Learn web development
a style sheet language. CSS is what you use to selectively style HTML elements. For example, this CSS selects paragraph text, setting the color to red: p { color: red; } Let's try it out! Using a text editor, paste the three lines of CSS (above) into a new file. Save the file as style.css in a directory named styles. To make the code work, we still need to apply this CSS (above) to your HTML document. Otherwise, the styling won't change the appearance of the HTML. (If you haven't been following our project, pause here to read Dealing with files and HTML basics.) Open your index.html file. Paste the following line in the head (between the <head> and </head> tags): <link href="styles/style.css" rel="stylesheet"> Save index.html and load it in your browser. You should see something like...
...lways be 600 pixels wide. margin: 0 auto; When you set two values on a property like margin or padding, the first value affects the element's top and bottom side (setting it to 0 in this case); the second value affects the left and right side. (Here, auto is a special value that divides the available horizontal space evenly between left and right). You can also use one, three, or four values, as documented in Margin Syntax. background-color: #FF9500; This sets the element's background color. This project uses a reddish orange for the body background color, as opposed to dark blue for the <html> element. (Feel free to experiment.) padding: 0 20px 20px 20px; This sets four values for padding. The goal is to put some space around the content. In this example, there is no padding on the top of the...
...ark blue for the <html> element. (Feel free to experiment.) padding: 0 20px 20px 20px; This sets four values for padding. The goal is to put some space around the content. In this example, there is no padding on the top of the body, and 20 pixels on the right, bottom and left. The values set top, right, bottom, left, in that order. As with margin, you can use one, two, three, or four values, as documented in Padding Syntax. border: 5px solid black; This sets values for the width, style and color of the border. In this case, it's a five-pixel-wide, solid black border, on all sides of the body. Positioning and styling the main page title h1 { margin: 0; padding: 20px 0; color: #00539F; text-shadow: 3px 3px 1px black; } You may have noticed there's a horrible gap at the top of the body...
Video and audio content - Learn web development
Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, familiarity with HTML fundamentals (as covered in Getting started with HTML) and Images in HTML. ...
...al component. Other than this, <audio> supports all the same features as <video> -- review the above sections for more information about them. Restarting media playback At any time, you can reset the media to the beginning--including the process of selecting the best media source, if more than one is specified using <source> elements--by calling the element's load() method: const mediaElem = document.getElementById("my-media-element"); mediaElem.load(); Detecting track addition and removal You can monitor the track lists within a media element to detect when tracks are added to or removed from the element's media. For example, you can watch for the addtrack event being fired on the associated AudioTrackList object (retrieved via HTMLMediaElement.audioTracks) to be informed when audio tracks...
...em.load(); Detecting track addition and removal You can monitor the track lists within a media element to detect when tracks are added to or removed from the element's media. For example, you can watch for the addtrack event being fired on the associated AudioTrackList object (retrieved via HTMLMediaElement.audioTracks) to be informed when audio tracks are added to the media: const mediaElem = document.querySelector("video"); mediaElem.audioTracks.onaddtrack = function(event) { audioTrackAdded(event.track); } You'll find more information about this in our TrackEvent documentation. Displaying video text tracks Now we'll discuss a slightly more advanced concept that is really useful to know about. Many people can't or don't want to hear the audio/video content they find on the Web, at least...
General asynchronous programming concepts - Learn web development
until the web app returns control of the processor. Let's look at a couple of examples that show what we mean by blocking. ...
...The code runs in the order it appears in the source, and ...
...n dates then logs the final one to the console) and then adds a paragraph to the DOM: const btn = document.querySelector('button'); btn.addEventListener('click', () => { let myDate; for(let i = 0; i < 10000000; i++) { let date = new Date(); myDate = date } console.log(myDate); let pElem = document.createElement('p'); pElem.textContent = 'This is a newly-added paragraph.'; document.body.appendChild(pElem); }); When running the example, open your JavaScript console then click the button -- you'll notice that the paragraph does not appear until after the dates have finished being calculated and the console message has been logged. 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: ...
Storing the information you need — Variables - Learn web development
sole (see What are browser developer tools for more information on how to access this tool). 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. But one special thing about variables is that their contained values can change. Let's look at a simple example: <button>Press me</button> const button = document.querySelector('button'); button.onclick = function() { let name = prompt('What is your name?'); alert('Hello ' + name + ', nice to see you!'); } In this example pressing the button runs a couple of lines of code. The first line pops a box up on the screen that asks the reader to enter their name, and then stores the value in a variable. The second line displays a welcome message that incl...
...iline JavaScript program that declares and initializes a variable, you can actually declare a variable with var after you initialize it and it will still work. For example: myName = 'Chris'; function logName() { console.log(myName); } logName(); var myName; Note: This won't work when typing individual lines into a JavaScript console, just when running multiple lines of JavaScript in a web document. This works because of hoisting -- read var hoisting for more detail on the subject. Hoisting no longer works with let. If we changed var to let in the above example, it would fail with an error. This is a good thing -- declaring a variable after you initialize it results in confusing, harder to understand code. Secondly, when you use var, you can declare the same variable as many times as yo...
...of JavaScript! So, you can't use words like var, function, let, and for as variable names. Browsers recognize them as different code items, and so you'll get errors. Note: You can find a fairly complete list of reserved keywords to avoid at Lexical grammar -- keywords. Good name examples: age myAge init initialColor finalOutputValue audio1 audio2 Bad name examples: 1 a _12 myage MYAGE var Document skjfndskjfnbdskjfb thisisareallylongstupidvariablenameman Try creating a few more variables now, with the above guidance in mind. Variable types There are a few different types of data we can store in variables. In this section we'll describe these in brief, then in future articles, you'll learn about them in more detail. So far we've looked at the first two, but there are others. Numbers Y...
Handling common HTML and CSS problems - Learn web development
or example you could put something like this in your IE stylesheet: aside, main, article, section, nav, figure, figcaption { display: block; } It isn't that simple, however -- you also need to create a copy of each element you want to style in the DOM via JavaScript, for them to be styleable; this is a strange quirk, and we won't bore you with the details here. For example: const asideElem = document.createElement('aside'); ... This sounds like a pain to deal with, but fortunately there is a polyfill available that does the necessary fixes for you, and more besides -- see HTML5Shiv for all the details (see manual installation for the simplest usage). Selector support Of course, no CSS features will apply at all if you don't use the right selectors to select the element you want to style! ...
...xample, make a local copy of selectivizr-example-start.html. If you look at this running live, you'll see that it contains two paragraphs, one of which is styled. We've selected the paragraph with p:first-child, which won't work in old versions of IE. Now download MooTools and Selectivizr, and save them in the same directory as your sample HTML. Put the following code into the head of your HTML document, just before the opening <style> tag: <script type="text/javascript" src="MooTools-Core-1.6.0.js"></script> <!--[if (gte IE 6)&(lte IE 8)]> <script type="text/javascript" src="selectivizr-min.js"></script> <![endif]--> If you try running this in an old version of IE, it should work fine. Handling CSS prefixes Another set of problems comes with CSS prefixes -- these are a m...
...on and choose Inspect/Inspect element (or whatever the option is in your browser) -- this should open up the dev tools in your browser, with the element highlighted in the DOM inspector. Look for a feature you can use to select that element. For example, at the time of writing, the main Google logo had an ID of hplogo. ...
Information for External Developers Dealing with Accessibility
Accessibility API cross reference Should be helpful at anyone looking at implementing accessibility API support for a product on multiple platforms. Contains info on accessible roles, states and events. Accessible Toolkit Checklist A list of what needs to be done for accessibility when building new toolkits, widget by widget. ...
...cessibility when building new toolkits, widget by widget. In addition, here is a list of official keyboard UI guidelines for each desktop: Windows keys: Guidelines on keyboard UI design and on implementing keyboard shortcuts: An excellent resource from Microsoft. ...
...ys, known keyboard shortcuts, explains how to create keyboard shortcuts, explains appropriate use for the arrow keys, how to move the insertion point with keys, how to extent text selection with keys, functions of function keys, what are reserved keyboard shortcuts, how to create your own keyboard shortcuts, keyboard focus and navigation, type-ahead and key-repeat, etc. Gnome keys: Keyboard documentation for Gnome 2.2: still seeking developer guidelines for keyboard. Other Useful Resources Links for those who wish to learn more about web accessibility or open source accessibility. Join the Mozilla Accessibility Community Live Chat Both end users and developers are invited for discussion on the live IRC channel at irc.mozilla.org/#accessibility. Since this is a worldwide effort, th...
Adding a new event
What type of event do you want? Roughly, there are 3 types of event. First, you need to choose which type you need. A simple DOM event which can be implemented with WebIDL and WidgetEvent or something. This type of event is useful if the event isn't handled by C++ code. A DOM event which represents a native event like a user action such as keyboard or mouse input. This type of event allows C++ code to handle it easier. It's not a DOM event. However, C++ code may need to dispatch an event to DOM tree and handle it with C++ event handler. This is useful for widget notifying DOM tree of something or retrieving something from DOM tree. ...
...ndard specification. And it should be in mozilla::dom namespace. For example, KeyboardEvent which is defined in DOM Level 3 Events should be implemented as mozilla::dom::KeyboardEvent. And the header file should be exported as "mozilla/dom/FooEvent.h". Add the header file to EXPORTS.mozilla.dom in dom/events/moz.build. You probably need to implement a lot of methods to the event class, but this document doesn't explain all of them. Please refer existing DOM event implementation for example. However, there are some hints: Set mEventIsInternal in the constructor of the most descendant class because each constructor creates dummy internal event instance at calling constructors of its super class. Therefore, super classes always set it false. Don't override methods of its super classes as far a...
...amespace. 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, internal event message, event h...
Command line options
y available for an application build for and running atop the X11/X.org display and window system to be found on Linux and other Unix-based systems. --class=WM_CLASS Set the WM_CLASS resource class of the X11 windows created by the application. --display=DISPLAY Set the X display to use. --g-fatal-warnings Make all warnings fatal. --sync Make X calls synchronous. ...
...se. --g-fatal-warnings Make all warnings fatal. --sync Make X calls synchronous. ...
... ...
Debugging on Windows
If VC++ and your Mozilla application hang shortly after you launch the application under the debugger, see Problems Loading Debug Symbols. Ways to start the debugger First of all, it's necessary to install a Visual Studio extension to be able to follow child processes as they are created. Firefox, in general, and even in non-e10s mode, does not start the main process directly, it starts it via a Launcher Process. This means that Visual Studio will only attach to the first process it finds, and will not hit any break-point (and even notifies you that it cannot find their location). ...
...he tab of page you want to debug, which would show the pid. You can then select the process from dialog opened from "Attach to Process". For more information, see Attach to Running Processes with the Visual Studio Debugger. Debugging Release and Nightly Builds Refer to the steps to use the Mozilla symbol server and source server. Creating a Visual C++ project for Firefox Please refer to the documentation on firefox-source-docs. Changing/setting the executable to debug VC++ 6.0: To change or set the executable to debug, go to Project > Settings..., Debug tab and select General from the drop down list. "Executable for debug session:" should show the executable you are debugging. If it is empty or incorrect, use the arrow button and select Browse... to locate the executable. Command line par...
...iner.v,su>, length=<nsStringContainer.d1,u> nsACString=<nsCStringContainer.v,s>, length=<nsCStringContainer.d1,u> nsStringContainer=<v,su>, length=<d1,u> nsCStringContainer=<v,s>, length=<d1,u> There is a more extensive version of this file in progress in AutoExpForVC8. Avoiding stepping into certain functions You can avoid stepping into certain functions, such as nsCOMPtr methods, using an undocumented feature of VC. See the blog post How to Not Step Into Functions using the Visual C++ Debugger for details. Here are some wildcards you can use (tested with VC 8): nsCOMPtr.*\:\:.*=NoStepInto (nsG|g)etter_*AddRefs.*=NoStepInto NS_ConvertUTF.* ; Might be too broad: (ns|Promise)[^\:]*[sS]tring.* ...add common functions to this list should probably make a .reg file for easy importing Obtaining...
Old Thunderbird build
Hardware requirements At least 4 GB of RAM. 8 GB or more is recommended. While you can build Thunderbird on older hardware it can take quite a bit of time to compile on slower machines with less RAM. Good internet connection for the initial source download. Build prerequisites Depending on your Operating System you will need to carry out a different process to prepare your machine. ...
...uild instructions. To build on Windows, please read the prerequisites so you don't skip preparing the MAPI headers needed to compile Thunderbird. Windows Build Prerequisites GNU/Linux Build Prerequisites Mac OS X Build Prerequisites Get the source Note: On Windows, you won't be able to build the Thunderbird source code if it's under a directory with spaces in the path (e.g., don't use "Documents and Settings"). You can pick any other location, such as a new directory C:/thunderbird-src (where "C:/", with a forward slash, is intentional to clarify you are in the MozillaBuild command prompt per Windows build prerequisite). Note: Parts of the build process also have problems when the source code is in a directory where the path is long (nested many levels deep). On Linux, this can manifes...
...e build system changes. ...
Simple Instantbird build
This should be kept in sync with Simple Thunderbird build, you might want to take a look at that page too. Build prerequisites Hardware Requirements: While you can build Instantbird on older hardware it can take quite a bit of time to compile on slower machines, and having 8GB of RAM is recommended (though you can probably still get away with 4Gb). Good internet connection for the initial source download. ...
...n opt to add the progressExtension to your mercurial.ini (for Windows) or .hgrc (for *Nix / Mac) file. This will provide status feedback during the lengthy clone / download process. see: Configure Mercurial .hgrc file for Progress Extension. Get the source Note: On Windows, you won't be able to build the Instantbird source code if it's under a directory with spaces in the path (e.g., don't use "Documents and Settings"). You can pick any other location, such as a new directory C:\instantbird-src. Note: Parts of the build process also have problems when the source code is in a directory where the path is long (nested many levels deep). On Linux, this can manifest as problems setting up the virtualenv for running tests (failure to install pip or virtualenv because of OS access denied errors, where...
...e hg clone instruction). ...
Simple SeaMonkey build
Build prerequisites Hardware Requirements: The SeaMonkey build process is both I/O- and CPU-intensive, and can take a long time to build even on modern hardware. Minimum and recommended hardware requirements for Mozilla development are: Recommended: 8GB of RAM (having only 4GB RAM and 4GB swap may give memory errors during compile) 35 GB free disk space. ...
...ions --disable-optimize Normally a shared build suffices for debugging purposes but current nightly releases are actually static builds which require even more memory to link. The support for libxul builds is still experimental but it should work if you --disable-mailnews. On Windows, the above commands will create the comm-central directory in %USERPROFILE% which may be some subfolder of c:\Documents and Settings\ on systems upgraded from XP or below. The space in this directory name, or in your user name if it contains one, will cause the configure script to break. To (possibly) fix this, cd to a dir without spaces before doing the "hg clone" command above. Running SeaMonkey The SeaMonkey executable can be found in obj-sm-release/dist/bin/ (used to be obj-sm-release/mozilla/dist/bin/) o...
...nd in obj-sm-release/dist/SeaMonkey.app/Contents/MacOS/ on Mac. How to build again later In your comm-central directory, run these commands: # Get the latest source python client.py checkout Then just re-run the "(moz)make -f client.mk" command above. (moz)make will only recompile files that changed, but it's still a long haul. An incremental build can be faster. References General Build Documentation comm-central ...
Simple Sunbird build
Building Sunbird is no longer supported. You can give it a try, but its likely that the build system will present you an error. Instead it is suggested to build Thunderbird with Lightning. Please refer to the Simple Thunderbird build guide. You can build a bleeding-edge, development version of Sunbird using the commands below. For complete information, see the build documentation. Installing build tools If your system is not listed below, see the build prerequisites page. Ubuntu Linux: sudo apt-get build-dep sunbird sudo apt-get install mercurial libasound2-dev libcurl4-openssl-dev libnotify-dev libiw-dev autoconf2.13 cvs Fedora Linux: sudo yum groupinstall 'Development Tools' 'Development Libraries' 'GNOME Software Development' sudo yum install mercurial autoconf213 glibc...
... a shell window by running: c:\mozilla-build\start-msvcX.bat (where X is 8 for VS 2005, and 9 for VS 2008). Problems? See Windows build prerequisites. Building Sunbird Building Sunbird requires at least 2.5 GB of disk space, 500 MB of RAM, and lots of available swap space. On Windows, if you open the command prompt you are usually in your user profile folder which often contains spaces ( C:\Documents and Settings\...). This causes problems while building. To avoid this issue, change to a directory without spaces (i.e. C:\ ) before doing the following steps. You can use the "cd" command to do so. # Get the source hg clone http://hg.mozilla.org/comm-central/ cd comm-central python client.py checkout # Setup a basic .mozconfig file echo 'ac_add_options --enable-application=calendar' > .mozcon...
...t changed, but it's still a long haul. ...
Simple Thunderbird build
Hardware requirements At least 4 GB of RAM. 8 GB or more is recommended. While you can build Thunderbird on older hardware it can take quite a bit of time to compile on slower machines with less RAM. Good internet connection for the initial source download. ...
...You can pick any other location, such as a new directory C:/thunderbird-src (where "C:/", with a forward slash, is intentional to clarify you are in the MozillaBuild command prompt per Windows build prerequisite). Note: Parts of the build process also have problems when the source code is in a directory where the path is long (nested many levels deep). On Linux, this can manifes...
... when the build system changes. ...
Eclipse CDT
t you yourself made) select "Index > Freshen All Files" on that directory. To rebuild the entire index (for example when you pull from mozilla-central) select "Index > Rebuild" on the project root. Usage tips Below are some of the more useful user tips. (If you're thinking of adding tips, please first consider how widely useful they'll be before adding to this already lengthy page.) For further documentation see the official Eclipse user guide and Eclipse CDT user guide. Keyboard shortcuts Regarding key bindings (keyboard shortcuts), the bindings given below are the defaults. You can change the key bindings by opening the workspace preferences (Eclipse > Preferences, or Window > Preferences) and selecting "General > Keys". You can set the scheme to "Emacs" or "Microsoft Visual Studio" if that'...
...fic by setting the "When" field to "C/C++ Editor" instead of the more general "Editing Text". Opening files You can quickly open a file by name using Cmd-Shift-R/Ctrl-Shift-R. Although Eclipse doesn't do fuzzy matching when you type a file name, it does allow you to use wildcards. To quickly switch between a source file and its header file, use Ctrl-Tab. To quickly switch to a recently viewed document use Cmd-F6/Ctrl-F6. If you want to change this awkward key binding, the command you need to rebind is "Next Editor". To show a filterable list of open documents (similar to the way Emacs gives you a list of open buffers), use Cmd-E/Ctrl-E. If you click the yellow, double arrow button at the top of the Project Explorer tab on the left, it will keep the selected file in the Project Explorer tab i...
...s if you run this script by double clicking it in Finder. #subprocess.Popen(["osascript", "-e", 'tell application "Terminal"', "-e", "close front window", "-e", "end tell"]) TODO: add instructions for Linux and Windows. Is there a Mercurial plugin for Eclipse? There is MercurialEclipse, but probably most Mozilla developers will just prefer to use the command line. If you think we need our own documentation on MercurialEclipse, please consider adding a separate page for that tool since this page is already pretty long. How can I delete my Eclipse project and start over? If you followed the recommendation above to create one workspace containing only one project for each Mozilla tree, then this is easy. (If you didn't, and you have projects for more than one source tree entangled in a workspac...
Obsolete Build Caveats and Tips
Purpose of this page The Mozilla build process and code base have evolved considerably over the past few years. This has resulted in many caveats and tips being added to the MDN documentation for building older versions of the code base or dealing with older build tools. These tips, while helpful, are jarring and superfluous to the majority of new Mozilla builders who are mainly interested in building the latest version of Firefox. Therefore, instead of deleting all these nuggets of information, it's best to collect them all here and remove them from the majority happy path documentation. Each piece of information should mention the page and the section it originally came from. You can copy in the original text and bold out what has been removed. Obsolete caveats and tips From Simple_Fi...
...SDK include: Windows Vista parental controls File associations and application registration on Vista and above Ability to display the UAC shield icon in the UI Thunderbird Windows Search integration Text Services Framework support There are two ways to obtain it: Download the Windows Vista SDK from the Microsoft Download Center. You may choose not to install the Sample Code and Documentation to save space and download time. If you are using Windows XP, you must have Windows XP Service Pack 2 and .NET Framework 2.0 installed before installing the Vista SDK. Use Visual Studio 2008 Professional. Gecko 1.9.2 through 11: If you would like to use this SDK, add ac_add_options --with-windows-version=600 to your .mozconfig. Windows Server 2003 R2 Platform SDK Obsolete sinc...
... on Windows 2000. This also used to be necessary for building a default Gecko 1.9.2 through 8 with Visual C++ Express editions (see atlbase.h for more). You can download the SDK from the Microsoft Download Center. You need to install at least the "Windows Core SDK", "Web Workshop (IE) SDK", and the "Data Access Services (MDAC) SDK". For all SDKs, you may choose not to install Sample Code and Documentation to save space and download time. Gecko 1.9.2 through 11: If you're building with this SDK, you will need to add ac_add_options --with-windows-version=502 to your .mozconfig. For mozilla-1.9.1 and mozilla-1.9.0, you need to add ac_add_options --disable-vista-sdk-requirements to your .mozconfig instead. Unsupported SDKs The Windows SDK for Windows Server 2008 is not supported, and has bee...
Developer guide
This guide provides information that will not only help you get started as a Mozilla contributor, but that you'll find useful to refer to even if you are already an experienced contributor. Documentation topics Getting Started A step-by-step beginner's guide to getting involved with Mozilla. For new Mozilla developers A directory of articles which are particularly helpful for new Mozilla developers. ...
...e guide. Build Instructions How to build Firefox, Thunderbird, SeaMonkey, or other Mozilla applications. Development process overview An overview of the entire Mozilla development process. Managing multiple profiles When working with prerelease versions of Firefox, it's often helpful to have multiple Firefox profiles, such as one for each channel, or for different kinds of testing. Getting documentation updated How to ensure that documentation is kept up to date as you develop. Mozilla modules and module ownership This article provides information about Mozilla's modules, what the role of a module owner is, and how module owners are selected. Code snippets Useful code samples for a wide variety of things you might need to figure out how to do. Mozilla development strategies Tips for ...
...irefox Information about creating customized versions of Firefox. Task-Graph Generation What controls the jobs that run on a push to version control? How can you change that? Obsolete Build Caveats and Tips A place to put build tips which are no longer relevant to building the latest version of the code from main but are relevant when building old codebases. Firefox Source Docs Web-hosted documentation built from the mozilla-central source code. Tools Bugzilla The Bugzilla database used to track issues for Mozilla projects. DXR Next generation of searching Mozilla's source code. In active development. SearchFox Another option for Mozilla code searching. Indexes JS as well as C++, includes blame capabilities. In active development. Mozilla build VM A VirtualBox compatible virt...
Tracking Protection
lback will not execute. ...
... Note: Depending on a third party in this way is not a good practice anyway, because then your site can be broken if the third party is slow or unavailable, or if the tracker has been blocked by an add-...
... Note: Depending on a third party in this way is not a good practice anyway, because then your site can be broken if the third party is slow or unavailable, or if the tracker has been blocked by an add-on. ...
mozbrowseropentab
e 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. ...
... 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. ...
...ancellable 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. ...
mozbrowsertitlechange
s Property Type Description 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. detail Read only String The title of the document. ...
...ion 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. detail Read only String The title of the document. ...
... bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. detail Read only String The title of the document. ...
Roll your own browser: An embedding how-to
You should instead build XULRunner and use it for all new embedding. You should not need to, and should not, use embedding/config. What bits do I need? One of the requirements of building a SDK is the ability to identify and package up required files. Like that isn't totally obvious, nonetheless it has to be done. Here is that effort. I have created a directory under embedding called config. Contained within this directory are a couple of makefiles: basebrowser-unix basebrowser-win The XPInstall packager follows the same format. However in our case, we only have one named XPI package. After the build is done, you can change directory into mozilla/embedding/config, and do a make. ...
... platform. Camino uses Cocoazilla, a variant of Fizzilla that consists of a UNIX back end wed to a Cocoa front end. ...
...that consists of a UNIX back end wed to a Cocoa front end. Java Examples Java Webclient: Provides a browser-neutral Java API that enables generic web browsing capability. ...
Integrated Authentication
This entails support for the the Simple and Protected GSS-API Negotiation Mechanism (SPNEGO) internet standard (RFC 2478) to negotiate either Kerberos, NTLM, or other authentication protocols supported by the operating system. SPNEGO is commonly referred to as the "negotiate" authentication protocol. Mozilla does not have its own internal implementation of SPNEGO. Instead, it leverages system libraries that provide SPNEGO; SSPI on Microsoft Windows, and GSS-API on Linux, Mac OSX, and other UNIX-like systems. The Mozilla implementation of SPNEGO can be found under extensions/auth/. It used to live in extensions/negotiateauth. ...
...own internal implementation of SPNEGO. Instead, it leverages system libraries that provide SPNEGO; SSPI on Microsoft Windows, and GSS-API on Linux, Mac OSX, and other UNIX-like systems. The Mozilla implementation of SPNEGO can be found under extensions/auth/. It used to live in extensions/negotiateauth. Mozilla also supports raw NTLM authentication using an internal implementation (based on the documentation provided by Eric Glass) that supports NTLMv1/LMv1 and NTLM2 Session Key modes. As of Mozilla 1.7, there is no support for NTLMv2/LMv2. This is mainly due to the fact that NTLMSSP does not provide a means to negotiate use of NTLMv2/LMv2. <i>This document is incomplete ...</i> Flow Diagram The diagram below shows how various components interact. Configuration By default, Mozilla rejects ...
... server. network.automatic-ntlm-auth.trusted-uris lists the trusted sites to use NTLM authentification. If you wish to use non-fully-qualified entries of the form mydomain.com in the above preferences for NTLM and SPNEGO authentication, you will also need to set the preferences network.automatic-ntlm-auth.allow-non-fqdn and network.negotiate-auth.allow-non-fqdn (respectively) to true. Original Document Information Author(s): Darin Fisher Last Updated Date: December 27, 2005 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
API-provided widgets
Properties Property Description id the ID of the widget (required). type a string indicating the type of widget. Possible types are button for simple button widgets (the default) view for buttons that open a panel or subview, depending on where they are placed. custom for fine-grained control over the creation of the widget. viewId Only useful for views (and required there): the id of the that should be shown when clicking the widget. ...
... showInPrivateBrowsing whether to show the widget in private browsing mode (optional, default: true) Event handlers You can also define several event handlers which will be called at various stages in a widget's lifetime: Event handler name Description onBuild(aDoc) Only useful for custom widgets (and required there); a function that will be invoked with the document in which to build a widget. Should return the DOM node that has been constructed. NB: the DOM node you construct should have the same ID as the id property described above, so that CustomizableUI can find the node again later. onBeforeCreated(aDoc) Attached to all non-custom widgets; a function that will be invoked before the widget gets a DOM node constructed, passing the document in...
...construct their views on the fly (e.g. from bootstrapped add-ons). onCreated(aNode) Attached to all widgets; a function that will be invoked whenever the widget has a DOM node constructed, passing the constructed node as an argument. onDestroyed(aDoc) Attached to all non-custom widgets; a function that will be invoked after the widget has a DOM node destroyed, passing the document from which it was removed. This is useful especially for 'view' type widgets that need to cleanup after views that were constructed on the fly. onCommand(aEvt) Only useful for button widgets; a function that will be invoked when the user activates the button. onClick(aEvt) Attached to all widgets; a function that will be invoked when the user clicks the widget. on...
Promise.jsm
omponents.utils.import("resource://gre/modules/commonjs/sdk/core/promise.js"); // Gecko 21 to 24 This implementation also includes helper functions that are specific to the Add-on SDK. While you may still import this module from the above paths, the recommended way for loading it is through the Add-on SDK loader. Introduction For an introduction to promises, you may start from the Add-on SDK documentation, keeping in mind that only the core subset is implemented in this module. A promise is an object representing a value that may not be available yet. Internally, a promise can be in one of three states: Pending, when the final value is not available yet. This is the only state that may transition to one of the other two states. Fulfilled, when and if the final value becomes available. A ...
... registers callback functions that are called as soon as the promise is either fulfilled or rejected. The method returns a new promise that, in turn, is fulfilled or rejected depending on the state of the original promise and on the behavior of the callbacks. For example, unhandled exceptions in the callbacks cause the new promise to be rejected, even if the original promise is fulfilled. See the documentation of the then method for details. Promises may also be created using the new Promise() constructor. Method overview Deferred defer(); Obsolete since Gecko 30 Promise resolve([optional] aValue); Promise reject([optional] aReason); Methods defer() Creates a new pending promise and provides methods to resolve or reject it. Deferred defer(); Obsolete since G...
...optional] aValue); Promise reject([optional] aReason); Methods defer() Creates a new pending promise and provides methods to resolve or reject it. Deferred defer(); Obsolete since Gecko 30 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. See the Deferred documentation for details. resolve() Creates a new promise fulfilled with the specified value, or propagates the state of an existing promise. Promise resolve( aValue ); Parameters aValue Optional If this value is not a promise, including undefined, it becomes the fulfillment value of the returned promise. If this value is a promise, then the returned promise will be resolved with the value, i.
WebRequest.jsm
r to add a listener to a particular event. It takes one mandatory argument and two optional arguments, as detailed below. Name Type Description callback Function The callback argument is a function to be called when the event is triggered. It's passed an object whose structure will vary depending on the event you're listening to: see the event-specific documentation for details. filter Object The optional filter argument is used to restrict the requests for which the listener callback will be invoked. See Filtering. opt_extraInfoSpec Array of String The optional opt_extraInfoSpec argument lets you pass extra instructions for the handling of events. The instructions you can pass here vary depending on the event...
...ect The optional filter argument is used to restrict the requests for which the listener callback will be invoked. See Filtering. opt_extraInfoSpec Array of String The optional opt_extraInfoSpec argument lets you pass extra instructions for the handling of events. The instructions you can pass here vary depending on the event you're listening to: see the event-specific documentation for details. In particular, "blocking" may be passed to several event types, and will make the event dispatch synchronous, so the browser will wait for the event listener to return before continuing with the request. This then enables the event listener to modify or cancel the request. See Modifying & canceling requests. Some examples of using addListener(). To remove a list...
... Array of HTTP headers. Modify response headers onHeadersReceived responseHeaders Array of HTTP headers. See some examples of canceling, redirecting, and modifying request headers. Events The events exported by WebRequest.jsm are triggered at the various stages of making a request. This section describes the stage corresponding to each event. It also documents two data structures that vary from one event to another: the opt_extraInfoSpec argument to addListener() the properties of the argument passed to the listener. onBeforeRequest This event is triggered when a request is about to be made, and before headers are available. This is a good place to listen if you want to cancel the request. opt_extraInfoSpec values Name Description...
Localization content best practices
Note: If you're a localizer and you want to contribute to the localization of Mozilla products, you might want to read our Localization quick start guide for information on localizing Mozilla code. Note on localizers Mozilla localizers are volunteers with very diverse technical skills: some of them rely exclusively on translation tools, others prefer to work directly with text editors and don't have problems working with VCS systems. It's important to consider this when adding strings, and especially localization comments for strings that contain references, or obscure technical details. ...
... the decision about capitalization. If you want to display WARNING, add a string with that capitalization, and explain it in the localization note. Design for +50% Bear in mind that English strings will likely be a lot shorter than their international equivalents, so you need to leave some space in your UI to allow for this. Some examples: OK in English becomes Ceart ma-tha in Gaelic. Save document? in English becomes A bheil thu airson an sgriobhainn a shabhaladh in Gaelic. Another good example is Yes/No. There are two types of languages, those that have Yes/No as a single word, and those that don't and work on mirroring the verb. For example, a Do you want to open the page? > Yes/No dialog works in English, but in Gaelic/Irish/Welsh and several other languages the equivalent answer is W...
...hat don't involve string changes. Note that even removing strings is considered a breakage. In the case of Firefox and Thunderbird, string frozen repositories are: mozilla-aurora, mozilla-beta, mozilla-release. Bugzilla and l10n Do I need l10n feedback? Feedback from l10n-drivers is not necessary for each landing involving strings, as long as you're following the basic rules described in this document. If you have doubts about the localizability of some text or structure (not about the text itself, that would need copywriters), it's definitely good to ask feedback. Keywords: l12y, late-l10n Two keywords are generally used on Bugzilla: l12y: it's used to track "localizability" bugs. A bug marked with l12y describes an issue that prevents localizers to create a good quality localization. So...
MathML Torture Test
addEventListener("change", updateMathFont, false) } window.addEventListener("load", load, false); The following test contains sample TeX formulas f...
... addEventListener("change", updateMathFont, false) } window.addEventListener("load", load, false); The following test contains sample TeX formulas from Knuth's TeX book and equivalent MathML representations. It compares the re...
...family: TeX Gyre Pagella Math; } .TeXGyreSchola math { font-family: TeX Gyre Schola Math; } .TeXGyreTermes math { font-family: TeX Gyre Termes Math; } .XITS math { font-family: XITS Math; } JavaScript Content function updateMathFont() { var mathFont = document.getElementById("MathFont").value; if (mathFont == "Default") { document.body.removeAttribute("class"); } else { document.body.setAttribute("class", mathFont); } } function load() { document.getElementById("MathFont"). addEventListener("change", updateMathFont, false) } window.addEventListener("load", load, false); The following test contains sample TeX formulas from Knuth's TeX book and equivalent MathML representations. It compares the rendering by the XeTeX engine using the default Latin Mod...
Updates
Complete support for STIX fonts 1.0. ...
...h lets you use MathML inside non-XHTML documents. Complete support for STIX fonts 1.0. Better rendering of mathematical symbols, especially stretchy operators. October 21, 2010 MathML 3.0 is now a W3C recommendation! June 11, 2010 STIX Fonts Version 1.0 are now compatible with trunk. May 28, 2010 STIX Fonts Version 1.0 Released. April 2010 New Web pages for the Mozilla MathML Project! Documentation is now available on MDC and wiki.mozilla.org. Feel free to complete and improve it! May 8, 2007 Mozilla CEO speaks out on the future of Firefox: the complete 8,000 word interview. Interview to the APC Magazine where Mitchell Baker mentions Roger Sidje's work on MathML. June 5, 2002 Mozilla 1.0 Released "By virtue of embedding Gecko, Mozilla 1.0 and products based on Mozilla code suppor...
...r mentions Roger Sidje's work on MathML. June 5, 2002 Mozilla 1.0 Released "By virtue of embedding Gecko, Mozilla 1.0 and products based on Mozilla code support more web standards, more deeply, more consistently across more platforms than any others. Mozilla 1.0 features full support for HTML 4.0, XML 1.0, Resource Description Framework (RDF), Cascading Style Sheets level 1 (CSS1), and the W3C Document Object Model level 1 (DOM1) [...] as well as support for display of mathematical equations using MathML." December 7, 2001 Status Report October 2000 The first International MathML conference April 14, 2000 Status Report February 12, 2000 MathML-enabled M13 Builds For Win32 September 21, 1999 MathML has landed. September 18, 1999 Status Report - MozillaZine annoucement September 3, ...
Gecko Profiler FAQ
mstange and ehsan tried to respond to some of the questions in advance in writing, and you can find the answers below. Is it possible to locate hot spots occurring within a single function? The Gecko Profiler currently doesn't have the ability to show you information about line numbers, neither for JS code nor for native code. For JS code, the profiler platform doesn't capture any information about lines. It only knows what function was executed and what line this function starts at. For native code, the profiler captures the necessary information but doesn't have a way to display it. ...
...n the call stacks whose cost increased the most in the "after" profile will be at the top, and those are the ones you usually want to look at if you caused a regression. In this view, the timestamps of individual samples / stacks will not be meaningful. profiler.firefox.com does not have a comparison view at the moment. I can help you add one, though. There is documentation for the Gecko profile format. Is it worth slowing down CPU to increase the profiler resolution? It depends on what you are trying to profile to some extent. Usually you should be really careful when changing the characteristics of the environment that you are trying to measure to avoid measuring the wrong thing. If the issue you are trying to avoid is no...
... all their stacks, and then resume all threads, especially on high-core systems. (ITIMER_REAL (due to posix) requires the signal occur on the calling thread, not a random thread. ITIMER_PROF interrupts the then-running thread, whichever one it is. Is there a way to isolate or filter a profile (at least of mainthread and maybe one or two other ones that make sense) to a specific tab/document/eventqueue? Currently not. Some functions (reflow, painting, JS excecution) insert the URL of the associated document into the call stack frame, so you can get a rough idea, but we don't have instrumentation at the tab/document/eventqueue level. For isolated profiles I recommend profiling a separate browser instance with only the tab that you're interested in. ...
Leak Gauge
It has two parts: (a) instrumentation in Gecko that produces a log file, and (b) a script to post-process the log file. Getting a log file To get a log file, run the browser with the following environment variables set. NSPR_LOG_MODULES=DOMLeak:5,DocumentLeak:5,nsDocShellLeak:5,NodeInfoManagerLeak:5 NSPR_LOG_FILE=nspr.log # or any other filename of your choice This will overwrite any existing file called nspr.log. The browser will run with negligible slowdown. ...
...igible slowdown. You must exit the browser before post-processing the log file or the results will be unreliable. Post-processing a log file Post-process the log file with tools/leak-gauge/leak-gauge.pl or tools/leak-gauge/leak-gauge.html. If there are no leaks, output will look like the following. Results of processing log leak.log : Summary: Leaked 0 out of 11 DOM Windows Leaked 0 out of 44 documents Leaked 0 out of 3 docshells Leaked content nodes in 0 out of 0 documents If there are leaks, output will look like the following. Results of processing log leak2.log : Leaked outer window 2c6e410 at address 2c6e410. Leaked outer window 2c6ead0 at address 2c6ead0. Leaked inner window 2c6ec80 (outer 2c6ead0) at address 2c6ec80. Summary: Leaked 13 out of 15 DOM Windows Leaked 35 out of 46 docume...
...ments If there are leaks, output will look like the following. Results of processing log leak2.log : Leaked outer window 2c6e410 at address 2c6e410. Leaked outer window 2c6ead0 at address 2c6ead0. Leaked inner window 2c6ec80 (outer 2c6ead0) at address 2c6ec80. Summary: Leaked 13 out of 15 DOM Windows Leaked 35 out of 46 documents Leaked 4 out of 4 docshells Leaked content nodes in 42 out of 53 documents If you see such a results, please file a bug. ...
Profiling with the Firefox Profiler
ng. There are also product docs available at profiler.firefox.com/docs/. In addition to profiler.firefox.com, the Firefox DevTools have a simplified interface targeted towards web developers, but does not include as much information as the Firefox Profiler web app. It is available from the menu at Tools > Web Developer > Performance. Understanding Profiles The Firefox Profiler has more current documentation available at profiler.firefox.com/docs/. However the following could have some potentially useful information for Gecko-specific problems. You can check out some frequently asked questions about the Firefox Profilers. Reporting a Performance Problem has a step-by-step guide for obtaining a profile when requested by Firefox developers. Interface 1. Timeline The timeline has several ro...
..."Filter stacks" box. You can then select corresponding Call Tree entries and watch the Timeline for entries in the content process main thread that get darker as you select Call Tree entries. Tip: If things are blank elsewhere in the UI, you may have text entered into the "Filter stacks" box. Custom Annotations In bug 1334218 an annotation was added to PresShell::Paint to show the URL of the document being painted. These annotations are not too complex to add so if you would like something added, 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 Under...
...tyles or recomputing layout. These sorts of flushes should be avoided if possible, as they can be quite expensive. Keep your eyes out for flushes like this that are blocking the main thread for a long time. If you notice these things happening in a loop, that's a bug to be fixed, since we're likely "layout thrashing". Some more tips and answers to common questions are available in a mid-2017 FAQ document. It's a good idea to search bugzilla before filing a bug about a performance problem in Firefox but sometimes it's hard to find issues that have already been reported. Therefore, it's usually a good idea to file a bug. Profiling local Windows builds If you built Firefox for Windows locally and you would like to use the local symbols with the profiler, you will need to run an additional tool; s...
Performance
A development environment is not required. Benchmarking Tips on generating valid performance metrics. Performance best practices in extensions A performance "best practices" guide for extension developers. Measuring Add-on Startup Performance A guide for add-on developers on how to set up a performance testing environment. ...
...ols for Mac OS X that report similar problems to those reported by LSAN and Valgrind. The "leaks" tool is not recommended for use with SpiderMonkey or Firefox, because it gets confused by tagged pointers and thinks objects have leaked when they have not (see bug 390944). Leak Gauge Leak Gauge is a tool that can be used to detect certain kinds of leaks in Gecko, including those involving documents, window objects, and docshells. LogAlloc LogAlloc is a tool that dumps a log of memory allocations in Gecko. That log can then be replayed against Firefox's default memory allocator independently or through another replace-malloc library, allowing the testing of other allocators under the exact same workload. Memory Profiler The memory profiler samples allocation events and p...
...of memory allocations in Gecko. That log can then be replayed against Firefox's default memory allocator independently or through another replace-malloc library, allowing the testing of other allocators under the exact same workload. Memory Profiler The memory profiler samples allocation events and provides different views to analyze the allocation characteristic. See also the documentation on Leak-hunting strategies and tips. Profiling and performance tools Profiling with the Developer Tools Profiler The profiler built into the developer tools has a high-level waterfall, detailed call tree, allocations and GC profiling, and flame graphs. It is available on all platforms and release channels, and also supports remote profiling b2g and Fennec. ...
Firefox Sync
ent. All data is encrypted and decrypted on each device; no Sync data is ever transmitted to a server without being encrypted. Mozilla does not hold any keys to your Sync data. Your data can only be decrypted by someone who is able to log in to your Firefox Account (ie, that knows your Firefox Accounts password and has access to your email for the verification required during the initial login). Documentation This document serves as an index for all technical documentation related to Sync. It is not designed for use by end-users, but instead for people who wish to understand the details of how Sync is implemented or wish to interact with it. General The always prolific Richard Newman has written a couple of notes about bookmark syncing (first, second) and has a blog where he talks about the va...
...cal documentation related to Sync. It is not designed for use by end-users, but instead for people who wish to understand the details of how Sync is implemented or wish to interact with it. General The always prolific Richard Newman has written a couple of notes about bookmark syncing (first, second) and has a blog where he talks about the various challenges syncing this kind of data. Servers Documentation for the various servers, including information on how to host your own. Android Searchfox has links to the main sync code and the storage layer. There are also some notes in a google document (that we really must move to its own Wiki page) There's also information available to help debug and diagnose Android sync issues. iOS There is some in-tree documentation and there are some extensi...
...notes in a google document (that we really must move to its own Wiki page) There's also information available to help debug and diagnose Android sync issues. iOS There is some in-tree documentation and there are some extensive comments here and here. Desktop Notes on how to file a good bug for Desktop Sync. There are some notes on how to run our TPS testing infrastructure. We have a Google document on how bookmark repair works. ...
L20n
A JavaScript localization framework to unleash your natural language's power with simple code. 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. L20n lets localizers reach higher levels of free linguistic expression by sharpening the divide between localization and application logic. ...
... 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 ...
...ir web apps using L20n. Internationalization for your web app First read for developers looking to use the L20n infrastructure. L20n's HTML bindings Tutorial on implementing L20n in your HTML code. L20n JavaScript API An API for l20n.js. L20n syntax cheatsheet for developers A simple cheatsheet to help developers as they add L20n to their localization infrastructure. For Localizers Documentation for Localizers creating localized content for a project that uses L20n. Learn the L20n syntax How to naturally localize applications using L20n. Complete with use cases and examples of L20n in action. Localization use-cases How to naturally localize applications using L20n. Complete with use cases and examples of L20n in action. L20n and Translation Memory eXchange (TMX) How L20n imp...
FIPS Mode - an explanation
NSS has a "FIPS Mode" that can be enabled when NSS is compiled in a specific way. (Note: Mozilla does not distribute a "FIPS Mode"-ready NSS with Firefox.) This page attempts to provide an informal explanation of what it is, who would use it, and why. What's a FIPS? The United States government defines many (several hundred) "Federal Information Processing Standard" (FIPS) documents. (FIPS sounds plural, but is singular; one FIPS document is a FIPS, not a FIP.) FIPS documents define rules, regulations, and standards for many aspects of handling of information by computers and by people. They apply to all US government employees and personnel, including soldiers in the armed forces. Generally speaking, any use of a computer by US government personnel must conform to all the relevant ...
..., so their applicability is somewhat wider than just the US government's personnel. What is "FIPS Mode"? One of the FIPS regulations, FIPS 140, governs the use of encryption and cryptographic services. It requires that ALL cryptography done by US government personnel MUST be done in "devices" that have been independently tested, and certified by NIST, to meet the extensive requirements of that document. These devices may be hardware or software, but either way, they must function and behave as prescribed. So, in order for Mozilla Firefox and Thunderbird to be usable by people who are subject to the FIPS regulations, Mozilla's cryptographic software must be able to operate in a mode that is fully compliant with FIPS 140. To that end, Mozilla products can function in a "FIPS Mode", which is re...
... not do ANY cryptographic operations that involve the use of cryptographic keys, nor allow ANY of the keys or certificates it holds to be seen or used, except when a user has successfully authenticated to it. If users authenticate to it with a password, it must ensure that their passwords are strong passwords. It must implement the US government standard algorithms (also specified in other FIPS documents) such as AES, triple-DES, SHA-1 and SHA-256, that are needed to do whatever job the application wants it to perform. It must generate or derive cryptographic keys and store them internally. Except for "public keys", it must not allow any keys to leave it (to get outside of it) unless they are encrypted ("wrapped") in a special way. This makes it difficult to move keys from one device to anoth...
Getting Started With NSS
are happy to assist you in identifying areas that match your interest or skills. You can find us on Mozilla IRC in channel #nss or you could ask your questions on the mozilla.dev.tech.crypto newsgroup. The NSS library and its supporting command line tools are written in the C programming language. Its build system and the automated tests are based on makefiles and bash scripts. ...
...n channel #nss or you could ask your questions on the mozilla.dev.tech.crypto newsgroup. The NSS library and its supporting command line tools are written in the C programming language. Its build system and the automated tests are based on makefiles and bash scripts. Over time, many documents have been produced that describe various aspects of NSS. You can start with: the current primary NSS documentation page from which we link to other documentation. a General Overview of the applications that use NSS and the features it provides. a high level Introduction to the Internals of NSS. learn about getting the NSS sources, building, and testing. Old documentation that is on the archived mozilla.org website. (Unfortunately the NSS project doesn't have a technical writer at this time, so our ...
...You could contribute by organizing it in a better way.) NSS Sample Code A good place to start learning how to write NSS applications are the command line tools that are maintained by the NSS developers. ...
JSS FAQ
Mozilla › Projects › NSS › JSS › JSS FAQ
If I don't call setCipherPolicy, is the DOMESTIC policy used by default? My SSL connection is hanging on Windows? How can I tell which SSL/TLS ciphers JSS supports? How can I debug my SSL connection? Can you explain JSS SSL certificate approval callbacks? ...
...go to JDK 1.4 and later, so use that if you can. If you are using JDK 1.3.x, you will need to use at least version 1.3.1--see bug 113808. JSS only supports the native threading model (no green threads). For JSS 3.2 and higher, if you use JDK 1.4 or higher you will not need to install the JCE, but if you using an earlier version of the JDK then you will also have to install JCE 1.2.1. See also the document Using JSS. Does JSS have 64 bit support? Yes, JSS 3.2 and higher supports 64 bit. You will need JDK 1.4 or higher and all the 64 bit versions of NSPR, and NSS. As well you must use the java flag -d64 to specify the 64-bit data model. Is JSS FIPS Compliant? NSS is a FIPS-certified software library. JSS is considered a FIPS-compliant software library since it only uses NSS for an...
...JSS 3.2 and higher supports 64 bit. You will need JDK 1.4 or higher and all the 64 bit versions of NSPR, and NSS. As well you must use the java flag -d64 to specify the 64-bit data model. Is JSS FIPS Compliant? NSS is a FIPS-certified software library. JSS is considered a FIPS-compliant software library since it only uses NSS for any and all crypto routines. Is there any sample code and documentation? The Using JSS document describes how to set up your environment to run JSS. The only other documentation is the Javadoc. JSS example code is essentially developer test code; with that understanding, the best directory to look for sample code is in the org/mozilla/jss/tests directory: http://lxr.mozilla.org/mozilla/source/security/jss/org/mozilla/jss/tests org/mozilla/jss...
NSS 3.12.9 release notes
oup: mozilla.dev.tech.crypto</center> Introduction Network Security Services (NSS) 3.12.9 is a patch release for NSS 3.12. The bug fixes in NSS 3.12.9 are described in the "Bugs Fixed" section below. NSS 3.12.9 is tri-licensed under the MPL 1.1/GPL 2.0/LGPL 2.1. Distribution Information The CVS tag for the NSS 3.12.9 release is NSS_3.12.9_RTM. NSS 3.12.9 requires NSPR 4.8.7. See the Documentation section for the build instructions. NSS 3.12.9 source distribution is also available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3.12.9_RTM/src/. You also need to download the NSPR 4.8.7 binary distributions to get the NSPR 4.8.7 header files and shared libraries, which NSS 3.12.9 requires. NSPR 4.8.
...New and revised documents available since the release of NSS 3.11 include the following:</for> Build Instructions for NSS 3.11.4 and above NSS Shared DB Compatibility NSS 3.12.9 sh...
... not use the SEC_ERROR_BAD_INFO_ACCESS_LOCATION error code for bad CRL distribution point URLs Bug 619268: Memory leaks in CERT_ChangeCertTrust and CERT_SaveSMimeProfile Bug 585518: AddTrust Qualified CA Root serial wrong in certdata.txt trust entry Bug 337433: Need CERT_FindCertByNicknameOrEmailAddrByUsage Bug 592939: Expired CAs in certdata.txt Documentation <for a="" class="new " documentation="" href="/en/index.html#Documentation" list="" nss="" of="" pages="" primary="" rel="internal" see="" the="" title="en/index.html#Documentation">NSS Documentation. New and revised documents available since the release of NSS 3.11 include the following:</for> Build Instructions for NSS 3.11.4 and above NSS Shared DB Compatibility NSS 3.12.9 shared libraries are backward compatible...
NSS environment variables
Note: NSS Environment Variables are subject to be changed and/or removed from NSS. Run-Time Environment Variables These environment variables affect the RUN TIME behavior of NSS shared libraries. There is a separate set of environment variables that affect how NSS is built, documented below. Variable Type Description Introduced in version NSRANDCOUNT Integer (byte count) Sets the maximum number of bytes to read from the file named in the environment variable NSRANDFILE (see below). Makes NSRANDFILE usable with /dev/urandom. 3.12.3 NSRANDFILE String (file name) Uses this file to seed the Pseudo Random Number Generator. Before 3.0 NSS_ALLOW_WEAK_SIGNATURE_ALG Boolean (any non-empty value to enable) Enables t...
..._PKIX_VERIFY Boolean (any non-empty value to enable) Use libPKIX, rather than the old cert library, to verify certificates. 3.12 NSS_FIPS String ("fips","true","on","1") Will start NSS in FIPS mode. 3.12.5 NSS_HASH_ALG_SUPPORT String Specifies agorithms allowed to be used in certain applications, such as in signatures on certificates and CRLs. See documentation at this link. 3.12.3 NSS_OUTPUT_FILE String (filename) Output file path name for the PKCS #11 Module Logger. Default is stdout. 3.7 NSS_SDB_USE_CACHE String ("no","yes","auto") Controls whether NSS uses a local cache of SQL database contents. Default is "auto". See the source for more information. 3.12 NSS_SSL_CBC_RANDOM_IV String ("...
... or SSLTRACE have to be set to use this functionality. 3.12 SSLFORCELOCKS Boolean (1 to enable) Forces NSS to use locks for protection. Overrides the effect of SSL_NO_LOCKS (see ssl.h). 3.11 SSLKEYLOGFILE String (file name) Key log file. If set, NSS logs RSA pre-master secrets to this file. This allows packet sniffers to decrypt TLS connections. See documentation. 3.12.6 SSLTRACE Integer Tracing level Note: The code must be built with TRACE defined to use this functionality. Before 3.0 Build-Time Environment Variables These environment variables affect the build (compilation) of NSS. Note: This section is a work in progress and is not yet complete. Variable Type Description Introduced in version ...
NSS reference
Notes We are migrating the SSL Reference into the format described in the MDN Style Guide. If you are inclined to help with this migration, your help would be very much appreciated. The proposed chapters below are based on the chapters of the SSL Reference and the categories of functions in NSS Public Functions. Should a particular page require the use of an underscore, please see the documentation for the Title Override Extension. Building and installing NSS Overview of an NSS application Based on "Overview of an SSL Application" in the SSL Reference. Getting started with NSS Based on "Getting Started With SSL" in the SSL Reference. Data types Based on "Selected SSL Types and Structures" in the SSL Reference. NSS initialization and shutdown NSS_Init NSS_InitReadWrite...
... PK11_SetPasswordFunc SSL Functions Based on "SSL Functions" in the SSL Reference and "SSL Functions" and "Deprecated SSL Functions" in NSS Public Functions. SSL_ConfigServerSessionIDCache SSL_ClearSessionCache S/MIME Based on the S/MIME Reference (which only has one written chapter) and "S/MIME Functions" in NSS Public Functions. PKCS #7 functions Based on "Archived PKCS #7 Functions documentation." PKCS #5 functions Password-based encryption SEC_PKCS5GetIV SEC_PKCS5CreateAlgorithmID SEC_PKCS5GetCryptoAlgorithm SEC_PKCS5GetKeyLength SEC_PKCS5GetPBEAlgorithm SEC_PKCS5IsAlgorithmPBEAlg PKCS #12 functions Based on "Archived PKCS #12 Functions documentation." Used to exchange data such as private keys and certificates between two parties. SEC_PKCS12CreateExportContext SEC...
... Based on NSS Tools Man Pages : work in progress ...
NSS_3.12.3_release_notes.html
NSS 3.12.3 Release Notes 2009-04-01 Newsgroup: mozilla.dev.tech.crypto Contents Introduction Distribution Information New in NSS 3.12.3 Bugs Fixed Documentation Compatibility Feedback Introduction Network Security Services (NSS) 3.12.3 is a patch release for NSS 3.12. The bug fixes in NSS 3.12.3 are described in the "Bugs Fixed" section below. NSS 3.12.3 is tri-licensed under the MPL 1.1/GPL 2.0/LGPL 2.1. Distribution Information The CVS tag for the NSS 3.12.3 release is NSS_3_12_3_RTM. NSS 3.12.3 requires NSPR 4.7.4. See the Documentation section for the build instructions. NSS 3.12.3 source and binary distributions are also available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NS...
...OW_WEAK_SIGNATURE_ALG Boolean (any non-empty value to enable) Enables the use of MD2 and MD4 hash algorithms inside signatures. This was allowed by default before NSS 3.12.3. NSS_HASH_ALG_SUPPORT String Specifies algorithms allowed to be used in certain applications, such as in signatures on certificates and CRLs. See documentation at this link. NSS_STRICT_NOFORK String ("1", "DISABLED", or any other non-empty value) It is an error to try to use a PKCS#11 crypto module in a process before it has been initialized in that process, even if the module was initialized in the parent process. Beginning in NSS 3.12.3, Softoken will detect this ...
...ommand line flags used to build intel-aes.s with Solaris gas for x86_64 Bug 485370: crash Bug 485713: Files added by Red Hat recently have missing texts in license headers. Bug 485729: Remove lib/freebl/mapfile.Solaris Bug 485837: vc90.pdb files are output in source directory instead of OBJDIR Bug 486060: sec_asn1d_parse_leaf uses argument uninitialized by caller pbe_PK11AlgidToParam Documentation For a list of the primary NSS documentation pages on mozilla.org, see NSS Documentation. New and revised documents available since the release of NSS 3.11 include the following: Build Instructions for NSS 3.11.4 and above NSS Shared DB Compatibility NSS 3.12.3 shared libraries are backward compatible with all older NSS 3.x shared libraries. A program linked with older NSS 3.x shared ...
Tutorial: Embedding Rhino
ith good results. With more effort on the part of the embedder, 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. ...
...of the embedder, 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. ...
...ps 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. ...
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. ...
... with a file name "js-gdb.py". If js/src/js does not provide the "iongraph" command, try js/src/shell/js. GDB may complain that ~/.gdbinit requires modification to authorize user scripts, and if so will print out directions. Break on valgrind errors Sometimes, a bug can be reproduced under valgrind but hardly under gdb. One way to investigate is to let valgrind start gdb for you, the other way documented here is to let valgrind act as a gdb server which can be manipulated from the gdb remote. $ valgrind --smc-check=all-non-file --vex-iropt-register-updates=allregs-at-mem-access --vgdb-error=0 ./js ... This command will tell you how to start gdb as a remote. Be aware that functions which are usually dumping some output will do it in the shell where valgrind is started and not in the shell wher...
...r TEST-START. For example in '[rr 28496 607198]REFTEST TEST-START | file:///home/bgirard/mozilla-central/tree/image/test/reftest/bmp/bmpsuite/b/wrapper.html?badpalettesize.bmp' Z would be 607198. ...
Introduction to the JavaScript shell
The JavaScript shell (js) is a command-line program included in the SpiderMonkey source distribution. It is the JavaScript equivalent of Python's interactive prompt, the Lisp read-eval-print loop, or Ruby's irb. This article explains how to use the shell to experiment with JavaScript code and run JavaScript programs. To get the SpiderMonkey JavaScript shell, see the SpiderMonkey Build Documentation or download a compiled binary for your platform from the Nightly Builds. For a list of other JavaScript shells, see JavaScript shells. Note: Starting with SpiderMonkey 44 (Firefox 44 / Thunderbird 44 / SeaMonkey 2.41), the standard, Web-compatible JavaScript version is used by default (and not JS1.7+ anymore). The version() shell builtin is still there for testing legacy features. Running the J...
... Running the JavaScript shell The shell offers two modes of operation. You can use it as an interactive shell, in which you type JavaScript code at a prompt and get instant gratification, which is handy for experimenting or testing new features. You can also pass in, on the command line, a JavaScript program file to run, in which case the program is run automatically. After following the build documentation and installing the built shell using make install, you can run the shell in interactive mode using the command: js [ If you get " symbol lookup error: ./js: undefined symbol: PR_SetCurrentThreadName" e.g. from a Bash console when using a pre-compiled binary, try <path to your Firefox's run-mozilla.sh>/run-mozilla.sh ./js -- that worked for me] If you'd like to run the JavaScript code...
...do this: js -f foo.js -i Reference Note: Because the JavaScript shell is used as a test environment for the JavaScript engine, the available options and built-in functions can change over time. Command line options There are a number of command line options you can specify to control the shell. These are summarized below. Be sure to use -h with your own jsshell to see if there is anything undocumented. -c, --compileonly Tells the shell to compile the program but not run it. This is a convenient way to quickly check for syntax errors in your program without actually running it. -e script Runs the specified script, which is a literal string containing the code to execute. -f filename Runs the JavaScript program specified by filename. -i Enables interactive mode. (Default if no filena...
JIT Optimization Strategies
The JIT coach feature was removed in Bug 1614622. This page contains only historic information about this feature. Note: This page is an in-progress documentation of JIT optimization strategies planned to support the "JIT Coach" feature intended for inclusion in Firefox developer tools. This page has two intended uses: 1. Provide a repository of JIT Optimization Strategy information which the JIT Coach tool can parse to display in its UI. 2. Provide a user-browsable documentation of optimization strategies, how they work, how they are defeated, and options for how to re-enable them. SpiderMonkey's optimizing JIT, IonMonkey, uses various strategies to optimize operations. The most commonplace operations that are relevant for fast program execution are property accesses and function calls. ...
...perty (obj.prop = val) GetElement (obj[elemName]) SetElement (obj[elemName] = val) Call (func(...)) At each operation site, IonMonkey tries a battery of strategies, from the most optimized but most restrictive to the least optimized but least restrictive. For each strategy attempted, its outcome is tracked. An outcome is either success or a reason why the strategy failed to apply. This page documents the various optimization strategies and their outcomes. It provides information on what they attempt to do, what general level of speed-up they provide, what kind of program characteristics can prevent them from being used, and common ways to enable the engine to utilize that optimization. GetProperty GetProperty_ArgumentsLength Attempts to optimize an arguments.length property access. This o...
...ipt. If a property has always contained the same uniquely-typed object, then the engine can use the unique type to map back to a specific object, and eliminate the property access, replacing it with a constant reference to the object. When this optimization is successful, property access is eliminated entirely and replaced with an inline constant. The different success and failure conditions are documented below: GetProp_StaticName Attempts to optimize a property access on window which refers to a property on the global object. GetProp_TypedObject Optimizes accesses to properties on TypedObjects. GetProp_DefiniteSlot Optimizes access to a well-known regular property on an object. For this optimization to succeed, the property needs to be well-defined on the object. For objects constructed b...
JSObjectOps.defaultValue
See bug 408416 for details. ...
...See bug 408416 for details. ...
...See bug 408416 for details. ...
JSObjectOps.defineProperty
See bug 408416 for details. ...
...See bug 408416 for details. ...
...See bug 408416 for details. ...
JSObjectOps.destroyObjectMap
See bug 408416 for details. ...
...See bug 408416 for details. ...
...See bug 408416 for details. ...
JSObjectOps.dropProperty
See bug 408416 for details. The JSObjectOps.dropProperty callback releases a JSProperty. ...
...See bug 408416 for details. The JSObjectOps.dropProperty callback releases a JSProperty. ...
...See bug 408416 for details. The JSObjectOps.dropProperty callback releases a JSProperty. ...
JSObjectOps.getAttributes
See bug 408416 for details. ...
...See bug 408416 for details. ...
...See bug 408416 for details. ...
JSObjectOps.getProperty
See bug 408416 for details. ...
...See bug 408416 for details. ...
...See bug 408416 for details. ...
JSObjectOps.getRequiredSlot
See bug 408416 for details. ...
...See bug 408416 for details. ...
...See bug 408416 for details. ...
JSObjectOps.lookupProperty
See bug 408416 for details. ...
...See bug 408416 for details. ...
...See bug 408416 for details. ...
JSObjectOps.newObjectMap
See bug 408416 for details. ...
...See bug 408416 for details. ...
...See bug 408416 for details. ...
JSObjectOps.setProto
See bug 408416 for details. ...
...See bug 408416 for details. ...
...See bug 408416 for details. ...
SpiderMonkey 1.8
reduce() and reduceRight(), expression closures, and generator expressions. There is also one obscure non-backwards-compatible change. For details, see New in JavaScript 1.8. New JSAPI features It has been a couple years since SpiderMonkey 1.7 was released, and many improvements have been made to the JSAPI. However, one of the most important advances for JSAPI application developers is that the documentation is much improved. See the JSAPI User Guide and the JSAPI Reference. Native functions may implement the new callback signature JSFastNative instead of JSNative. JSFastNative can be significantly faster, but applications that use SpiderMonkey's fine-grained security features should heed the warning in its API documentation. New macros JS_FS, JS_FN, and JS_FS_END are recommended for populat...
...ear, such as in the argument to eval(). Functions that were JS_THREADSAFE-only in SpiderMonkey 1.7 (JS_BeginRequest, for example) are now present, but do nothing, in non-JS_THREADSAFE builds. This is to help applications share and reuse code regardless of whether they use threads. There are two new JSExtendedClass hooks, JSExtendedClass.iteratorObject and JSExtendedClass.wrappedObject. Both are documented but obscure. Many new memory management features have been added as well. The new function JS_SetScriptStackQuota limits the size of the JavaScript stack. Two new functions, JS_SetGCZeal and JS_DumpHeap, aim to help developers debug GC-related problems. These functions are only present in DEBUG builds. JS_SetGCZeal is especially helpful. When GC zeal is enabled, GC happens extremely frequ...
...ts of the GC heap and can help detect leaks. A new GC parameter, JSGC_STACKPOOL_LIFESPAN, controls how eagerly SpiderMonkey returns unused memory back to the system. The new function JS_SetExtraGCRoots provides another way to protect values from garbage collection. There is a new set of APIs for integrating SpiderMonkey's garbage collector with other memory management systems. These APIs are undocumented but fairly stable. The APIs include the new JSTraceOp callback. New JavaScript shell functions There are a few new built-in functions in the JavaScript shell, mostly useful for testing. countHeap, dumpHeap, gcparam, gczeal, and stackQuota are related to memory management. sleep and scatter, defined in <href="internal" a="" class="/en/SpiderMonkey/JSAPI_reference/JS_THREADSAFE" title="en/Sp...
Handling Mozilla Security Bugs
Introduction In order to improve the Mozilla project's approach to resolving Mozilla security vulnerabilities, mozilla.org is creating more formal arrangements for handling Mozilla security-related bugs. ...
...with primary responsibility for coordinating the investigation and resolution of reported Mozilla security vulnerabilities. The security module owner will have one or more peers to assist in this task. At the same time, mozilla.org is also creating a larger "Mozilla security bug group" by which Mozilla contributors and others can participate in addressing security vulnerabilities in Mozilla. This document describes how the new security organizational structure will work, and how security-related Mozilla bug reports will be handled. Note that the focus of this new structure is restricted solely to addressing actual security vulnerabilities arising from problems in Mozilla code. This work is separate from the work of developers adding new security features (cryptographically-based or otherwise) to ...
... above, information about security bugs can be held confidential for some period of time; there is no pre-determined lmit on how long that time period might be. However, this is offset by the fact that the person reporting a bug has visibility into the activities (if any) being taken to address the bug, and has the power to open the bug report for public scrutiny. The remaining sections of this document describe in more detail how these general policies have been implemented in practice. Organizational Structure for Handling Security Bugs We are organizing the investigation and fixing of Mozilla security vulnerabilities similar to the way Mozilla project activities are handled in general: There will be a security module owner, a small core of active contributors who can act as peers to the mod...
XForms Accessibility
two approaches to test XForms accessibility. The first is to use and assistive technology such as a screen reader, or an accessibility testing tool, to make sure XForms elements have proper accessible objects. Or you may be guided by toolkit checklist to check keyboard navigation for XForms controls. ...
...e and assistive technology such as a screen reader, or an accessibility testing tool, to make sure XForms elements have proper accessible objects. Or you may be guided by toolkit checklist to check keyboard navigation for XForms controls. ...
...air, IBM Accessibility Architecture Review Board) gave some clarification about navindex. He wrote: Navindex was in XForms - it was stripped out as it was believed the focus model was dependent on the content which used it. So, yes we don't care about navindex in XForms. If you use xhtml1.x use tabindex. If you use Xhtml2 use nextfocus. Therefore since Mozilla XForms works in XHTML (1.x) or XUL documents only then we use tabindex instead. Note, we support -moz-user-focus style neither for XHTML or XUL. AT API Accessible properties This section describes common rules how accessibility properties are formed for forms control elements. name It is formed from value of child XForms label element if the element doesn't have labelledby attribute. description It is formed from value of child XFor...
Using the Places history service
ost name, last referrer, flags for typed, hidden, and gecko flags (gecko flags is trunk only). The NavHistory service has broken this into two tables (see History Service Design). The main URL table stores the information about the page: URL, host name, title, visit count, hidden, and typed. Stored separately is the information specific to each visit. This information is called a "visit" in this document and in the code. A visit contains a reference to the URL table for the page, the visit date, the transition type (typed, click, redirect, bookmark, etc.), a reference to the referring visit, and the session ID. This separation of the global page information and the visit allows us to store information about each time the page was visited instead of just the last time. Using the referrer informat...
...ew one. break; } In case the database is locked by a third party process and cannot be opened, a "places-database-locked" notification is fired, in such a case the service won't be able to initialize. Adding pages to history nsIGlobalHistory2.addURI: This is the basic function for adding pages to history that is called by the docshell as you browse. The redirect flag is deprecated. See addDocumentRedirect below. nsIGlobalHistory3.addDocumentRedirect: This is called by the docshell when a redirect occurs. It replaces the old redirect flag on addURI. It gives the old and new channels to the history service so that the source page of the redirect can be determined. nsIBrowserHistory.addPageWithDetails: Called by history importing code. New code should use nsINavHistoryService.setPageDetails...
...ory.addPageWithDetails: Called by history importing code. New code should use nsINavHistoryService.setPageDetails. nsINavHistoryService.addVisit: This is an advanced function that allows the caller to set the exact referring visit, the time, the session, etc. It is designed for people writing synchronizing or backup services that need access to all the flags. Under normal browsing, addURI and addDocumentRedirect will infer this information for you. Modifying pages in history nsIGlobalHistory2.setPageTitle: Called by Gecko when the <title> element is encountered. nsIGlobalHistory3.setGeckoFlags: Called by Gecko to store rendering information about a page. Currently, this is used to store whether there was a scrollbar, which allows more efficient layout if the page is revisited. However, this is...
Building the WebLock UI
the AddSite method expects is a string, so we can pass a string directly in from the user interface, or we can do a check on the string and verify that it's a valid URL. In this tutorial, focusing as it is on the WebLock functionality (rather than the UI), we'll assume the strings we get from the UI itself are URLs we actually want to write to the white list: function addThisSite() { var tf = document.getElementById("dialog.input"); // weblock is global and declared above weblock.AddSite(tf.value); } This JavaScript function can be called directly from the XUL widget, where the input string is retrieved as the value property of the textbox element. You also need to create the function that displays the WebLock window itself when the user clicks the weblock icon in the statusbar. That fu...
... component and made it available to XPCOM, we create the UI that actually instantiates the WebLock component and uses its methods to control page loading in the browser. In the previous section, we outlined the JavaScript that interacts with the WebLock component. In this section, we are going to create the XUL interface that calls the JavaScript methods when the user interacts with it. The XUL Document The first thing to do is create the actual XUL document in which the user interface for the dialog and the events that initiate interaction with the web locking are defined. At the top of all XUL documents, an XML declaration is followed by the root element for the document, which is usually <window/> but for dialog boxes can also be the element <dialog/>. The "shell" for the XUL file, then, loo...
...oes not install cleanly in Mozilla Firefox due to Firefox's newness compared to this book (which was originally written in 2003). << 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 derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. ...
Components.utils.cloneInto
If you pass the {wrapReflectors:true} flag, then the object you clone is allowed to cont...
...criptObject.greetme(); }, false); Cloning objects that contain DOM elements By default, if the object you clone contains objects that are reflected from C++, such as DOM elements, the cloning operation will fail with an error. ...
... ...
imgILoader
add a summary to this article. ...
...n nsIChannel aChannel, in imgIDecoderObserver aObserver, in nsISupports cx, out nsIStreamListener aListener); boolean supportImageWithMimeType(in string mimeType); Constants Constant Value Description LOAD_CORS_ANONYMOUS 1 << 16 LOAD_CORS_USE_CREDENTIALS 1 << 17 Methods loadImage() Start the load and decode of an image. imgIRequest loadImage( in nsIURI aURI, in nsIURI aInitialDocumentURL, in nsIURI aReferrerURI, in nsIPrincipal aLoadingPrincipal, in nsILoadGroup aLoadGroup, in imgIDecoderObserver aObserver, in nsISupports aCX, in nsLoadFlags aLoadFlags, in nsISupports cacheKey, in imgIRequest aRequest, in nsIChannelPolicy channelPolicy ); Parameters aURI The URI to load. aInitialDocumentURL aReferrerURI The 'referring' URI. aLoadingPrincipal The principal...
... aReferrerURI, in nsIPrincipal aLoadingPrincipal, in nsILoadGroup aLoadGroup, in imgIDecoderObserver aObserver, in nsISupports aCX, in nsLoadFlags aLoadFlags, in nsISupports cacheKey, in imgIRequest aRequest, in nsIChannelPolicy channelPolicy ); Parameters aURI The URI to load. aInitialDocumentURL aReferrerURI The 'referring' URI. aLoadingPrincipal The principal of the loading document. aLoadGroup Loadgroup to put the image load into. aObserver The observer (may be null) aCX Some random data. aLoadFlags Load flags for the request. cacheKey aRequest A newly created, unused imgIRequest object or null for one to be created for you. libpr0n does NOT keep a strong ref to the observer; this prevents reference cycles. This means that callers of loadImage should make sure to Cancel() ...
nsIAccessible
ssible interface is a cross-platform interface that supports platform-specific accessibility APIs like MSAA and ATK. Contains the sum of what's needed to support IAccessible as well as ATK's generic accessibility objects. Can also be used by in-process accessibility clients to get information about objects in the accessible tree. The accessible tree is a subset of nodes in the DOM tree -- such as documents, focusable elements and text. Mozilla creates the implementations of nsIAccessible on demand. [scriptable, uuid=(c7520419-87ec-42bc-98cc-04c0bf173530)] interface nsIAccessible : nsISupports { ... }; accessible/public/nsIAccessible.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Overview This section provides...
...use nsIAccessible.indexInParent to get accessible index in its parent. Use nsIAccessible.groupPosition() to get information about this accessible in its group. Relations Many accessibles are linked with each other, for example, if one accessible gives the accessible name for another accessible (for example, html:label and html control) then these accessibles are related, please refer to relations documentation for more information. You can get related accessibles by methods nsIAccessible.getAccessibleRelated() nsIAccessible.getRelations() nsIAccessible.getRelation() and nsIAccessible.relationsCount. Focus and selection In order to focus an accessible or get focused child accessible use nsIAccessible.takeFocus() and nsIAccessible.focusedChild. To select an accessible you can use nsIAccessib...
...nded for this nsIAccessible.actionCount, nsIAccessible.getActionName(), nsIAccessible.getActionDescription() and nsIAccessible.doAction(). Descriptions nsIAccessible.description and nsIAccessible.help provides additional text information about accessible. Attributes Many accessibles exposes attributes to provide more details that cannot be fit into existing API methods, please refer to attributes documentation for more information. You can use nsIAccessible.attributes to get a map of attributes. Keyboard shortcuts Some actions on accessibles can be performed by keyboard shortcuts. Following methods are used to get them nsIAccessible.defaultKeyBinding(), nsIAccessible.getKeyBindings(), nsIAccessible.keyboardShortcut. Size and screen position You can use nsIAccessible.getBounds() to get size and coo...
nsIAccessibleHyperText
A typical implementation is to implement this interface on the small text object such as a paragraph of text. ...
...A typical implementation is to implement this interface on the small text object such as a paragraph of text. ...
...A typical implementation is to implement this interface on the small text object such as a paragraph of text. ...
nsIContentSecurityPolicy
on reports when queried, so this value should not be cached. Read only. allowsInlineScript boolean Whether this policy allows in-page script. Calls to this may trigger violation reports when queried, so this value should not be cached. Read only. isInitialized boolean Set to true when the Content Security Policy has been read in and parsed and is ready to enforce. This is a barrier for the nsDocument so it doesn't load any sub-content until either it knows that a Content Security Policy is ready or will not be used. policy AString A read-only string version of the policy for debugging. Read only. reportOnlyMode boolean When set to true, content load-blocking and fail-closed are disabled: Content Security Policy will only send reports, and not modify behavior. Methods permitsAncestry() ...
...eports() Manually triggers violation report sending given a URI and reason. The URI may be null, in which case "self" is sent. void sendReports( in AString blockedURI, in AString violatedDirective ); Parameters blockedURI The URI that violated the policy. violatedDirective The directive that was violated. shouldLoad() Delegate method called by the service when sub-elements of the protected document are being loaded. Given a bit of information about the request, decides whether or not the policy is satisfied. Calls to this may trigger violation reports when queried, so this value should not be cached. short shouldLoad( in unsigned long aContentType, in nsIURI aContentLocation, in nsIURI aRequestOrigin, in nsISupports aContext, in ACString aMimeTypeGuess, in nsISupports aExtra ); ...
...cached. short shouldLoad( in unsigned long aContentType, in nsIURI aContentLocation, in nsIURI aRequestOrigin, in nsISupports aContext, in ACString aMimeTypeGuess, in nsISupports aExtra ); Parameters aContentType aContentLocation aRequestOrigin aContext aMimeTypeGuess aExtra Return value shouldProcess() Delegate method called by the service when sub-elements of the protected document are being processed. Given a bit of information about the request, decides whether or not the policy is satisfied. short shouldProcess( in unsigned long aContentType, in nsIURI aContentLocation, in nsIURI aRequestOrigin, in nsISupports aContext, in ACString aMimeType, in nsISupports aExtra ); Parameters aContentType aContentLocation aRequestOrigin aContext aMimeType aExtra Re...
nsIDOMSerializer
Inherits from: nsISupports Last changed in Gecko 1.7 Implemented by: @mozilla.org/xmlextras/xmlserializer;1. ...
... charset); AString serializeToString(in nsIDOMNode root); Methods serializeToStream() The subtree rooted by the specified element is serialized to a byte stream using the character set specified. void serializeToStream( in nsIDOMNode root, in nsIOutputStream stream, in AUTF8String charset ); Parameters root The root of the subtree to be serialized. This could be any node, including a Document. stream The byte stream to which the subtree is serialized. charset The name of the character set to use for the encoding to a byte stream. If this string is empty and root is a document, the document's character set will be used. serializeToString() The subtree rooted by the specified element is serialized to a string. AString serializeToString( in nsIDOMNode root ); Parameters root The roo...
...e name of the character set to use for the encoding to a byte stream. If this string is empty and root is a document, the document's character set will be used. serializeToString() The subtree rooted by the specified element is serialized to a string. AString serializeToString( in nsIDOMNode root ); Parameters root The root of the subtree to be serialized. This could be any node, including a Document. Return value The serialized subtree in the form of a Unicode string. ...
nsIDOMWindow
dom/interfaces/base/nsIDOMWindow.idlScriptable This interface is the primary interface for a window object. It represents a single window object that may contain child windows if the document in the window contains an HTML frameset document, or if the document contains iframe elements. 66 Introduced Gecko 1.0 Deprecated Gecko 44 Inherits from: nsISupports Last changed in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) Starting with Firefox 44, this file is empty as its features were either no longer used or are only available from C++ code; see dom/base/nsPIDOMWindow.h for those. While this interface is not officially defined by any standard bodies, it originates from the de-facto DOM Level 0 standard. Starting in Firefox 3, DOM windows ar...
...Lines); void scrollByPages(in long numPages); void scrollTo(in long xScroll, in long yScroll); void sizeToContent(); Attributes Attribute Type Description applicationCache nsIDOMOfflineResourceList Get the application cache object for this window. Read only. Note: Prior to Gecko 7.0 this attribute was part of nsIDOMWindow2. document nsIDOMDocument The document contained in the window. Read only. frames nsIDOMWindowCollection The child windows for this window. Read only. Native code only! globalStorage nsIDOMStorageList Global storage, accessible by domain. Read only. Note: Prior to Gecko 8.0 this attribute was part of nsIDOMStorageWindow. localStorage nsIDOMStorage Local sto...
...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 this attribute was part of nsIDOMStorageWindow. textZoom float Get or set the document scale factor as a multiplier of the default size. When setting this attribute, an NS_ERROR_NOT_IMPLEMENTED error may be returned by implementations not supporting zoom. This attribute should always return 1.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 conta...
nsIDOMWindowInternal
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 parameters optional; in previous versions, all parameters were required. void alert(in DOMString text) ...
...e to the window that opened this current window. status DOMString Sets the text in the status bar at the bottom of the browser or returns the previously set text. defaultStatus DOMString Gets/sets the status bar text for the given window. location nsIDOMLocation Readonly: Returns a nsIDOMLocation object, which contains information about the URL of the document. innerWidth long Width of the browser window. innerHeight long Height of the browser window. outerWidth long Gets the width of the outside of the browser window. outerHeight long Gets the height of the outside of the browser window. screenX long The horizontal distance of the left border of the user's browser from the left...
... outerHeight long Gets the height of the outside of the browser window. screenX long The horizontal distance of the left border of the user's browser from the left side of the screen. screenY long The vertical distance of the top border of the user's browser from the top edge of the screen. pageXOffset long Returns the number of pixels that the document has already been scrolled horizontally. pageYOffset long Returns the number of pixels that the document has already been scrolled vertically. scrollMaxX long Returns the maximum number of pixels that the document can be scrolled horizontally. scrollMaxY long Returns the maximum number of pixels that the document can be scrolled vertically. len...
nsIDOMXPathExpression
dom/interfaces/xpath/nsIDOMXPathExpression.idlScriptable Represents a compiled XPath query returned from nsIDOMXPathEvaluator.createExpression or document.createExpression Inherits from: nsISupports Last changed in Gecko 1.7 Method overview nsISupports evaluate(in nsIDOMNode contextNode, in unsigned short type, in nsISupports result) Methods evaluate() Evaluate the XPath expression. nsISupports evaluate( in nsIDOMNode contextNode, in unsigned short type, in nsISupports result ); Parameters contextNode A DOM node to evaluate the XPath expression against. To evaluate against a whole document, use the document.documentElement method to get the node to evaluate against. type A number that corresponds to one of the type constants of nsIDOMXPathResu...
...document, use the document.documentElement method to get the node to evaluate against. type A number that corresponds to one of the type constants of nsIDOMXPathResult. result An existing nsIDOMXPathResult to use for the result. Using null will create a new nsIDOMXPathResult. Return value An XPath result. ...
...ocument.documentElement method to get the node to evaluate against. ...
nsIDroppedLinkHandler
dom/base/nsIDroppedLinkHandler.idlScriptable Please add a summary to this article. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview boolean canDropLink(in nsIDOMDragEvent aEvent, in PRBool aAllowSameDocument); AString dropLink(in nsIDOMDragEvent aEvent, out AString aName, [optional] in boolean aDisallowInherit); void dropLinks(in nsIDOMDragEvent aEvent, [optional] in boolean aDisallowInherit, [optional] out unsigned long aCount, [retval, array, size_is(aCount)] out nsIDroppedLinkItem aLinks); Methods canDropLink() Determines if a link being dragged can be dropped. boolean canDropLink( in nsIDOMDragEvent aEvent, in PRBool aAllowSa...
...ing aName, [optional] in boolean aDisallowInherit); void dropLinks(in nsIDOMDragEvent aEvent, [optional] in boolean aDisallowInherit, [optional] out unsigned long aCount, [retval, array, size_is(aCount)] out nsIDroppedLinkItem aLinks); Methods canDropLink() Determines if a link being dragged can be dropped. boolean canDropLink( in nsIDOMDragEvent aEvent, in PRBool aAllowSameDocument ); Parameters aEvent A dragenter or dragover event. aAllowSameDocument If false, drops are only allowed if the document of the source of the drag is different from the destination. This check includes any parent, sibling and child frames in the same content tree. If true, the source is not checked. Return value true if the link being dragged can be dropped. Exceptions thrown Missin...
...t exists, or an empty string otherwise. Return value A uri, or null if there is no valid link to be dropped. Exceptions thrown NS_ERROR_DOM_SECURITY_ERR Error will be thrown and the event canceled if the receiving target should not load the uri for security reasons. This will occur if the source of the drag initiated a link for dragging that it itself cannot access. This prevents a source document from tricking the user into a dragging a chrome url for example. dropLinks() Given a drop event, determines the link being dragged. If non-empty links array is returned the caller can, for instance, load it. If empty links array is returned, there is no valid link to be dropped. void dropLinks( in nsIDOMDragEvent aEvent, [optional] in boolean aDisallowInherit, [optional] out unsigned lo...
nsIFeedTextConstruct
nsISupports Last changed in Gecko 1.8.1 (Firefox 2 / Thunderbird 2 / SeaMonkey 1.1) Implemented by: @mozilla.org/feed-textconstruct;1, but users usually don't need to create instances of this directly. Various other feed-related interfaces, such as nsIFeed, nsIFeedEntry, and nsIFeedContainer have attributes that return objects implementing nsIFeedTextConstruct. Method overview nsIDOMDocumentFragment createDocumentFragment(in nsIDOMElement element); AString plainText(); Attributes Attribute Type Description base nsIURI If the text construct contains HTML or XHTML, relative references in the content should be resolved against this base URI. lang AString The language of the text (such as "en-US" for U.S. English). te...
...e references in the content should be resolved against this base URI. lang AString The language of the text (such as "en-US" for U.S. English). text AString The actual text content. This string may contain markup if the type is either "html" or "xhtml". type AString The type of content described; one of "text", "html", or "xhtml". Methods createDocumentFragment() Creates a new document fragment on a given DOM element, containing the text and (if the text construct contains HTML or XHTML) its markup. nsIDOMDocumentFragment createDocumentFragment( in nsIDOMElement element ); Parameters element The element in which to create the new document fragment. Return value An nsIDocumentFragment containing the text and markup. plainText() Ret...
...ment. Return value An nsIDocumentFragment containing the text and markup. plainText() Returns the text as plain text with all markup stripped and all entities decoded. AString plainText(); Parameters None. Return value The plain text version of the text construct's contents. If the type attribute is "text", this method returns the value of the text attribute unchanged. Remarks If the document type is either "html" or "xhtml", a "<" character represents markup. To display that character, an escape such as "&lt;" must be used. If the type is "text", the "<" character represents itself. See also nsIDOMElement nsIDocumentFragment Interwiki link ...
nsILocalFileMac
to avoid using it. Init this object with an FSSpec Legacy method - leaving in place for now. void initWithFSSpec( [const] in FSSpecPtr aFileSpec ); Parameters aFileSpec The native file spec. isPackage() boolean isPackage(); Parameters None. Return value true if a directory is determined to be a package under Mac OS 9/X. launchWithDoc() Launch the application that this file points to with a document. void launchWithDoc( in nsILocalFile aDocToLoad, in boolean aLaunchInBackground ); Parameters aDocToLoad Must not be null. If no document, use nsILocalFile::launch. aLaunchInBackground true if the application should not come to the front. openDocWithApp() Open the document that this file points to with the given application. void openDocWithApp( in nsILocalFile aAppToOpenWith, in boole...
...aLaunchInBackground true if the application should not come to the front. ...
...aLaunchInBackground true if the application should not come to the front. setFileTypeAndCreatorFromExtension() Obsolete since Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Sets the file type and creator code from a file extension Internet Config is used to determine the mapping. ...
nsIPrintingPrompt
ser/nsIPrintingPrompt.idlScriptable This is the printing prompt interface which can be used without knowlege of a parent window. The parentage is hidden by the GetInterface though which it is gotten. Inherits from: nsISupports Last changed in Gecko 1.7 This interface is identical to nsIPintingPromptService but without the parent nsIDOMWindow parameter. See nsIPrintingPromptService for all documentation. This service enables embedders to implement their own Print and Progress Dialogs. Each platform has a "base" or "backstop" implementation of the service. The service is automatically registered at start up. Historically, platform toolkits with native dialogs have implemented them in the GFX layer Usually they were displayed when a new DeviceContextSpec specific to that platform was create...
...s for page setup. aObs Optional An observer to know if the contents of the Print Settings object has changed while the dialog is being shown. For example, some platforms may implement an "Apply" button. showPrintDialog() Show the Print Dialog. void showPrintDialog( in nsIWebBrowserPrint webBrowserPrint, in nsIPrintSettings printSettings ); Parameters webBrowserPrint Represents the document to be printed. printSettings PrintSettings for print "job". showProgress() Shows the print progress dialog. void showProgress( in nsIWebBrowserPrint webBrowserPrint, in nsIPrintSettings printSettings, in nsIObserver openDialogObserver, in boolean isForPrinting, out nsIWebProgressListener webProgressListener, out nsIPrintProgressParams printProgressParams, out boolean notifyOnO...
... "job". showProgress() Shows the print progress dialog. void showProgress( in nsIWebBrowserPrint webBrowserPrint, in nsIPrintSettings printSettings, in nsIObserver openDialogObserver, in boolean isForPrinting, out nsIWebProgressListener webProgressListener, out nsIPrintProgressParams printProgressParams, out boolean notifyOnOpen ); Parameters webBrowserPrint Represents the document to be printed. printSettings PrintSettings for print "job" openDialogObserver An observer that will be notifed when the dialog is opened. isForPrinting true - for printing, false for print preview. webProgressListener Additional listener can be registered for progress notifications. printProgressParams Parameter object for passing progress state. notifyOnOpen This indicates that the o...
nsISelection
Implemented by: ?????????????????????????????????????. ...
...MRange range); void collapse(in nsIDOMNode parentNode, in long offset); [noscript,notxpcom,nostdcall] boolean collapsed(); void collapseNative(in nsIDOMNode parentNode, in long offset); Native code only! void collapseToEnd(); void collapseToStart(); boolean containsNode(in nsIDOMNode node, in boolean partlyContained); void deleteFromDocument(); void extend(in nsIDOMNode parentNode, in long offset); void extendNative(in nsIDOMNode parentNode, in long offset); Native code only! nsIDOMRange getRangeAt(in long index); void modify(in DOMString alter, in DOMString direction, in DOMString granularity); void removeAllRanges(); void removeRange(in nsIDOMRange range); void select...
... true when the entire node is part of the selection. boolean containsNode( in nsIDOMNode node, in boolean partlyContained ); Parameters node The nsIDOMNode to look for partlyContained If partlyContained is set to PR_FALSE, the function only returns true when the entire node is part of the selection. Return value Whether or not the range contains the requested noe. deleteFromDocument() Deletes this selection from the document the nodes belong to. void deleteFromDocument(); extend() Extends the selection by moving the selection end to the specified nsIDOMNode and offset, preserving the selection begin position. The new selection end result will always be from the anchorNode to the new focusNode, regardless of direction. void extend( in nsIDOMNode parentNode, in long offse...
nsISessionStore
ndows is stored in last in/first out (LIFO) order, so the window at index 0 is the last one that was closed. Return value Returns a reference to the reopened window as an nsIDOMWindow object. Note on windows The nsISessionStore API stores state information for certain windows inside the web brower. These windows are nsIDOMWindow objects that contain the tabbrowser that users see as tabs; the document in these windows is browser.xul. For many extensions, those that overlay browser.xul, the appropriate window object for nsISessionStore is the global object 'window'. For JavaScript running in windows other than the one you want to use in nsISessionStore, you need a nsIDOMWindow object containing browser.xul. This will be the outermost or root nsIDOMWindow in a nsIXULWindow (the window seen by ...
...instanceof nsIInterfaceRequestor) { var win = xul_win.docShell.getInterface(nsIDOMWindow); ... Note on tabs The nsISessionStore APIs referencing nsIDOMNode aTab require you to get hold of the tab node storing the data. If you you are working in a browser.xul overlay and want the currently selected tab, it's as simple as gBrowser.selectedTab. ...
...cing nsIDOMNode aTab require you to get hold of the tab node storing the data. If you you are working in a browser.xul overlay and want the currently selected tab, it's as simple as gBrowser.selectedTab. If you just hold a reference to some content document in the overlay's chrome window, here is how you find its corresponding tab: function tabFromDoc(doc) { var no = gBrowser.getBrowserIndexForDocument(doc); return gBrowser.tabContainer.childNodes[no]; } // example use: Cc['@mozilla.org/browser/sessionstore;1'] .getService(Ci.nsISessionStore) .setTabValue(tabFromDoc(myContentDoc), 'myKey', 'myValue'); See also The Session store API article. nsISessionStartup JSON ...
nsITextInputProcessor
means that another instance of nsITextInputProcessor has composition on the window or is dispatching an event. In this case, other instances cannot create composition nor dispatch keyboard events on the window. The second argument, callback, should be an object which implements nsITextInputProcessorCallback or just a function which is the same as nsITextInputProcessorCallback.onNotify(). See the document of nsITextInputProcessorCallback for the detail. Next, you can set the composition string or dispatch keyboard events. The following example sets "foo-bar-buzz", "bar" is selected clause to convert, and caret position is the end of the selected clause: // First, sets composition string. TIP.setPendingCompositionString("foo-bar-buzz"); // Next, append clauses. TIP.appendClauseToPendingCompositi...
...s composing on the window, this associates the instance with the window and registers the callback to the instance. boolean beginInputTransaction(in nsIDOMWindow aWindow, in nsITextInputProcessorCallback aCallback); Parameters aWindow The DOM window which has focused editor. This must not be null. aCallback The callback object. This must not be null. See the document of nsITextInputProcessorCallback for the details. Return value Returns true if the instance could create composition. Otherwise, false. beginInputTransactionForTests() This must be called before starting composition for automated tests every time. This tries to get the rights to create composition on the window. If no other instance is composing on the window, this associates the instance wi...
...callback to the instance if it's specified. boolean beginInputTransactionForTests(in nsIDOMWindow aWindow, in nsITextInputProcessorCallback aCallback Optional); Parameters aWindow The DOM window which has focused editor. This must not be null. aCallback The callback object. If this is not specified, requests to IMEs are handled automatically. See the document of nsITextInputProcessorCallback for the details. Return value Returns true if the instance could create composition. Otherwise, false. cancelComposition() Cancels the composition which was created by the instance. If you call this when there is no composition, this throws an exception. void cancelComposition(in nsIDOMKeyEvent aDOMKeyEvent Optional, in unsigned long a...
Using nsIDirectoryService
is implementation will allow you to Get(), Set(), Define(), and Undefine() nsIFile. Getting a location: Most developers need to find where a file or directory is located. With nsDirectoryService, there are two steps involved. First, you must know what the string key (or property) is that refers to this locations. Header files containing known keys are listed in the Known Locations section of this document. Bear in 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_...
...leLocator and still be able to use the same components directory as an existing Mozilla installation, you had to make a component with the same ID as nsIFileLocator and then, after auto-registering components, manually register your own and replace the existing one -- all in all, a big pain. The New Method The new method uses nsIDirectoryService to locate files and directories. Be sure to see the documentation on the service itself. This document will focus on how the service is used and how to customize it. Briefly, nsIDirectoryService uses "providers" of type nsIDirectoryServiceProvider to provide file locations. When the service is asked for a file location, it goes through its list of providers asking each if it knows the requested location until it finds one that does. Once the service finds ...
...ess that need these locations at a very early point - even before registering components. If you want to use mpfilelocprovider, or something like it, to provide one fixed profile, just construct it and call its Initialize method - it will register itself. Again, if you do this, do not initialize the profile service - it's either one or the other. Related Pages Code_snippets:File_I/O Original Document Information Authors: Conrad Carlen, Doug Turner Last Updated Date: September 26, 2000 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
XPCOM
thod.Interfacing with the XPCOM cycle collectorThis is a quick overview of the cycle collector introduced into XPCOM for Firefox 3, including a description of the steps involved in modifying an existing C++ class to participate in XPCOM cycle collection. ...
...It is available to trusted callers, meaning extensions and Firefox components only.The Thread ManagerThe Thread Manager, introduced in Firefox 3, offers an easy to use mechanism for creating threads and dispatching events to them for processing. Troubleshooting XPCOM components registrationOften the first time you create an XPCOM component, it may fail to register correctly.Using nsCOMPtrThis document is the sum total of everything written down about nsCOMPtr. If you have a question about nsCOMPtr, and this document doesn't answer it, there probably isn't a document that answers it. You'll have to turn to the XPCOM newsgroup or another experienced nsCOMPtr user, or find the answer by experimentation.Using nsIClassInfoIf you use a C++ class which implements nsIClassInfo from JavaScript, then yo...
...n servers sending correct MIME types; images sent with incorrect MIME types would not be correctly displayed.XPCOM glueThe XPCOM Glue is a static library which component developers and embedders can link against. It allows developers to link only against the frozen XPCOM method symbols and maintain compatibility with multiple versions of XPCOM.XPCOM guideThese 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.XPCOM ownership guidelines...naturally. If you create a temporary object, obviously it's up to you to destroy it. That's a sure sign of ownership. If you create an object with a longer lifespan, you will own it until you give ownership away.XPCOM referenceThis refer...
Filelink Providers
nsIMsgCloudFileProvider Note: Cloudfiles and BigFiles were the two temporary feature names that were used while Filelink was under construction. Both refer to the Filelink feature. Filelink storage providers must implement the nsIMsgCloudFileProvider interface. The Hightail implementation is a great place to look for examples and inspiration. ...
...dd the components to the cloudfile/cloudFileComponents.manifest, cloudfile/jar.mn, and installer/package-manifest.in. If the nsIMsgCloudFileProvider is being created as part of an add-on, the add-on must register the component in chrome.manifest. Also, you must add the component's contract ID to the "cloud-file" category. See cloudfile/cloudFileComponents.manifest for an example, as well as this document on chrome.manifest files. The Account Setup Dialog The account setup dialog allows the user to select what account type they would like to create from a menulist. Some providers require Thunderbird to do very little in order to connect a user to their account. Other providers however may require the user to fill in additional details in order to connect to the service. Hightail, for example,...
... need only provide an extraArgs function in the IFrame content which returns an object specifying the name, type, and value to save. The format for the returned object is: { FIELD_NAME: {type: FIELD_TYPE, value: FIELD_VALUE} } Where FIELD_TYPE is "int", "bool", or "char". For example, the Hightail implementation provides the following function: function extraArgs() { var usernameValue = document.getElementById("username").value; return { "username": {type: "char", value: usernameValue}, }; } In this example, the username value is read from the input, and then the specially-crafted object is returned. Once this is done, the field is accessible from within the implementation via the Preferences API using the key mail.cloud_files.accounts.ACCOUNT_KEY.username where ACCOUNT_KEY is...
Mail and RDF
Warning: The content of this article may be out of date. It was imported from mozilla.org and last updated in 1999. Mozilla Mail exposes many of it's data structures to RDF through a few datasources. This allows exposure of mailnews-specific data to user interface using RDF Templates. You should learn about RDF before reading this document or you will be hopelessly confused. Overview of Mail RDF graph The root resource for all accounts, folders and messages is the RDF Resource named msgaccounts:/. From this resource, you can follow a number of arcs to find servers, folders, and finally messages. Eventually we'll probably hang mail filters, annotations, etc, off of nodes in the graph. Here is an example of how this might be set up: In this tree-style representation of an RDF g...
... 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 methods of reflecting data into RDF. Answering queries: When RDF asks for information about a resource, data...
...ata into RDF. Answering queries: When RDF asks for information about a resource, datasources answer with the results of the query. Asynchronously notifying RDF when the data itself changes, RDF needs to be notified. The details Answering Queries Mail uses RDF Resource Factories to attach mail-specific information to RDF resources. (The details of RDF Resource Factories will be left to RDF documentation for now.) From an RDF Resource, it is possible to QueryInterface() to the appropriate mail/news object, and then access information from there. For example, the folder pane needs to display the number of messages in the INBOX. Information for this column is queried when the tree's RDF Template calls the folder datasource's GetTarget() method. The query's target is the resource named mailbox...
Mail composition back end
interface that accomplishes this task is the nsIMsgSend interface. The feedback mechanism is provided by a nsIMsgSendListener which is implemented by the caller. The caller has the ability to add or remove listener interfaces to the nsIMsgSend object and the interface can support multiple listeners. (For detailed information on the listener interfaces, see the Listener Interfaces section of this document) nsIMsgSend The following describes the methods of the nsIMsgSend interface. All of these methods are asynchronous operations. CreateAndSendMessage The CreateAndSendMessage method will create an RFC822 message and send it all in one operation as well as providing the ability to save disk files for later use. The mode of delivery can also be specified ...
...or the person doing the send operation. This will be needed to determine the appropriate folder for copy operations. nsIMsgCompFields *fields, - the message composition fields. This will contain all of the relevant header information for message creation PRBool digest_p, - this is a flag that says that most of the documents we are attaching are themselves messages, and so we should generate a multipart/digest container instead of multipart/mixed. (It's a minor difference.) PRBool dont_deliver_p, - If "dont_deliver_p" is false, then we actually deliver the message to the SMTP and/or NNTP server nsMsgDeliverMode mode, - mode is the d...
... (It's a minor difference.) nsMsgDeliverMode mode, - mode is the delivery mode. This can be set for the various modes of delivery. These can include nsMsgDeliverNow, nsMsgQueueForLater, nsMsgSave, nsMsgSaveAs, nsMsgSaveAsDraft, ...
Building a Thunderbird extension 5: XUL
ent location and renaming it to omni.zip. If you have trouble with one zip manager (like 7zip) try another (like WinRAR). In messenger.xul we find the status bar, which looks something like this.: <statusbar id="status-bar" ...> ... <statusbarpanel>s ... </statusbar> <statusbar id="status-bar"> is a "merge point" for a XUL overlay. XUL Overlays are a way of attaching other UI widgets to a XUL document at run time. A XUL Overlay is a .xul file that specifies XUL fragments to insert at specific merge points within a "master" document. These fragments can specify widgets to be inserted, removed or modified. In this example you are adding a line to the indented statusbar. Therefore it becomes an item owned by the id called "status-bar". This shows how the Thunderbird architecture allows extension...
...ted, removed or modified. In this example you are adding a line to the indented statusbar. Therefore it becomes an item owned by the id called "status-bar". This shows how the Thunderbird architecture allows extensions to modify the user experience without modifying the installation files. This also enables version independence between Thunderbird and Thunderbird extensions. ...
... 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 <statusbar> tag and merge them with the original XUL 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...
Building a Thunderbird extension 6: Adding JavaScript
eme 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-panel"); var date = new Date(); var day = date.getDay(); 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>-...
... = new Date(); var day = date.getDay(); 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...
...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 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 >> ...
Thunderbird extensions
Need personalized help? See Community / Communications. Warning: This content is for older versions of Thunderbird. Much of it may no longer be relevant. See developer.thunderbird.net for newer information. ...
... Need personalized help? See Community / Communications. Warning: This content is for older versions of Thunderbird. Much of it may no longer be relevant. See developer.thunderbird.net for newer information. ...
...larities with Firefox extensions, but there are also differences that may confound the starting Thunderbird developer. This documention series focuses on Thunderbird. Need personalized help? See Community / Communications. Warning: This content is for older versions of Thunderbird. Much of it may no longer be relevant. See developer.thunderbird.net for newer information. Documentation Getting started with Thunderbird A brave, young developer wants to develop an add-on for Thunderbird. These links to help through this journey. Start by reading the tutorial and learn how to build a Thunderbird extension. Also see Thunderbird 57-60 add-ons guide for changes introduced in Thunderbird 60. Read about the main windows to learn about << thread pane >>, ...
Thunderbird
Thunderbird is built on the same technical platform as the Firefox web browser. Currently one of the most popular open source email clients, it is used by tens of millions of people around the world to bring together all their email accounts, chat, newsgroup and feed reading in a familiar high-productivity environment. ...
...form as the Firefox web browser. Currently one of the most popular open source email clients, it is used by tens of millions of people around the world to bring together all their email accounts, chat, newsgroup and feed reading in a familiar high-productivity environment. (From early 2007 to early 2011 Thunderbird was developed by Mozilla Messaging, a subsidiary owned by Mozilla.) Documentation Building Thunderbird Information about building Thunderbird with the comm-central repository. There's also information about how the review process works and how to use the Mozilla symbol server to help with debugging. MailNews Protocols Rough documentation about mail protocols.. Database views Backend information about nsIMsgDBView and related interfaces.
...ing Thunderbird Information about building Thunderbird with the comm-central repository. There's also information about how the review process works and how to use the Mozilla symbol server to help with debugging. MailNews Protocols Rough documentation about mail protocols.. Database views Backend information about nsIMsgDBView and related interfaces. Thunderbird API documentation Thunderbird API documentation Extension documentation Tutorials and tips for building Thunderbird extensions View All... Community Thunderbird product home page Thunderbird project community pages User support is handled at Mozilla Support Development discussion happens on the tb-planning mailing list: subscribe ...
WebIDL bindings
The WebIDL bindings are generated at build time based on two things: the actual WebIDL file and a configuration file that lists some metadata about how the WebIDL should be reflected into Gecko-internal code. All WebIDL files should be placed in dom/webidl and added to the list in the moz.build file in that directory. Note that if you're adding new interfaces, then the test at dom/tests/mochitest/general/test_interfaces.html will most likely fail. This is a signal that you need to get a review from a DOM peer. Resist the urge to just add your interfaces to the moz.build list without the review; it will just annoy the DOM peers and they'll make you get the review anyway. ...
...n instance of your class, returns the same object every time (unless you write explicit code that handles your parent object changing by reparenting JS wrappers, as nodes do). The idea is that walking the GetParentObject chain will eventually get you to a Window, so that every WebIDL object is associated with a particular Window. For example, nsINode::GetParentObject returns the node's owner document. The return type of GetParentObject doesn't matter other than it must either singly-inherit from nsISupports or have a corresponding ToSupports method that can produce an nsISupports from it. (This allows the return value to be implicitly converted to a ParentObject instance by the compiler via one of that class's non-explicit constructors.) If many instances of MyInterface are expected to b...
...s A dictionary argument is represented by a const reference to a struct whose name is the dictionary name in the mozilla::dom namespace. The struct has one member for each of the dictionary's members with the same name except the first letter uppercased and prefixed with "m". The members that are required or have default values have types as described under the corresponding WebIDL type in this document. The members that are not required and don't have default values have those types wrapped in Optional<>. Dictionary return values are represented by an out parameter whose type is a non-const reference to the struct described above, with all the members that have default values preinitialized to those default values. Note that optional dictionary arguments are always forced to have a default va...
Standard OS Libraries
you make must be shipped with your add-on. Standard libraries offer the advantage of not having to ship anything. They are already available on the operating system for you. You just need to supply the path to appropriate files and set up the proper types of values/arguments in the js-ctypes code. This article allows you to find out what types to give to values/arguments by supplying links to the documentation of the OS libraries. Windows Windows has many Standard OS Libraries. The most common, found on all Windows OS version, is "WinAPI". Windows also has the "WinAPILists" and ".NET Framework" (I'm not sure if it can be accessed JSCtypes but probably). A complete list of Windows APIs can be found at the MSDN API Index. WinAPI This is the one that is most commonly used by js-ctypes. This comes...
... library that Linux uses, and that can be used through js-ctypes, is X11. GDK As mentioned, all Firefox's are a GTK+ app, which means it has to have GDK, as GDK is underlying level of GTK+. Therefore all the GDK library functions are available for use. GDK has version 2 and 3, typically version 2 is referred to as just GDK and version 3 is referred to as GDK3. Examples for both are found below. Documentation for GDK functions are found here: GNOME Developer :: GDK 2 Reference Manual. For GDK3 documentation is found here: GNOME Developer :: GDK 3 Reference Manual. Because GNOME is in the name of the websites don't get confused and think this only works on GNOME. It is true though that GDK was developed by the GNOME team. Example: gdk_window_get_pointer This example is fot the GDK 2.0 library. I...
...erating systems like Linux, all of the BSD variants, Sun Solaris both native 32 and 64 bit support, Solaris x86, Mac OS X (via Darwin) as well as other platforms like OS/2 and Cygwin. There are updates that happen to X11; at the time of this writing, the latest version is 4.4.0. Information on all releases can be found on its official page X11 Resources. Syntax and variable types are found on the documentation pages linked from this page. For example the documentation for v4.4.0 is seen here: X11 Manual pages: Section 3. Example: XQueryPointer Get mouse cursor position and some extra information. Documentation on this function is found at XFree86 :: XQueryPointer(3X11) Manual Page. Components.utils.import("resource://gre/modules/ctypes.jsm"); let X11 = ctypes.open("libX11.so.6"); let Display_pt...
Using js-ctypes
loaded from the system's Carbon framework. Line 11 declares the stdAlert() function, which will call the Carbon StandardAlert routine. It uses the default ABI, returns a 16-bit integer (which is a Carbon OSErr value), and accepts an integer (the alert type), two strings, a pointer to a parameter block, which we aren't using, and another integer, which is used to return the hit item. See Apple's documentation for StandardAlert for details. After that, we simply set up our parameters by using makeStr() to generate the two Str255 strings we need, then call stdAlert(), which produces the following alert window: The last thing we do is call carbon.close() to close the library when we're done using it. Standard Alert in 64bit OS X Carbon is not available in 64bit versions of OS X, therefore Core...
....StructType("__CFAllocator"); var CFAllocatorRef = __CFAllocator.ptr; var UniChar = ctypes.jschar; // uint16 with automatic conversion // DEFINE CONSTANTS var kCFUserNotificationStopAlertLevel = 0; var kCFUserNotificationNoteAlertLevel = 1; var kCFUserNotificationCautionAlertLevel = 2; var kCFUserNotificationPlainAlertLevel = 3; // DECLARE FUNCTIONS /* https://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFUserNotificationRef/index.html#//apple_ref/c/func/CFUserNotificationDisplayNotice * SInt32 CFUserNotificationDisplayNotice ( * CFTimeInterval timeout, * CFOptionFlags flags, * CFURLRef iconURL, * CFURLRef soundURL, * CFURLRef localizationURL, * CFStringRef alertHeader, * CFStringRef alertMessage, * CFStringRef defaultButtonTitle * ); */ v...
...NotificationDisplayNotice = libcf.declare("CFUserNotificationDisplayNotice", ctypes.default_abi, SInt32, // return CFTimeInterval, // timeout CFOptionFlags, // flags CFURLRef, // iconURL CFURLRef, // soundURL CFURLRef, // localizationURL CFStringRef, // alertHeader CFStringRef, // alertMessage CFStringRef // defaultButtonTitle ); /* https://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFTypeRef/#//apple_ref/c/func/CFRelease * void CFRelease ( * CFTypeRef cf * ); */ var CFRelease = libcf.declare('CFRelease', ctypes.default_abi, VOID, // return CFTypeRef // cf ); /* https://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFStringRef/#//apple_ref/c/func/CFStringCreateWithCharacters * CFStringRef CFStringCreateWithCha...
Plug-in Development Overview - Plugins
owser calls the plug-in to inform it that the stream was created and to push more data. In streams produced by the plug-in, by contrast, the plug-in calls Netscape functions to create a stream, push data into it, and delete it. Working with URLs The Plug-in API provides methods that plug-ins can use to retrieve data from or post data to a URL anywhere on the network, provide hyperlinks to other documents, post form data to CGI scripts using HTTP, or upload files to a remote server using FTP. Use NPN_GetURL to request the browser to load a URL into a particular browser window or frame for display, or to deliver the data of that URL to the plug-in instance in a new stream. The NPN_GetURLNotify function operates like NPN_GetURL, except that it notifies the plug-in of the result when the operati...
...articular browser window or frame for display, or delivered to the plug-in instance in a new stream. The NPN_PostURLNotify function operates like NPN_PostURL, except that it notifies the plug-in of the result when the operation completes. For information about using these methods, see URLs. Starting in Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7), you can get the origin of the document in a secure, convenient way by calling NPN_GetValue() to retrieve the value of the variable NPNVdocumentOrigin. The returned value is the Unicode serialization of the document's origin converted to NFKC-encoded (that is, normalized) UTF-8. Your plug-in must free the returned string's memory by calling NPN_MemFree() when you're done with it. Getting Version and UI Information The Netscape group ...
...d 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 && thePlugin.advanceToNextSong) thePlugin.advanceToNextSong(); else alert("Plugin not installed correctly"); </script> In the past, LiveConnect and later XPConnect were used to make plug-ins scriptable. See the Wikipedia article for historical information. Both technologies are now obsolete for the purposes of plug-in scriptability, and th...
Scripting plugins - Plugins
(A bit of history: NPAPI plugins that used to take advantage of being scriptable via LiveConnect in 4.x Netscape browsers lost this possibility in Mozilla (due to the JNI making the Netscape 4.x JRI obsolete). ...
... (A bit of history: NPAPI plugins that used to take advantage of being scriptable via LiveConnect in 4.x Netscape browsers lost this possibility in Mozilla (due to the JNI making the Netscape 4.x JRI obsolete). ...
...working with reference counted NPObjects, the caller is responsible for calling NPN_ReleaseObject on the NPObject to drop the reference. ...
URLs - Plugins
es. nntp (USENET news using nntp access) Locates USENET news groups or individual USENET articles; alternate to news. prospero (Prospero Directory Service) Locates a resource on a Prospero directory server. telnet (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_U...
...L, NPN_GetURLNotify, and NPP_URLNotify functions. This section describes the methods and procedures used for getting the URL and displaying the page. The plug-in uses the NPN_GetURL function to ask the browser to display data retrieved from a URL in a specified target window or frame, or deliver it to the plug-in instance in a new stream. This is the way that plug-ins provide hyperlinks to other documents or retrieve data from the network. If the browser cannot locate the URL and retrieve the data, it does not create a stream for the instance; in this case, the plug-in receives notification of the result. To request a stream and receive notification of the result in all cases, use NPN_GetURLNotify. For HTTP URLs, the browser resolves NPN_GetURL as the HTTP server method GET, which requests URL ...
...target, even though, when used with a mailto or news URL, this creates an extra blank browser instance. _self or _current: Load the URL into the same window the plug-in instance occupies. If this target refers to the window or frame containing the instance, the instance is destroyed and the plug-in may be unloaded. _parent: Load the URL into the immediate FRAMESET parent of the plug-in instance document. If the plug-in instance document has no parent, the default is _self. _top: Load the URL into the plug-in instance window. The default is _self, if the plug-in instance document is already at the top. Use for breaking out of a deep frame nesting. Be careful when you assign a target. If the target refers to the window or frame containing the instance or one of its parents/ancestors, the instan...
Web Console Helpers - Firefox Developer Tools
The commands The JavaScript command line provided by the Web Console offers a few built-in helper functions that make certain tasks easier. $(selector, element) Looks up a CSS selector string selector , returning the first node descended from element that matches. If unspecified, element defaults to document. Equivalent to document.querySelector() or calls the $ function in the page, if it exists. See the QuerySelector code snippet. $$(selector, element) Looks up a CSS selector string selector, returning an array of DOM nodes descended from element that match. If unspecified, element defaults to document. This is like for document.querySelectorAll(), but returns an array instead of a NodeList. $0 The currently-inspected element in the page. $_ Stores the result of the last expres...
...eList. $0 The currently-inspected element in the page. $_ Stores the result of the last expression executed in the console's command line. For example, if you type "2+2 <enter>", then "$_ <enter>", the console will print 4. $x(xpath, element, resultType) Evaluates the XPath xpath expression in the context of element and returns an array of matching nodes. If unspecified, element defaults to document. The resultType parameter specifies the type of result to return; it can be an XPathResult constant, or a corresponding string: "number", "string", "bool", "node", or "nodes"; if not provided, ANY_TYPE is used. :block (Starting in Firefox 80) Followed by an unquoted string, blocks requests where the URL contains that string. In the Network Monitor, the string now appears and is selected in the ...
...s where the URL contains that string. In the Network Monitor, the string now appears and is selected in the Request Blocking sidebar. Unblock with :unblock. cd() Switches JavaScript evaluation context to a different iframe in the page. This helper accepts multiple different ways of identifying the frame to switch to. You can supply any of the following: a selector string to be passed to document.querySelector to locate the iframe element the iframe element itself the content window inside the iframe See working with iframes. clear() Clears the console output area. clearHistory() Just like a normal command line, the console command line remembers the commands you've typed. Use this function to clear the console's command history. copy() Copies the argument to the clipboard...
Animation.startTime - Web APIs
An animation's start time is initially unresolved (meaning that it's null because it has no value). ...
...g the current time in milliseconds, or null if no time is set. You can read this value to determine what the start time is currently set at, and you can change this value to make the animation start at a different time. ...
..., and you can change this value to make the animation start at a different time. Examples In the Running on Web Animations API example, the we can sync all new animated cats by giving them all the same startTime as the original running cat: var catRunning = document.getElementById ("withWAAPI").animate(keyframes, timing); /* A function that makes new cats. ...
AudioBuffer.getChannelData() - Web APIs
ZE_ERR exception will be thrown. Return value A Float32Array. Example In the following example we create a two second buffer, fill it with white noise, and then play it via an AudioBufferSourceNode. The comments should clearly explain what is going on. You can also run the code live, or view the source. ...
...lue A Float32Array. Example In the following example we create a two second buffer, fill it with white noise, and then play it via an AudioBufferSourceNode. The comments should clearly explain what is going on. You can also run the code live, or view the source. ...
...wing example we create a two second buffer, fill it with white noise, and then play it via an AudioBufferSourceNode. The comments should clearly explain what is going on. You can also run the code live, or view the source. ...
AudioProcessingEvent - Web APIs
scriptNode.onaudioprocess function takes the associated audioProcessingEvent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...ssociated audioProcessingEvent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...op through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
AudioTrackList: change event - Web APIs
The change event is fired when an audio track is enabled or disabled, for example by changing the track's enabled property. ...
... Cancelable No Interface Event Event handler property onchange Examples Using addEventListener(): const videoElement = document.querySelector('video'); videoElement.audioTracks.addEventListener('change', (event) => { console.log(`'${event.type}' event fired`); }); // changing the value of `enabled` will trigger the `change` event const toggleTrackButton = document.querySelector('.toggle-track'); toggleTrackButton.addEventListener('click', () => { const track = videoElement.audioTracks[0]; track.enabled = !track.enabled; }); Using the onchange event handler property: const videoElement = document.querySelector('video'); videoElement.audioTracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; // changing the value of `enabl...
... Living Standard ...
BaseAudioContext.createBufferSource() - Web APIs
oContext.createBufferSource(); Returns An AudioBufferSourceNode. Example In this example, we create a two second buffer, fill it with white noise, and then play it via an AudioBufferSourceNode. The comments should clearly explain what is going on. Note: You can also run the code live, or view the source. ...
...AudioBufferSourceNode. Example In this example, we create a two second buffer, fill it with white noise, and then play it via an AudioBufferSourceNode. The comments should clearly explain what is going on. Note: You can also run the code live, or view the source. ...
...le, we create a two second buffer, fill it with white noise, and then play it via an AudioBufferSourceNode. The comments should clearly explain what is going on. Note: You can also run the code live, or view the source. ...
BaseAudioContext.createScriptProcessor() - Web APIs
scriptNode.onaudioprocess function takes the associated audioProcessingEvent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...ssociated audioProcessingEvent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...op through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
BaseAudioContext.createStereoPanner() - Web APIs
nect() 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 output, respectively. ...
... 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 output, respectively. ...
...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 output, respectively. ...
BatteryManager.onlevelchange - Web APIs
is updated. Syntax navigator.battery.onlevelchange = funcRef Where battery is a BatteryManager object, and funcRef is a function to be called when the levelchange event occurs. ...
...r object, and funcRef is a function to be called when the levelchange event occurs. ...
...wn)</div> <div id="stateBaterry">(charging state unknown)</div> JavaScript navigator.getBattery().then(function(battery) { battery.onlevelchange = function(){ document.querySelector('#level').textContent = battery.level; if(battery.charging) { document.querySelector('#stateBaterry').textContent = "Charging time: " + (battery.chargingTime / 60); } else { document.querySelector('#stateBaterry').textContent = "Discharging time: " + (battery.dischargingTime / 60); } }; }); Specifications Specification Status Comment Battery Status API Candidate Recommendation Initial definition ...
Beacon API - Web APIs
requests use the HTTP POST method and requests typically do not require a response. Requests are guaranteed to be initiated before a page is unloaded and they are run to completion, without requiring a blocking request (for example XMLHttpRequest). Example use cases of the Beacon API are logging activity and sending analytics data to the server. ...
...equest (for example XMLHttpRequest). Example use cases of the Beacon API are logging activity and sending analytics data to the server. Example code of the interfaces described in this document is included in Using the Beacon API. Why use Beacon? The Beacon interface addresses the needs of analytics and diagnostics code that typically attempts to send data to a web server before unloading the document. Sending the data any sooner may result in a missed opportunity to gather data. However, ensuring that the data is sent during the unloading of a document is something that has traditionally been difficult for developers. User agents will typically ignore asynchronous XMLHttpRequests made in an unload handler. To solve this problem, analytics and diagnostics code will typically make a synchronou...
...There is nothing the next page can do to avoid this perception of poor page load performance. There are other techniques used to ensure that data is submitted. One such technique is to delay the unload to submit data by creating an Image element and setting its src attribute within the unload handler. ...
Body.json() - Web APIs
Web › API › Body › json
bject, an array, a string, a number... Example In our fetch json example (run fetch json live), we create a new request using the Request() constructor, then use it to fetch a .json file. When the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data. ...
...ful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data. const myList = document.querySelector('ul'); const myRequest = new Request('products.json'); fetch(myRequest) .then(response => response.json()) .then(data => { for (const product of data.products) { let listItem = document.createElement('li'); listItem.appendChild( document.createElement('strong') ).textContent = product.Name; listItem.append( ` can be found in ${ product.Location }. ...
...t) .then(response => response.json()) .then(data => { for (const product of data.products) { let listItem = document.createElement('li'); listItem.appendChild( document.createElement('strong') ).textContent = product.Name; listItem.append( ` can be found in ${ product.Location }. Cost: ` ); listItem.appendChild( document.createElement('strong') ).textContent = `GBP${product.Price}`; myList.appendChild(listItem); } }) .catch(console.error); Specifications Specification Status Comment FetchThe definition of 'Body.json()' in that specification. Living Standard Initial definition ...
CSSRule - Web APIs
Web › API › CSSRule
efore, which specialized interface it implements). The relationships between these constants and the interfaces are: Type Value Rule-specific interface Comments and examples CSSRule.STYLE_RULE 1 CSSStyleRule The most common kind of rule: selector { prop1: val1; prop2: val2; } CSSRule.IMPORT_RULE 3 CSSImportRule An @import rule. ...
...7 CSSKeyframesRule CSSRule.KEYFRAME_RULE 8 CSSKeyframeRule Reserved for future use 9 Should be used to define color profiles in the future CSSRule.NAMESPACE_RULE 10 CSSNamespaceRule CSSRule.COUNTER_STYLE_RULE 11 CSSCounterStyleRule CSSRule.SUPPORTS_RULE 12 CSSSupportsRule CSSRule.DOCUMENT_RULE 13 CSSDocumentRule CSSRule.FONT_FEATURE_VALUES_RULE 14 CSSFontFeatureValuesRule CSSRule.VIEWPORT_RULE 15 CSSViewportRule CSSRule.REGION_STYLE_RULE 16 CSSRegionStyleRule CSSRule.UNKNOWN_RULE 0 CSSUnknownRule CSSRule.CHARSET_RULE 2 CSSCharsetRule (Removed in most browsers.) ...
...n of 'CSSRule' in that specification. Working Draft Added value FONT_FEATURE_VALUES_RULE. CSS Counter Styles Level 3The definition of 'CSSRule' in that specification. Candidate Recommendation Added value COUNTER_STYLE_RULE. CSS Conditional Rules Module Level 3The definition of 'CSSRule' in that specification. Candidate Recommendation Added value SUPPORTS_RULE. (DOCUMENT_RULE has been pushed to CSS Conditional Rules Level 4) Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSRule' in that specification. Obsolete Initial definition. ...
CSSStyleDeclaration - Web APIs
The CSSStyleDeclaration interface represents an object that is a CSS declaration block, and exposes style information and various style-related methods and properties. A CSSStyleDeclaration object can be exposed using three different APIs: Via HTMLElement.style, which deals with the inline styles of a single element (e.g., <div style="...">). Via the CSSStyleSheet API. For example, document.styleSheets[0].cssRules[0].style returns a CSSStyleDeclaration object on the first CSS rule in the document's first stylesheet. Via Window.getComputedStyle(), which exposes the CSSStyleDeclaration object as a read-only interface. Attributes CSSStyleDeclaration.cssText Textual representation of the declaration block. Setting this attribute changes the style. CSSStyleDeclaration.lengthRead only Th...
....removeProperty() Removes a property from the CSS declaration block. CSSStyleDeclaration.setProperty() Modifies an existing CSS property or creates a new CSS property in the declaration block. CSSStyleDeclaration.getPropertyCSSValue() Only supported via getComputedStyle in Firefox. Returns the property value as a CSSPrimitiveValue or null for shorthand properties. Example var styleObj = document.styleSheets[0].cssRules[0].style; console.log(styleObj.cssText); for (var i = styleObj.length; i--;) { var nameString = styleObj[i]; styleObj.removeProperty(nameString); } console.log(styleObj.cssText); Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleDeclaration' in that specification. Working Draft Merged th...
... Obsolete Initial definition ...
CSSStyleSheet.ownerRule - Web APIs
The read-only CSSStyleSheet property ownerRule returns the CSSImportRule corresponding to the @import at-rule which imported the stylesheet into the document. If the stylesheet wasn't imported into the document using @import, the returned value is null. Syntax var ownerRule = cssStyleSheet.ownerRule; Value A CSSImportRule corresponding to the @import rule which imported the stylesheet into the document. If the stylesheet wasn't imported into the document using @import, the returned value is null. Examples This snippet of code looks for rules which were not imported into the document using an @import at-rule. ...
... value is null. Syntax var ownerRule = cssStyleSheet.ownerRule; Value A CSSImportRule corresponding to the @import rule which imported the stylesheet into the document. If the stylesheet wasn't imported into the document using @import, the returned value is null. Examples This snippet of code looks for rules which were not imported into the document using an @import at-rule. ...
...ue is null. Examples This snippet of code looks for rules which were not imported into the document using an @import at-rule. let ruleList = document.styleSheets[0].cssRules; for (let rule of ruleList) { if (!rule.ownerRule) { /* rule is not imported */ } } This snipped obtains a reference to the stylesheet associated with the @import and processes it in some manner: let ruleList = document.styleSheets[0].cssRules; for (let rule of ruleList) { if (rule.ownerRule) { checkStylesheet(rule.ownerRule.styleSheet); } } Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleSheet.ownerRule' in that specification. Working Draft ...
CanvasPattern.setTransform() - Web APIs
nsform method This is just a simple code snippet which uses the setTransform method to create a CanvasPattern with the specified pattern transformation from an SVGMatrix. The pattern gets applied if you set it as the current fillStyle and gets drawn onto the canvas when using the fillRect() method, for example. ...
...od to create a CanvasPattern with the specified pattern transformation from an SVGMatrix. The pattern gets applied if you set it as the current fillStyle and gets drawn onto the canvas when using the fillRect() method, for example. ...
...Reset" /> </div> <textarea id="code" class="playable-code" style="height:120px"> var img = new Image(); img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createPattern(img, 'repeat'); pattern.setTransform(matrix.rotate(-45).scale(1.5)); ctx.fillStyle = pattern; ctx.fillRect(0, 0, 400, 400); };</textarea> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var edit = document.getElementById('edit'); var code = textarea.value; var svg1 = document.getElementById('svg1'); var matrix = svg1.createSVGMatrix(); function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textare...
CanvasRenderingContext2D.createPattern() - Web APIs
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. ...
...tion() { 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. ...
...he pattern a width and height of 50 patternCanvas.width = 50; patternCanvas.height = 50; // Give the pattern a background color and draw an arc patternContext.fillStyle = '#fec'; patternContext.fillRect(0, 0, patternCanvas.width, patternCanvas.height); patternContext.arc(0, 0, 50, 0, .5 * Math.PI); patternContext.stroke(); // Create our primary canvas and fill it with the pattern const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const pattern = ctx.createPattern(patternCanvas, 'repeat'); ctx.fillStyle = pattern; ctx.fillRect(0, 0, canvas.width, canvas.height); // Add our primary canvas to the webpage document.body.appendChild(canvas); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasR...
CanvasRenderingContext2D.filter - Web APIs
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="display:none;"> <img i...
...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. ...
...ombine 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="display:none;"> <img id="source" src="https://udn.realityripple.com/samples/90/a34a525ace.jpg"> </div> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const image = document.getElementById('source'); image.addEventListener('load', e => { ctx.filter = 'contrast(1.4) sepia(1) drop-shadow(9px 9px 2px #e81)'; ctx.drawImage(image, 10, 10, 180, 120); }); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.filter' in that specification. Living Standard Initial definition. ...
CanvasRenderingContext2D.stroke() - Web APIs
ing 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, this may be the desired e...
...h() 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. ...
...ineTo(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. ...
Channel Messaging API - Web APIs
Note: This feature is available in Web Workers. Channel messaging concepts and usage A message channel is created using the MessageChannel() constructor. ...
... Note: This feature is available in Web Workers. Channel messaging concepts and usage A message channel is created using the MessageChannel() constructor. ...
...transferred, they are 'neutered' on the previous context -- the one they previously belonged to. For instance a port, when is sent, cannot be used anymore by the original context. The other browsing context can listen for the message using MessagePort.onmessage, and grab the contents of the message using the event's data attribute. You could then respond by sending a message back to the original document using MessagePort.postMessage. When you want to stop sending messages down the channel, you can invoke MessagePort.close to close the ports. Find out more about how to use this API in Using channel messaging. Channel messaging interfaces MessageChannel Creates a new message channel to send messages across. MessagePort Controls the ports on the message channel, allowing sending of message...
ContentIndex.getAll() - Web APIs
ach item returned is an Object containing the following data: id: A unique String identifier. title: A String title for the item. Used in user-visible lists of content. title: A String title of the item. Used in user-visible lists of content. description: A String description of the item. Used in user-visible lists of content. url: A String containing the url of the corresponding HTML document. Needs to be under the scope of the current service worker. category: Optional A String defining the category of content. Can be: '' An empty String, this is the default. homepage article video audio icons: Optional An Array of image resources, defined as an Object with the following data: src: A url String of the source image. sizes: Optional A Stri...
...ction that retrieves items within the content index and iterates over each entry, building a list for the interface. ...
...st() { // access our service worker registration const registration = await navigator.serviceWorker.ready; // get our index entries const entries = await registration.index.getAll(); // create a containing element const readingListElem = document.createElement('div'); // test for entries if (!Array.length) { // if there are no entries, display a message const message = document.createElement('p'); message.innerText = 'You currently have no articles saved for offline reading.' readingListElem.append(message); } else { // if entries are present, display in a list of links to the content const listElem = document.createElement('ul'); for (const entry of entries) { const listItem = document.createElement('li'); const anchorElem = docum...
Content Index API - Web APIs
scope of the current service worker. The browser can then use these entries to display offline reading to a user. As a developer you can also display these entries within your application. Indexed entries do not automatically expire. It's good practice to present an interface for clearing out entries, or periodically remove older entries. The API supports indexing URLs corresponding to HTML documents. A URL for a cached media file, for example, can't be indexed directly. Instead, you need to provide a URL for a page that displays media, and which works offline. Interfaces ContentIndex The ContentIndex interface provides functionality to register content available offline. ContentIndexEvent The ContentIndexEvent interface of the Content Index API defines the object used to repre...
...ction that retrieves items within the content index and iterates over each entry, building a list for the interface. ...
...st() { // access our service worker registration const registration = await navigator.serviceWorker.ready; // get our index entries const entries = await registration.index.getAll(); // create a containing element const readingListElem = document.createElement('div'); // test for entries if (!Array.length) { // if there are no entries, display a message const message = document.createElement('p'); message.innerText = 'You currently have no articles saved for offline reading.' readingListElem.append(message); } else { // if entries are present, display in a list of links to the content const listElem = document.createElement('ul'); for (const entry of entries) { const listItem = document.createElement('li'); const anchorElem = docum...
DOMHighResTimeStamp - Web APIs
double-precision floating-point number which describes the number of milliseconds (accurate to within 5 microseconds if the device supports it) elapsed between two points in time. The starting time can be either a specific time determined by the script for a site or app, or the time origin. ...
...en two points in time. The starting time can be either a specific time determined by the script for a site or app, or the time origin. The time origin The time origin is a standard time which is considered to be the beginning of the current document's lifetime. It's calculated like this: If the script's global object is a Window, the time origin is determined as follows: If the current Document is the first one loaded in the Window, the time origin is the time at which the browser context was created. If during the process of unloading the previous document which was loaded in the window, a confirmation dialog was displayed to let the user confirm whether or not to leave the previous page, the time origin is the time at which the user confirmed that navigating to the new page was acc...
...nt which was loaded in the window, a confirmation dialog was displayed to let the user confirm whether or not to leave the previous page, the time origin is the time at which the user confirmed that navigating to the new page was acceptable. If neither of the above determines the time origin, then the time origin is the time at which the navigation responsible for creating the window's current Document took place. If the script's global object is a WorkerGlobalScope (that is, the script is running as a web worker), the time origin is the moment at which the worker was created. In all other cases, the time origin is undefined. Methods This type has no methods. Usage notes You can get the current timestamp value--the time that has elapsed since the context was created--by calling the ...
DOMImplementation.hasFeature() - Web APIs
entation.hasFeature() method returns a Boolean flag indicating if a given feature is supported. It is deprecated and modern browsers return true in all cases. The different implementations fairly diverged in what kind of features were reported. The latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use. Syntax const flag = document.implementation.hasFeature(feature, version); Parameters feature A DOMString representing the feature name. version A DOMString representing the version of the specification defining the feature. Specifications Specification Status Comment DOMThe definition of 'DOMImplementation.hasFeature' in that specification. Living Standard Modified to always return...
...ion); Parameters feature A DOMString representing the feature name. version A DOMString representing the version of the specification defining the feature. Specifications Specification Status Comment DOMThe definition of 'DOMImplementation.hasFeature' in that specification. Living Standard Modified to always return true except for SVG features. ...
...ature. Specifications Specification Status Comment DOMThe definition of 'DOMImplementation.hasFeature' in that specification. Living Standard Modified to always return true except for SVG features. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'DOMImplementation.hasFeature' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'DOMImplementation.hasFeature' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification Document Object Model (DOM) Level 1 SpecificationThe definition of 'DOMImplementation.hasFeature' in that specification. Obsol...
DOMMatrixReadOnly.scale() - Web APIs
e: At time of writing, Firefox still supports an older version of the specification that accepts either one or three values. DOMMatrix.scale(scale[, originX][, originY]) We'll show an example of how you can deal with the cross-browser support implications of 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 s...
... Candidate R...
... Candidate Recommendation Initial definition ...
Locating DOM elements using selectors - Web APIs
lectors API provides methods that make it quick and easy to retrieve Element nodes from the DOM by matching against a set of selectors. This is much faster than past techniques, wherein it was necessary to, for example, use a loop in JavaScript code to locate the specific items you needed to find. 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. If no matching node is found, null is returned. querySelectorAll() Returns a NodeList containing all matching Element nodes within the node's subtree, or an empty NodeList if no matches are found. Note: The NodeList returned by querySelectorAll() is not live, which ...
...) Returns a NodeList containing all matching Element nodes within the node's subtree, or an empty NodeList if no matches are found. Note: The NodeList returned by querySelectorAll() is not live, which means that changes in the DOM are not reflected in the collection. This is different from other DOM querying methods that return live node lists. ...
...e node lists. You may find examples and details by reading the documentation for the Element.querySelector() and Element.querySelectorAll() methods, as well as in the article Code snippets for querySelector. Selectors The selector methods accept one or more comma-separated selectors to determine what element or elements should be returned. For example, to select all paragraph (p) elements in a document whose CSS class is either warning or note, you can do the following: var special = document.querySelectorAll( "p.warning, p.note" ); You can also query by ID. For example: var el = document.querySelector( "#main, #basic, #exclamation" ); After executing the above code, el contains the first element in the document whose ID is one of main, basic, or exclamation. You may use any CSS selectors ...
EffectTiming.fill - Web APIs
Web › API › EffectTiming › fill
e element should be in before the animation begins and after it ends, and so forth. Here we specify that the animation should take 2000 milliseconds (2 seconds) to complete, should only run once, and that the fill mode should be "none". As defined above, the "none" fill mode means that the element will be rendered in its natural, unaltered condition anytime the animation isn't actively running. ...
...th. Here we specify that the animation should take 2000 milliseconds (2 seconds) to complete, should only run once, and that the fill mode should be "none". As defined above, the "none" fill mode means that the element will be rendered in its natural, unaltered condition anytime the animation isn't actively running. document.getElementById("animateButton").addEventListener("click", event => { document.getElementById("box").animate( boxRotationKeyframes, boxRotationTiming ); }, false); The rest of the code is pretty simple: it adds an event listener to the "Animate" button so that when it's clicked by the user, the box is animated by calling Element.animate() on it, providing the boxRotationKeyframes and boxRotationTiming objects to describe the animation that should occur. Result ...
...When used to persist the effect of an animation indefinitely, however, they have a number of drawbacks: The forwards fill of an animation (or backwards fill if the animation is playing in reverse) will continue to override any changes to speci...
Element.closest() - Web APIs
Web › API › Element › closest
Will return itself or the matching ancestor. If no such element exists, it returns null. Syntax var closestElement = targetElement.closest(selectors); Parameters selectors is a DOMString containing a selector list. ex: p:hover, .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. ...
...urn 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. ...
...nodeType === 1); return null; }; } However, if you really do require IE 8 support, then the following polyfill will do the job very slowly, but eventually. However, it will only support CSS 2.1 selectors in IE 8, and it can cause severe lag spikes in production websites. if (window.Element && !Element.prototype.closest) { Element.prototype.closest = function(s) { var matches = (this.document || this.ownerDocument).querySelectorAll(s), i, el = this; do { i = matches.length; while (--i >= 0 && matches.item(i) !== el) {}; } while ((i < 0) && (el = el.parentElement)); return el; }; } Specifications Specification Status Comment DOMThe definition of 'Element.closest()' in that specification. Living Standard Init...
Element.hasAttribute() - Web APIs
The Element.hasAttribute() method returns a Boolean value indicating whether the specified element has the specified attribute or not. Syntax var result = element.hasAttribute(name); result holds the return value true or false. name is a string representing the name of the attribute. ...
...tAttributeNS setAttributeNode setAttributeNodeNS getAttribute (DOM 1) getAttributeNS getAttributeNode getAttributeNodeNS hasAttribute (DOM 2) hasAttributeNS - - removeAttribute (DOM 1) removeAttributeNS removeAttributeNode - Specifications Specification Status Comment DOMThe definition of 'Element.hasAttribute()' in that specification. ...
...tributeNode getAttributeNodeNS hasAttribute (DOM 2) hasAttributeNS - - removeAttribute (DOM 1) removeAttributeNS removeAttributeNode - Specifications Specification Status Comment DOMThe definition of 'Element.hasAttribute()' in that specification. Living Standard From Document Object Model (DOM) Level 3 Core Specification, moved from Node to Element Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Element.hasAttribute()' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Element.hasAttribute()' in that specification. Obsolete Initial definition. ...
Element.id - Web APIs
Web › API › Element › id
Note: Identifiers are case-sensitive, but you should avoid creating IDs that differ only in the capitalization. Syntax var idStr = element.id; // Get the id element.id = idStr; // Set the id idStr is the identifier of the element. ...
... Note: Identifiers are case-sensitive, but you should avoid creating IDs that differ only in the capitalization. Syntax var idStr = element.id; // Get the id element.id = idStr; // Set the id idStr is the identifier of the element. ...
... Note: Identifiers are case-sensitive, but you should avoid creating IDs that differ only in the capitalization. Syntax var idStr = element.id; // Get the id element.id = idStr; // Set the id idStr is the identifier of the element. Specifications Specification Status Comment DOMThe definition of 'id' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'id' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'id' in that specification. Obsolete Initial definition. ...
Element.localName - Web APIs
Web › API › Element › localName
Syntax name = element.localName Return value A DOMString representing the local part of the element's qualified name. ...
... A DOMString representing the local part of the element's qualified name. ...
... width="100px" height="100px" viewBox="0 0 100 100"> <svg:circle cx="50" cy="50" r="30" style="fill:#aaa" id="circle"/> </svg:svg> <textarea id="text" rows="4" cols="55"/> </body> </html> Notes The local name of a node is that part of the node'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 documents. For example, in the qualified name ecomm:partners, partners is the local name and ecomm is the prefix: <ecomm:business id="soda_shop" type="brick_n_mortar" xmlns:ecomm="http://example.com/ecomm"> <ecomm:partners> <ecomm:partner id="1001">Tony's Syrup Warehouse </ecomm:partner> </ecomm:partner> </ecomm:business> Note: In Gecko 1.9.2 and earlier, the property returns the upper-cas...
Element.querySelector() - Web APIs
will occur. The first element found which matches this group of selectors is returned. Return value The first descendant element of baseElement which matches the specified group of selectors. The entire hierarchy of elements is considered when matching, including those outside the set of elements including baseElement and its descendants; in other words, selectors is first applied to the whole document, not the baseElement, to generate an initial list of potential elements. The resulting elements are then examined to see if they are descendants of baseElement. The first match of those remaining elements is returned by the querySelector() method. If no matches are found, the returned value is null. Exceptions SyntaxError The specified selectors are invalid. Examples Let's consider a few...
...ose remaining elements is returned by the querySelector() method. If no matches are found, the returned value is null. Exceptions SyntaxError The specified selectors are invalid. Examples Let's consider a few examples. Find a specific element with specific values of an attribute In this first example, the first <style> element which either has no type or has type "text/css" in the HTML document body is returned: var el = document.body.querySelector("style[type='text/css'], style:not([type])"); The entire hierarchy 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 paragrap...
...rates 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 examples See Document.querySelec...
Element.tagName - Web APIs
Web › API › Element › tagName
The tagName read-only property of the Element interface returns the tag name of the element on which it's called. For example, if the element is an <img>, its tagName property is "IMG" (for HTML documents; it may be cased differently for XML/XHTML documents). Syntax elementName = Element.tagName; Value A string indicating the element's tag name. This string's capitalization depends on the document type: For DOM trees which represent HTML documents, the returned tag name is always in the canonical upper-case form. For example, tagName called on a <div> element returns "DIV". ...
...ng the element's tag name. This string's capitalization depends on the document type: For DOM trees which represent HTML documents, the returned tag name is always in the canonical upper-case form. For example, tagName called on a <div> element returns "DIV". The tag names 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. ...
...OM 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 DOMThe definition...
Element.toggleAttribute() - Web APIs
he Element interface toggles a Boolean attribute (removing it if it is present and adding it if it is not present) on the given element. Syntax Element.toggleAttribute(name [, force]); Parameters name A DOMString specifying the name of the attribute to be toggled. The attribute name is automatically converted to all lower-case when toggleAttribute() is called on an HTML element in an HTML document. force Optional A boolean value to determine whether the attribute should be added or removed, no matter whether the attribute is present or not at the moment. Return 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 t...
...te 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>. ...
...wise. 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>. ...
Event.defaultPrevented - Web APIs
as not. Example This example logs attempts to visit links from two <a> elements. JavaScript is used to prevent the second link from working. ...
... Living Standard ...
... Living Standard ...
Event.eventPhase - Web APIs
Web › API › Event › eventPhase
t phase constants. Constants Event phase constants These values describe which phase the event flow is currently being evaluated. Constant Value Description Event.NONE 0 No event is being processed at this time. Event.CAPTURING_PHASE 1 The event is being propagated through the target's ancestor objects. This process starts with the Window, then Document, then the HTMLHtmlElement, and so on through the elements until the target's parent is reached. Event listeners registered for capture mode when EventTarget.addEventListener() was called are triggered during this phase. Event.AT_TARGET 2 The event has arrived at the event's target. Event listeners registered for this phase are called at this time. If Event.bubbles is false, process...
... 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() { for (let i = 0; i < divs.length; i++) { let d = divs[i] if (d.id != "divInfo") { d.removeEventListener("click", OnDivCli...
... Obsolete Initial definition ...
Event.initEvent() - Web APIs
Web › API › Event › initEvent
This method must be called to set the event before it is dispatched, using EventTarget.dispatchEvent(). Once dispatched, it doesn't do anything anymore. Do not use this method anymore as it is deprecated. Instead use specific event constructors, like Event(). The page on Creating and triggering events gives more information about the way to use these. Syntax event.initEvent(type, bubbles, cancelable); type Is a DOMString defining the type of event. ...
...ype Is a DOMString defining the type of event. bubbles Is a Boolean deciding whether the event should bubble up through the event chain or not. Once set, the read-only property Event.bubbles will give its value. cancelable Is a Boolean defining whether the event can be canceled. Once set, the read-only property Event.cancelable will give its value. Example // Create the event. var event = document.createEvent('Event'); // Create a click event that bubbles up and // cannot be canceled event.initEvent('click', true, false); // Listen for the event. elem.addEventListener('click', function (e) { // e.target matches elem }, false); elem.dispatchEvent(event); Specifications Specification Status Comment DOMThe definition of 'Event.initEvent()' in that specificatio...
...ate a click event that bubbles up and // cannot be canceled event.initEvent('click', true, false); // Listen for the event. elem.addEventListener('click', function (e) { // e.target matches elem }, false); elem.dispatchEvent(event); Specifications Specification Status Comment DOMThe definition of 'Event.initEvent()' in that specification. Living Standard From Document Object Model (DOM) Level 2 Events Specification, deprecated it, superseded by event constructors. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'Event.initEvent()' in that specification. Obsolete Initial definition. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the dat...
EventSource: message event - Web APIs
through an event source. Bubbles No Cancelable No Interface MessageEvent Event handler property EventSource.onmessage Examples In this basic example, an EventSource is created to receive events from the server; a page with the name sse.php is responsible for generating the events. ...
...MessageEvent Event handler property EventSource.onmessage Examples In this basic example, an EventSource is created to receive events from the server; a page with the name sse.php is responsible for generating the events. ...
...e.php is responsible for generating the events. var evtSource = new EventSource('sse.php'); var eventList = document.querySelector('ul'); evtSource.addEventListener('message', (e) => { var newElement = document.createElement("li"); newElement.textContent = "message: " + e.data; eventList.appendChild(newElement); }); onmessage equivalent evtSource.onmessage = (e) => { var newElement = document.createElement("li"); newElement.textContent = "message: " + e.data; eventList.appendChild(newElement); }; Specifications Specification Status HTML Living StandardThe definition of 'message event' in that specification. Living Standard ...
EventTarget - Web APIs
For example XMLHttpRequest, AudioNode, AudioContext, and others. Many event targets (including elements, documents, and windows) also support setting event handlers via onevent properties and attributes. ...
... EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them. Element, Document, and Window are the most common event targets, but other objects can be event targets, too. For example XMLHttpRequest, AudioNode, AudioContext, and others. Many event targets (including elements, documents, and windows) also support setting event handlers via onevent properties and attributes. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/EventTarget" target="_top"><rect x=...
...nt.type in this.listeners)) { return true; } var stack = this.listeners[event.type].slice(); for (var i = 0, l = stack.length; i < l; i++) { stack[i].call(this, event); } return !event.defaultPrevented; }; Specifications Specification Status Comment DOMThe definition of 'EventTarget' in that specification. Living Standard No change. Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'EventTarget' in that specification. Obsolete A few parameters are now optional (listener), or accepts the null value (useCapture). Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'EventTarget' in that specification. Obsolete Initial definition. ...
Using Fetch - Web APIs
ders: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch((error) => { console.error('Error:', error); }); Uploading a file Files can be uploaded using an HTML <input type="file" /> input element, FormData() and fetch(). ...
...//example.com/profile/avatar', { method: 'PUT', body: formData }) .then(response => response.json()) .then(result => { console.log('Success:', result); }) .catch(error => { console.error('Error:', error); }); Uploading multiple files Files can be uploaded using an HTML <input type="file" multiple /> input element, FormData() and fetch(). ...
...ta The Body mixin defines the following methods to extract a body (implemented by both Request and Response). These all return a promise that is eventually resolved with the actual content. arrayBuffer() blob() json() text() formData() This makes usage of non-textual data much easier than it was with XHR. Request bodies can be set by passing body parameters: const form = new FormData(document.getElementById('login-form')); fetch('/login', { method: 'POST', body: form }); Both request and response (and by extension the fetch() function), will try to intelligently determine the content type. A request will also automatically set a Content-Type header if none is set in the dictionary. Feature detection Fetch API support can be detected by checking for the existence of Headers, Re...
File.webkitRelativePath - Web APIs
y 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. ...
...r 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. ...
...ierarchies is generated and displayed. HTML content <input type="file" id="filepicker" name="fileList" webkitdirectory multiple /> <ul id="listing"></ul> JavaScript content document.getElementById("filepicker").addEventListener("change", function(event) { let output = document.getElementById("listing"); let files = event.target.files; for (let i=0; i<files.length; i++) { let item = document.createElement("li"); item.innerHTML = files[i].webkitRelativePath; output.appendChild(item); }; }, false); Result Specifications Specification Status Comment File and Directory Entries APIThe definition of 'webkitRelativePath' in that specification. Draft Initial specification. This API has no official W3C or WHATWG specification. Browser ...
FileReader.readAsDataURL() - Web APIs
ng 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. ...
...he Base64 encoded string, first remove data:*/*;base64, from the result. Syntax instanceOfFileReader.readAsDataURL(blob); Parameters blob The Blob or File from which to read. ...
...der(); 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 image = new Image(); image.height = 100; ...
FileSystemDirectoryEntry - Web APIs
by calling getDirectory(). If you want to create subdirectories, create each child directory in sequence. If you try creating a directory using a full path that includes parent directories that do not exist yet, an error is returned. So create the hierarchy by recursively adding a new path after creating the parent directory. ...
...ding a new path after creating the parent directory. Example In the following code snippet, we create a directory called "Documents." // Taking care of the browser-specific prefixes. window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.directoryEntry = window.directoryEntry || window.webkitDirectoryEntry; ... ...
...er-specific prefixes. window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.directoryEntry = window.directoryEntry || window.webkitDirectoryEntry; ... function onFs(fs){ fs.root.getDirectory('Documents', {create:true}, function(directoryEntry){ //directoryEntry.isFile === false //directoryEntry.isDirectory === true //directoryEntry.name === 'Documents' //directoryEntry.fullPath === '/Documents' }, onError); } // Opening a file system with temporary storage window.requestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, onFs, onError); Properties This interface has no properties of its own, but inherits properties from its parent interface, FileSystemEntry. Methods This interface inherits methods from its parent interface, FileSystemEn...
FileSystemEntry.toURL() - Web APIs
L([mimeType]); Parameters mimeType Optional An optional string specifying the MIME type to use when interpreting the file. This can be used to help deal with files whose types aren't recognized automatically by the user agent. If this parameter is omitted, the user agent uses its standard algorithms to identify the file. Return value A DOMString containing a URL that can then be used as a document reference in HTML content, or an empty string if the URL can't be generated (such as if the file system implementation doesn't support toURL()). Example If you have a FileSystemFileEntry corresponding to an image file in a file system available to your Web site or app, you can call toURL() to get its URL for use in HTML. If your site is located at http://my-awesome-website.woot, and you have a ...
... URL for use in HTML. If your site is located at http://my-awesome-website.woot, and you have a temporary file system that contains an image file named awesomesauce.jpg, the URL returned by toURL() might be (depending on the browser's implementation) something like "filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg". ...
...-website.woot, and you have a temporary file system that contains an image file named awesomesauce.jpg, the URL returned by toURL() might be (depending on the browser's implementation) something like "filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg". Code that makes use of this might look like this: let img = document.createElement("img"); img.src = imageFileEntry.toURL(); document.body.appendChild(img); Assuming the scenario mentioned before the code, the result would be HTML that looks like this being appended to the end of the document: <img src="filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg"> 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 h...
FullscreenOptions.navigationUI - Web APIs
be allocated to the display of the element. "show" The browser will present page navigation controls and possibly other user interface; the dimensions of the element (and the perceived size of the screen) will be clamped to leave room for this user interface. "auto" The browser will choose which of the above settings to apply. This is the default value. ...
...page navigation controls and possibly other user interface; the dimensions of the element (and the perceived size of the screen) will be clamped to leave room for this user interface. "auto" The browser will choose which of the above settings to apply. This is the default value. Example In this example, the entire document is placed into full-screen mode by calling requestFullscreen() on the document's Document.documentElement, which is the document's root <html> element. ...
... the perceived size of the screen) will be clamped to leave room for this user interface. "auto" The browser will choose which of the above settings to apply. This is the default value. Example In this example, the entire document is placed into full-screen mode by calling requestFullscreen() on the document's Document.documentElement, which is the document's root <html> element. let elem = document.documentElement; elem.requestFullscreen({ navigationUI: "show" }).then({}).catch(err => { alert(`An error occurred while trying to switch into full-screen mode: ${err.message} (${err.name})`); }); The promise's resolve handler does nothing, but if the promise is rejected, an error message is displayed by calling alert(). Specifications Specification Status Comment ...
GeolocationCoordinates.longitude - Web APIs
t 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. ...
...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. ...
...les 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. ...
Using the Geolocation API - Web APIs
titude and longitude. If sucessful, the available hyperlink is populated with an openstreetmap.org URL that will show their location. ...
...erlink is populated with an openstreetmap.org URL that will show their location. ...
...`; mapLink.textContent = `Latitude: ${latitude} ?, Longitude: ${longitude} ?`; } function error() { status.textContent = 'Unable to retrieve your location'; } if(!navigator.geolocation) { status.textContent = 'Geolocation is not supported by your browser'; } else { status.textContent = 'Locating...'; navigator.geolocation.getCurrentPosition(success, error); } } document.querySelector('#find-me').addEventListener('click', geoFindMe); Result ...
Geolocation API - Web APIs
titude and longitude. If sucessful, the available hyperlink is populated with an openstreetmap.org URL that will show their location. ...
...erlink is populated with an openstreetmap.org URL that will show their location. ...
...`; mapLink.textContent = `Latitude: ${latitude} ?, Longitude: ${longitude} ?`; } function error() { status.textContent = 'Unable to retrieve your location'; } if(!navigator.geolocation) { status.textContent = 'Geolocation is not supported by your browser'; } else { status.textContent = 'Locating...'; navigator.geolocation.getCurrentPosition(success, error); } } document.querySelector('#find-me').addEventListener('click', geoFindMe); Result Specifications Specification Status Comment Geolocation API Recommendation ...
GlobalEventHandlers.ondragend - Web APIs
ransfer.setData("text", ev.target.id); } function dragover_handler(ev) { console.log("dragOver"); // Change the target element's border to signify a drag over event // has occurred ev.currentTarget.style.background = "lightblue"; ev.preventDefault(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragenter_handler(ev) { console.log("dragEnter"); // Change the source element's background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's border back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { con...
...background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's border back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragEnd"); // Change the target element's background color to visually indicate // the drag ended. ...
...color to visually indicate // the drag ended. ...
GlobalEventHandlers.ondragenter - Web APIs
ransfer.setData("text", ev.target.id); } function dragover_handler(ev) { console.log("dragOver"); // Change the target element's border to signify a drag over event // has occurred ev.currentTarget.style.background = "lightblue"; ev.preventDefault(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragenter_handler(ev) { console.log("dragEnter"); // Change the source element's background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's border back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { con...
...background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's border back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragEnd"); // Change the target element's background color to visually indicate // the drag ended. ...
...color to visually indicate // the drag ended. ...
GlobalEventHandlers.ondragexit - Web APIs
ransfer.setData("text", ev.target.id); } function dragover_handler(ev) { console.log("dragOver"); // Change the target element's border to signify a drag over event // has occurred ev.currentTarget.style.background = "lightblue"; ev.preventDefault(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragenter_handler(ev) { console.log("dragEnter"); // Change the source element's background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's border back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { con...
...background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's border back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragEnd"); // Change the target element's background color to visually indicate // the drag ended. ...
...color to visually indicate // the drag ended. ...
GlobalEventHandlers.ondragleave - Web APIs
tData("text", ev.target.id); } function dragover_handler(ev) { console.log("dragOver"); // Change the target element's background color to signify a drag over event // has occurred ev.currentTarget.style.background = "lightblue"; ev.preventDefault(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragenter_handler(ev) { console.log("dragEnter"); // Change the source element's background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's background color back to white ev.currentTarget.style.background = "white"; } function dragend_handler(...
... color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's background color back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragEnd"); // Change the target element's background color to visually indicate // the drag ended. ...
...isually indicate // the drag ended. ...
GlobalEventHandlers.onkeypress - Web APIs
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. HTML <input> <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. HTML <label>Enter numbers only: <input> </label> JavaScript function numbersOnly(event) { return e...
... 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. HTML <label>Enter numbers only: <input> </label> JavaScript function numbersOnly(event) { return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode)); } const input = document.querySelector('input'); input.onkeypress = numbersOnly; // Prevent pasting (since pasted content might include non-number characters) input.onpaste = event => false; Result Capture the typing of a hidden word The following JavaScript function will do something after the user types the word "exit" in any point of a page. /* Type the word "exit" in any point of your page... */ (function () ...
...pasted content might include non-number characters) input.onpaste = event => false; Result Capture the typing of a hidden word The following JavaScript function will do something after the user types the word "exit" in any point of a page. /* Type the word "exit" in any point of your page... ...
GlobalEventHandlers.onmousedown - Web APIs
Living Standard ...
... Living Standard ...
... Living Standard ...
GlobalEventHandlers.onmouseup - Web APIs
Living Standard ...
... Living Standard ...
... Living Standard ...
HTMLAnchorElement - Web APIs
mark ('#'), if any, in the referenced URL. HTMLHyperlinkElementUtils.host Is a USVString representing the hostname and port (if it's not the default port) in the referenced URL. HTMLHyperlinkElementUtils.hostname Is a USVString representing the hostname in the referenced URL. HTMLHyperlinkElementUtils.href Is a USVString that is the result of parsing the href HTML attribute relative to the document, containing a valid URL of a linked resource. HTMLAnchorElement.hreflang Is a DOMString that reflects the hreflang HTML attribute, indicating the language of the linked resource. HTMLAnchorElement.media Is a DOMString that reflects the media HTML attribute, indicating the intended media for the linked resource. HTMLHyperlinkElementUtils.password Is a USVString containing the password specif...
...ject. HTMLAnchorElement.relList Read only Returns a DOMTokenList that reflects the rel HTML attribute, as a list of tokens. HTMLHyperlinkElementUtils.search Is a USVString representing the search element, including leading question mark ('?'), if any, of the referenced URL. HTMLElement.tabindex Is a long containing the position of the element in the tabbing navigation order for the current document. HTMLAnchorElement.target Is a DOMString that reflects the target HTML attribute, indicating where to display the linked resource. HTMLAnchorElement.text Is a DOMString being a synonym for the Node.textContent property. HTMLAnchorElement.type Is a DOMString that reflects the type HTML attribute, indicating the MIME type of the linked resource. HTMLHyperlinkElementUtils.username Is a USVSt...
...HTMLAnchorElement' in that specification. Recommendation The methods blur() and focus(), as well as the properties tabindex and accessKey, are now defined on HTMLElement. The following properties are now obsolete: charset, coords, name, rev, and shape. The following properties have been added: hash, host, hostname, media, pathname, port, protocol, relList, search, and text. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLAnchorElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLAnchorElement' in that specification. Obsolete Initial definition. ...
HTMLBaseElement - Web APIs
This object inherits all of the properties and methods as described in the HTMLElement interface. ...
...family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLBaseElement</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits properties from its parent, HTMLElement. HTMLBaseElement.href Is a DOMString that reflects the href HTML attribute, containing a base URL for relative URLs in the document. HTMLBaseElement.target Is a DOMString that reflects the target HTML attribute, containing a default target browsing context or frame for elements that do not have a target reference specified. Methods No specific method; inherits attributes from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLBaseEleme...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLBaseElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLBaseElement' in that specification. Recommendation No change from HTML5 HTML5The definition of 'HTMLBaseElement' in that specification. Recommendation No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLBaseElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLBaseElement' in that specification. Obsolete Initial definitio...
HTMLButtonElement - Web APIs
perties from its parent, HTMLElement. HTMLButtonElement.accessKey Is a DOMString indicating the single-character keyboard key to give access to the button. HTMLButtonElement.autofocus Is a Boolean indicating whether or not the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form-associated element in a document can have this attribute specified. HTMLButtonElement.disabled Is a Boolean indicating whether or not the control is disabled, meaning that it does not accept any clicks. HTMLButtonElement.form Read only Is a HTMLFormElement reflecting the form that this button is associated with. If the button is a descendant of a form element, then this attribute is the ID of that form element. If the butt...
... control is disabled, meaning that it does not accept any clicks. HTMLButtonElement.form Read only Is a HTMLFormElement reflecting the form that this button is associated with. If the button is a descendant of a form element, then this attribute is the ID of that form element. If the button 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. HTMLButtonElement.formAction Is a DOMString reflecting the URI of a resource that processes information submitted by the button. If specified, this attribute overrides the action attribute of the <form> element that owns this element. HTMLButtonElement.formEnctype Is a DOMString reflecting the type of content that is used to submit the form...
...ecommendation The attributes tabindex and accesskey, are now defined on HTMLElement. The following attributes have been added: autofocus, formAction, formEnctype, formMethod, formNoValidate, formTarget, labels, validity, validationMessage, and willValidate. The following methods have been added: checkValidity(), setCustomValidity(). The type attribute is no more read-only. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLButtonElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLButtonElement' in that specification. Obsolete Initial definition. ...
HTMLCanvasElement.mozGetAsFile() - Web APIs
anvas" width="100" height="100"></canvas> <p><a href="#" id="link">Click here to try out mozGetAsFile()</a>.</p> JavaScript The following code uses mozGetAsFile() to create a File object from the canvas and appends it as an image to the page by loading it as a data URL using the readAsDataURL() method. Then a new <img> element is created using the new data URL. ...
...e to the page by loading it as a data URL using the readAsDataURL() method. Then a new <img> element is created using the new data URL. ...
...ed using the new data URL. function draw() { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.fillStyle = 'rgb(200, 0, 0)'; ctx.fillRect(10, 10, 55, 50); ctx.fillStyle = 'rgba(0, 0, 200, 0.5)'; ctx.fillRect(30, 30, 55, 50); var link = document.getElementById('link'); link.addEventListener('click', copy); } function copy() { var canvas = document.getElementById('canvas'); var f = canvas.mozGetAsFile('test.png'); var reader = new FileReader(); reader.readAsDataURL(f); reader.onloadend = function() { var newImg = document.createElement('img'); newImg.src = reader.result; document.body.appendChild(newImg); } } window.addEventListener('load', draw); Specifications Not part of any specification. ...
HTMLCanvasElement.toDataURL() - Web APIs
ge/jpeg and image/webp. If this argument is anything else, the default value for image quality is used. The default value is 0.92. Other arguments are ignored. Return value A DOMString containing the requested data URI. ...
...the requested data URI. Exceptions SecurityError The canvas's bitmap is not origin clean; at least some of its contents have or may have been loaded from a site other than the one from which the document itself was loaded. ...
...HTML <img class="grayscale" src="myPicture.png" alt="Description of my picture" /> JavaScript window.addEventListener('load', removeColors); function showColorImg() { this.style.display = 'none'; this.nextSibling.style.display = 'inline'; } function showGrayImg() { this.previousSibling.style.display = 'inline'; this.style.display = 'none'; } function removeColors() { var aImages = document.getElementsByClassName('grayscale'), nImgsLen = aImages.length, oCanvas = document.createElement('canvas'), oCtx = oCanvas.getContext('2d'); for (var nWidth, nHeight, oImgData, oGrayImg, nPixel, aPix, nPixLen, nImgId = 0; nImgId < nImgsLen; nImgId++) { oColorImg = aImages[nImgId]; nWidth = oColorImg.offsetWidth; nHeight = oColorImg.offsetHeight; oCanvas.width =...
HTMLDialogElement: cancel event - Web APIs
wser's UI. ...
...ble Yes Interface Event Event handler oncancel Examples Live example HTML <dialog class="example-dialog"> <button class="close" type="reset">Close</button> </dialog> <button class="open-dialog">Open dialog</button> <div class="result"></div> CSS button, div { margin: .5rem; } JS const result = document.querySelector('.result'); const dialog = document.querySelector('.example-dialog'); dialog.addEventListener('cancel', (event) => { result.textContent = 'dialog was canceled'; }); const openDialog = document.querySelector('.open-dialog'); openDialog.addEventListener('click', () => { if (typeof dialog.showModal === 'function') { dialog.showModal(); result.textContent = ''; } else { result.textContent = 'The dialog API is ...
... Living Standard ...
HTMLDialogElement: close event - Web APIs
ed. ...
...No Interface Event Event handler property onclose Examples Live example HTML <dialog class="example-dialog"> <button class="close" type="reset">Close</button> </dialog> <button class="open-dialog">Open dialog</button> <div class="result"></div> CSS button, div { margin: .5rem; } JS const result = document.querySelector('.result'); const dialog = document.querySelector('.example-dialog'); dialog.addEventListener('close', (event) => { result.textContent = 'dialog was closed'; }); const openDialog = document.querySelector('.open-dialog'); openDialog.addEventListener('click', () => { if (typeof dialog.showModal === 'function') { dialog.showModal(); result.textContent = ''; } else { result.textContent = 'The dialog API is no...
... Living Standard ...
HTMLElement: animationcancel event - Web APIs
EventListener(). Bubbles Yes Cancelable No Interface AnimationEvent Event handler property onanimationcancel Examples This code gets an element that's currently being animated and adds a listener to the animationcancel event. It then sets the element's display property to none, which will trigger the animationcancel event. ...
...oncancel event. It then sets the element's display property to none, which will trigger the animationcancel event. ...
...iner { height: 3rem; } .event-log { width: 25rem; height: 2rem; border: 1px solid black; margin: 0.2rem; padding: 0.2rem; } .animation.active { animation-duration: 2s; animation-name: slidein; animation-iteration-count: 2; } @keyframes slidein { from { transform: translateX(100%) scaleX(3); } to { transform: translateX(0) scaleX(1); } } JS const animation = document.querySelector('p.animation'); const animationEventLog = document.querySelector('.animation-example>.event-log'); const applyAnimation = document.querySelector('.animation-example>button.activate'); let iterationCount = 0; animation.addEventListener('animationstart', () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `; }); animation.addEventListener('...
HTMLElement: animationend event - Web APIs
tion, such as if the element is removed from the DOM or the animation is removed from the element, the animationend event is not fired. ...
... AnimationEvent Event handler property onanimationend Examples This example gets an element that's being animated and listens for the animationend event: const animated = document.querySelector('.animated'); animated.addEventListener('animationend', () => { console.log('Animation ended'); }); The same, but using the onanimationend event handler property: const animated = document.querySelector('.animated'); animated.onanimationend = () => { console.log('Animation ended'); }; Live example HTML <div class="animation-example"> <div class="container"> <p class="animation">You chose a cold night to visit our planet.</p> </div> <button class="activate" type="button">Activate animation</button> <div class="event-log"></div> </div> CSS .container ...
....container { height: 3rem; } .event-log { width: 25rem; height: 2rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .animation.active { animation-duration: 2s; animation-name: slidein; animation-iteration-count: 2; } @keyframes slidein { from { margin-left: 100%; width: 300%; } to { margin-left: 0%; width: 100%; } } JS const animation = document.querySelector('p.animation'); const animationEventLog = document.querySelector('.animation-example>.event-log'); const applyAnimation = document.querySelector('.animation-example>button.activate'); let iterationCount = 0; animation.addEventListener('animationstart', () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `; }); animation.addEventListener('...
HTMLElement: animationiteration event - Web APIs
ime as the animationend event, and therefore does not occur for animations with an animation-iteration-count of one. ...
...nimationiteration to keep track of the number of iterations an animation has completed: const animated = document.querySelector('.animated'); let iterationCount = 0; animated.addEventListener('animationiteration', () => { iterationCount++; console.log(`Animation iteration count: ${iterationCount}`); }); The same, but using the onanimationiteration event handler property: const animated = document.querySelector('.animated'); let iterationCount = 0; animated.onanimationiteration = () => { iterationCount++; console.log(`Animation iteration count: ${iterationCount}`); }; Live example HTML <div class="animation-example"> <div class="container"> <p class="animation">You chose a cold night to visit our planet.</p> </div> <button class="activate" type="button">Activat...
...iner { height: 3rem; } .event-log { width: 25rem; height: 2rem; border: 1px solid black; margin: 0.2rem; padding: 0.2rem; } .animation.active { animation-duration: 2s; animation-name: slidein; animation-iteration-count: 2; } @keyframes slidein { from { transform: translateX(100%) scaleX(3); } to { transform: translateX(0) scaleX(1); } } JS const animation = document.querySelector('p.animation'); const animationEventLog = document.querySelector('.animation-example>.event-log'); const applyAnimation = document.querySelector('.animation-example>button.activate'); let iterationCount = 0; animation.addEventListener('animationstart', () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `; }); animation.addEventListener('...
HTMLElement: animationstart event - Web APIs
apsedTime equal to the absolute value of the delay (and, correspondingly, the animation will begin playing at that time index into the sequence). ...
...le No Interface AnimationEvent Event handler property onanimationstart Examples This listens for the animationstart event and logs a message when it is fired: const animated = document.querySelector('.animated'); animated.addEventListener('animationstart', () => { console.log('Animation started'); }); The same, but using onanimationstart: const animated = document.querySelector('.animated'); animated.onanimationstart = () => { console.log('Animation started'); }; Live example HTML <div class="animation-example"> <div class="container"> <p class="animation">You chose a cold night to visit our planet.</p> </div> <button class="activate" type="button">Activate animation</button> <div class="event-log"></div> </div> CSS .conta...
...iner { height: 3rem; } .event-log { width: 25rem; height: 2rem; border: 1px solid black; margin: 0.2rem; padding: 0.2rem; } .animation.active { animation-duration: 2s; animation-name: slidein; animation-iteration-count: 2; } @keyframes slidein { from { transform: translateX(100%) scaleX(3); } to { transform: translateX(0) scaleX(1); } } JS const animation = document.querySelector('p.animation'); const animationEventLog = document.querySelector('.animation-example>.event-log'); const applyAnimation = document.querySelector('.animation-example>button.activate'); let iterationCount = 0; animation.addEventListener('animationstart', () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `; }); animation.addEventListener('...
HTMLElement: change event - Web APIs
Try entering something into the field below, and then clic...
...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"><...
...sult.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.lang - Web APIs
Web › API › HTMLElement › lang
This also only works with the lang attribute and not with xml:lang. ...
... This also only works with the lang attribute and not with xml:lang. ...
...odeReference.lang = NewLanguage; // Set new value for lang languageUsed is a string variable that gets the language in which the text of the current element is written. NewLanguage is a string variable with its value setting the language in which the text of the current element is written. Example // this snippet compares the base language and // redirects to another url based on language if (document.documentElement.lang === "en") { window.location.href = "Some_document.html.en"; } else if (document.documentElement.lang === "ru") { window.location.href = "Some_document.html.ru"; } Specification Specification Status Comment Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'lang' in that specification. Obsolete ...
HTMLHtmlElement - Web APIs
The HTMLHtmlElement interface serves as the root node for a given HTML document. This object inherits the properties and methods described in the HTMLElement interface. You can retrieve the HTMLHtmlElement object for a given document by reading the value of the document.documentElement property. <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" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,An...
...<text x="416" y="94" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLHtmlElement</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits properties from its parent, HTMLElement. HTMLHtmlElement.version Is a DOMString representing the version of the HTML Document Type Definition (DTD) that governs this document. This property should not be used any more as it is non-conforming. Simply omit it. Methods No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHtmlElement' in that specification. Living Standard HTML 5...
...HTML Living StandardThe definition of 'HTMLHtmlElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLHtmlElement' in that specification. Recommendation No change since the last snapshot HTML5The definition of 'HTMLHtmlElement' in that specification. Recommendation The version element has been removed, as it is non-conforming. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLHtmlElement' in that specification. Obsolete Reflecting the element change in HTML 4.01 Specification, the version property is now deprecated. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLHtmlElement' in that specification. Obsolete Initial definition ...
HTMLIFrameElement.referrerPolicy - Web APIs
rer header will be omitted entirely. No referrer information is sent along with requests. no-referrer-when-downgrade (default) This is the user agent's default behavior if no policy is specified. The URL is sent as a referrer when the protocol security level stays the same (HTTP->HTTP, HTTPS->HTTPS), but isn't sent to a less secure destination (HTTPS->HTTP). origin Only send the origin of the document as the referrer in all cases. The document https://example.com/page.html will send the referrer https://example.com/. origin-when-cross-origin Send a full URL when performing a same-origin request, but only send the origin of the document for other cases. same-origin A referrer will be sent for same-site origins, but cross-origin requests will contain no referrer information. strict-origin ...
... strict-origin-when-cross-origin Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS->HTTPS), and send no header to a less secure destination (HTTPS->HTTP). ...
...t, only send the origin when the protocol security level stays the same (HTTPS->HTTPS), and send no header to a less secure destination (HTTPS->HTTP). unsafe-url Send a full URL when performing a same-origin or cross-origin request. This policy will leak origins and paths from TLS-protected resources to insecure origins. Carefully consider the impact of this setting. Examples var iframe = document.createElement("iframe"); iframe.src = "/"; iframe.referrerPolicy = "unsafe-url"; var body = document.getElementsByTagName("body")[0]; body.appendChild(iframe); // Fetch the image using the complete URL as the referrer Specifications Specification Status Comment Referrer PolicyThe definition of 'referrerpolicy attribute' in that specification. Candidate Recommenda...
HTMLIFrameElement - Web APIs
n in the iframe's src attribute. The default value is src. HTMLIFrameElement.allowfullscreen Is a Boolean indicating whether the inline frame is willing to be placed into full screen mode. See Using full-screen mode for details. HTMLIFrameElement.allowPaymentRequest Is a Boolean indicating whether the Payment Request API may be invoked inside a cross-origin iframe. HTMLIFrameElement.contentDocument Read only Returns a Document, the active document in the inline frame's nested browsing context. HTMLIFrameElement.contentWindow Read only Returns a WindowProxy, the window proxy for the nested browsing context. HTMLIFrameElement.csp Specifies the Content Security Policy that an embedded document must agree to enforce upon itself. HTMLIFrameElement.frameBorder Is a DOMString that indic...
...frame margin. HTMLIFrameElement.marginWidth Is a DOMString being the width of the frame margin. HTMLIFrameElement.name Is a DOMString that reflects the name HTML attribute, containing a name by which to refer to the frame. HTMLIFrameElement.featurePolicy Read only Returns the FeaturePolicy interface which provides a simple API for introspecting the feature policies applied to a specific document. HTMLIFrameElement.referrerPolicy Is a DOMString that reflects the referrerpolicy HTML attribute indicating which referrer to use when fetching the linked resource. HTMLIFrameElement.sandbox Is a DOMSettableTokenList that reflects the sandbox HTML attribute, indicating extra restrictions on the behavior of the nested content. HTMLIFrameElement.scrolling Is a DOMString that indicates whe...
...that specification. Living Standard The following property has been added: allowFullscreen. HTML5The definition of 'HTMLIFrameElement' in that specification. Recommendation The following properties are now obsolete: scrolling, marginWidth, marginHeight, longDesc, frameBorder, and align. The following properties have been added: srcdoc, sandbox, and contentWindow. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLIFrameElement' in that specification. Obsolete The contentDocument property has been added. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLIFrameElement' in that specification. Obsolete Initial definition. ...
HTMLInputElement.stepDown() - Web APIs
Try it with 0, 5, -2, etc. */ input.stepDown(); }...
...Try it with 0, 5, -2, etc. */ input.stepDown(); } } CSS input:invalid { border: red solid 3px; } Result Note if you don't pass a parameter to the stepDown() method, it defaults to 1. A...
...Try it with 0, 5, -2, etc. ...
HTMLInputElement.stepUp() - Web APIs
Try it with 0 */ input.stepUp() } } CSS input:invalid { b...
...Try it with 0 */ input.stepUp() } } CSS input:invalid { border: red solid 3px; } Result Note if you don't pass a parameter to the stepUp method, it defaults to 1. Any other value is a multi...
...t blank: <input type="number" step="1" id="incrementer" min="0" max="25"> </label> </p> <input type="button" value="Increment" id="theButton"> JavaScript /* make the button call the function */ let button = document.getElementById('theButton') button.addEventListener('click', function() { steponup() }) function steponup() { let input = document.getElementById('theNumber') let val = document.getElementById('incrementer').value if (val) { /* increment with a parameter */ input.stepUp(val) } else { /* or without a parameter. Try it with 0 */ input.stepUp() } } CSS input:invalid { border: red solid 3px; } Result Note if you don't pass a parameter to the stepUp method, it defaults to 1. Any other value is a multiplier of the step attribute value, which in this ...
HTMLInputElement.webkitdirectory - Web APIs
or 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. ...
...r 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. ...
...ierarchies is generated and displayed. HTML content <input type="file" id="filepicker" name="fileList" webkitdirectory multiple /> <ul id="listing"></ul> JavaScript content document.getElementById("filepicker").addEventListener("change", function(event) { let output = document.getElementById("listing"); let files = event.target.files; for (let i=0; i<files.length; i++) { let item = document.createElement("li"); item.innerHTML = files[i].webkitRelativePath; output.appendChild(item); }; }, false); Result Specifications Specification Status Comment File and Directory Entries APIThe definition of 'webkitdirectory' in that specification. Draft Initial specification. This API has no official W3C or WHATWG specification. Browser com...
HTMLInputElement - Web APIs
indicating that the control is not available for interaction. The input values will not be submitted with the form. See also readonly autofocus Boolean: Returns / Sets the element's autofocus attribute, which specifies that a form control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form element in a document can have the autofocus attribute. It cannot be applied if the type attribute is set to hidden (that is, you cannot automatically set focus to a hidden control). required Boolean: Returns / Sets the element's required attribute, indicating that the user must fill in a value before submitting a form. value string: Returns / Sets the current value of the control. Note: If ...
...ns / Sets the element's height attribute, which defines the height of the image displayed for the button, if the value of type is image. src string: Returns / Sets the element's src attribute, which specifies a URI for the location of an image to display on the graphical submit button, if the value of type is image; otherwise it is ignored. width string: Returns / Sets the document's width attribute, which defines the width of the image displayed for the button, if the value of type is image. Properties that apply only to elements of type file accept string: Returns / Sets the element's accept attribute, containing comma-separated list of file types accepted by the server when type is file. allowdirs Boolean: Part of the non-standard Direct...
...mMethod, formNoValidate, formTarget, height, indeterminate, labels, list, max, min, multiple, pattern, placeholder, required, selectionDirection, selectionEnd, selectionStart, step, validationMessage, validity, valueAsDate, valueAsNumber, width, and willValidate. The following methods have been added: checkValidity(), setCustomValidity(), setSelectionRange(), stepUp(), and stepDown(). Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLInputElement' in that specification. Obsolete The size property is now an unsigned long. The type property must be entirely given in lowercase characters. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLInputElement' in that specification. Obsolete Initial definition. ...
HTMLMetaElement - Web APIs
It inherits all of the properties and methods described in the HTMLElement interface. ...
...seline="middle">HTMLMetaElement</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits properties from its parent, HTMLElement. Name Type Description content DOMString Gets or sets the value of meta-data property. httpEquiv DOMString Gets or sets the name of an HTTP response header to define for a document. name DOMString Gets or sets the name of a meta-data property to define for a document. scheme DOMString Gets or sets the name of a scheme used to interpret the value of a meta-data property. Methods No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardTh...
...Methods No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMetaElement' in that specification. Living Standard HTML5The definition of 'HTMLMetaElement' in that specification. Recommendation The following property is now obsolete: scheme. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLMetaElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLMetaElement' in that specification. Obsolete Initial definition. ...
HTMLObjectElement - Web APIs
either the applet's subclass, or the path to get to the class, including the class file itself. HTMLObjectElement.codeBase Is a DOMString that reflects the codebase HTML attribute, specifying the base path to use to resolve relative URIs. HTMLObjectElement.codeType Is a DOMString that reflects the codetype HTML attribute, specifying the content type of the data. HTMLObjectElement.contentDocument Read only Returns a Document representing the active document of the object element's nested browsing context, if any; otherwise null. HTMLObjectElement.contentWindow Read only Returns a WindowProxy representing the window proxy of the object element's nested browsing context, if any; otherwise null. HTMLObjectElement.data Returns a DOMString that reflects the data HTML attribute, specifyi...
... HTMLObjectElement.name Returns a DOMString that reflects the name HTML attribute, specifying the name of the browsing context. HTMLObjectElement.standby Is a DOMString that reflects the standby HTML attribute, specifying a message to display while the object loads. HTMLObjectElement.tabindex Is a long representing the position of the element in the tabbing navigation order for the current document. HTMLObjectElement.type Is a DOMString that reflects the type HTML attribute, specifying the MIME type of the resource. HTMLObjectElement.typeMustMatch Is a Boolean that reflects the typemustmatch HTML attribute, indicating if the resource specified by data must only be played if it matches the type attribute. HTMLObjectElement.useMap Is a DOMString that reflects the usemap HTML attribute, ...
...property tabindex is now defined on HTMLElement. The following properties are now obsolete: align, archive, border, code, codeBase, codeType, declare, hspace, standby, and vspace. The following properties have been added: typeMustMatch, contentWindow, willValidate, validity, and validationMessage. The following methods have been added: checkValidity() and setCustomValidity(). Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLObjectElement' in that specification. Obsolete The contentDocument property has been added. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLObjectElement' in that specification. Obsolete Initial definition. ...
HTMLSelectElement.selectedOptions - Web APIs
<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. ...
... 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. ...
... 7 rows tall. Note also the <button>, whose role it is to trigger fetching the HTMLCollection of selected elements using the selected property. ...
HTMLStyleElement.media - Web APIs
The HTMLStyleElement.media property specifies the intended destination medium for style information. Syntax medium = style.media style.media = medium Parameters medium is a string describing a single medium or a comma-separated list. ...
...le.media = medium Parameters medium is a string describing a single medium or a comma-separated list. Example <!doctype html> <html> <head> <link id="LinkedStyle" rel="stylesheet" href="document.css" type="text/css" media="screen" /> <style id="InlineStyle" rel="stylesheet" type="text/css" media="screen, print"> p { color: blue; } </style> </head> <body> <script> alert('LinkedStyle: ' + document.getElementById('LinkedStyle').media); // 'screen' alert('InlineStyle: ' + document.getElementById('InlineStyle').media); // 'screen, print' </script> </body> </html> Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLStyleElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLStyleElement'...
.../body> </html> Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLStyleElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLStyleElement' in that specification. Recommendation HTML5The definition of 'HTMLStyleElement' in that specification. Recommendation Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLStyleElement' in that specification. Obsolete Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLStyleElement' in that specification. Obsolete Initial definition. ...
HTMLTableCellElement - Web APIs
The HTMLTableCellElement interface provides special properties and methods (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating the layout and presentation of table cells, either header or data cells, in an HTML document. <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" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monos...
...plied to them. This value is only allowed if the cell is in a row group. The empty string ("") The header cell has no predefined scope; the user agent will establish the scope based on contextual clues. Methods No specific method; inherits methods from its parent, HTMLElement. Deprecated properties Warning: These properties have been deprecated and should no longer be used. They are documented primarily to help understand older code bases. HTMLTableCellElement.align A DOMString containing an enumerated value reflecting the align attribute. It indicates the alignment of the element's contents with respect to the surrounding context. The possible values are "left", "right", and "center". HTMLTableCellElement.axis A DOMString containing a name grouping cells in virtual. It r...
...om HTML5. HTML5The definition of 'HTMLTableCellElement' in that specification. Recommendation The following properties have been obsoleted: align, axis, bgColor, height, width, ch, chOff, noWrap, and vAlign. The headers property is now read-only and contains a DOMSettableTokenList rather than a mere DOMString. The colspan and rowspan properties are now unsigned long. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLTableCellElement' in that specification. Obsolete The cellIndex property is now read-only. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLTableCellElement' in that specification. Obsolete Initial definition. ...
HTMLTitleElement - Web APIs
This element inherits all of the properties and methods of the HTMLElement interface. ...
...th="2px" /><text x="411" y="94" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLTitleElement</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits properties from its parent, HTMLElement. HTMLTitleElement.text Is a DOMString representing the text of the document's title. Methods No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTitleElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLTitleElement' in that specification. Recommendation No change from HTML5 HTML5The d...
...ecifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTitleElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLTitleElement' in that specification. Recommendation No change from HTML5 HTML5The definition of 'HTMLTitleElement' in that specification. Recommendation No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLTitleElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLTitleElement' in that specification. Obsolete Initial definit...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
the JSON string, then will presumably decode it and process the messages it finds in the resulting array. Examples Simple microtask example In this simple example, we see that enqueueing a microtask causes the microtask's callback to run after the body of this top-level script is done running. HTML <pre id="log"> </pre> JavaScript The code below is used to log the output. let logElem = document.getElementById("log"); let log = s => logElem.innerHTML += s + "<br>"; In the following code, we see a call to queueMicrotask() used to schedule a microtask to run. This call is bracketed by calls to log(), a custom function that simply outputs text to the screen. log("Before enqueueing the microtask"); queueMicrotask(() => { log("The microtask has run.") }); log("After enqueueing the microt...
...sult Timeout and microtask example In this example, a timeout is scheduled to fire after zero milliseconds (or "as soon as possible"). This demonstrates the difference between what "as soon as possible" means when scheduling a new task (such as by using setTimeout()) versus using a microtask. HTML <pre id="log"> </pre> JavaScript The code below is used to log the output. let logElem = document.getElementById("log"); let log = s => logElem.innerHTML += s + "<br>"; In the following code, we see a call to queueMicrotask() used to schedule a microtask to run. This call is bracketed by calls to log(), a custom function that simply outputs text to the screen. The code below schedules a timeout to occur in zero milliseconds, then enqueues a microtask. This is bracketed by calls to log() to...
... This example expands slightly on the previous one by adding a function that does some work. This function uses queueMicrotask() to schedule a microtask. The important thing to take away from this one is that the microtask isn't processed when the function exits, but when the main program exits. HTML <pre id="log"> </pre> JavaScript The code below is used to log the output. let logElem = document.getElementById("log"); let log = s => logElem.innerHTML += s + "<br>"; The main program code follows. The doWork() function here calls queueMicrotask(), yet the microtask still doesn't fire until the entire program exits, since that's when the task exits and there's nothing else on the execution stack. let callback = () => log("Regular timeout callback has run"); let urgentCallback = () => lo...
History.pushState() - Web APIs
Web › API › History › pushState
Syntax history.pushState(state, title[, url]) Parameters state 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 restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. ...
...o load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. ...
... relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. If this parameter isn't specified, it's set to the document's current URL. Description In a sense, calling pushState() is similar to setting window.location = "#foo", in that both will also create and activate another history entry associated with the current document. But pushState() has a few advantages: The new URL can be any URL in the same origin as the current URL. In contrast, setting window.location keeps you at the same document only if you modify only the hash. You don't have to change the URL if you don't want to. In contrast, setting window.location = "#foo"; only creates a new history entry if the current hash isn't #foo. You can associate ar...
IntersectionObserver - Web APIs
The ancestor element or viewport is referred to as the root. When an IntersectionObserver is created, it's configured to watch for given ratios of visibility within the root. ...
...gree of visibility; however, you can watch multiple target elements with the same observer. Constructor IntersectionObserver.IntersectionObserver() Creates a new IntersectionObserver object which will execute a specified callback function when it detects that a target element's visibility has crossed one or more thresholds. Properties IntersectionObserver.root Read only The Element or Document whose bounds are used as the bounding box when testing for intersection. If no root value was passed to the constructor or its value is null, the top-level document's viewport is used. IntersectionObserver.rootMargin Read only An offset rectangle applied to the root's bounding box when calculating intersections, effectively shrinking or growing the root for calculation purposes. The value retu...
...rsectionObserver to stop observing a particular target element. Examples var intersectionObserver = new IntersectionObserver(function(entries) { // If intersectionRatio is 0, the target is out of view // and we do not need to do anything. if (entries[0].intersectionRatio <= 0) return; loadItems(10); console.log('Loaded new items'); }); // start observing intersectionObserver.observe(document.querySelector('.scrollerFooter')); Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserver' in that specification. Working Draft ...
KeyboardEvent.code - Web APIs
Handle keyboard events in a game This example establishes an event listener for keydown events that handle keyboard input for a game that uses the typical "WASD" keybo...
... Handle keyboard events in a game This example establishes an event listener for keydown events that handle keyboard input for a game that uses the typical "WASD" keyboard layout for steering forward, left, backward, and right. This wi...
...current amount of rotation applied to the ship, in degrees; it starts at 0? (pointing straight up). Finally, spaceship is set to refer to the element with the ID "spaceship", which is the SVG polygon representing the ship the player controls. let shipSize = { width: 30, height: 30 }; let position = { x: 200, y: 200 }; let moveRate = 9; let turnRate = 5; let angle = 0; let spaceship = document.getElementById("spaceship"); Next comes the function updatePosition(). This function takes as input the distance the ship is to be moved, where positive is a forward movement and negative is a backward movement. This function computes the new position of the ship given the distance moved and the current direction the ship is facing. It also handles ensuring that the ship wraps across the bounda...
KeyboardEvent - Web APIs
a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as keyCode. Warning: This attribute is deprecated; you should use KeyboardEvent.key instead, if available. Events The following events are based on the KeyboardEvent type. They can be delivered to any object which implements GlobalEventHandlers, including Element, Document, and Window. In the list below, each event links to the documentation for the Document handler for the event, which applies generally to all of the recipients. keydown A key has been pressed. keyup A key has been released. Obsolete events keypress A key that normally produces a character value has been pressed. This event was highly device-dependent and is obsolete. You should not u...
...g an event does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself. Example <!DOCTYPE html> <html> <head> <script> 'use strict'; document.addEventListener('keydown', (event) => { const keyName = event.key; if (keyName === 'Control') { // do not alert when only Control key is pressed. return; } if (event.ctrlKey) { // Even though event.key is not 'Control' (e.g., 'a' is pressed), // event.ctrlKey may be true if Ctrl key is pressed at the same time. alert(`Combination of ctrlKey + ${keyName}`); } else ...
...me = event.key; if (keyName === 'Control') { // do not alert when only Control key is pressed. return; } if (event.ctrlKey) { // Even though event.key is not 'Control' (e.g., 'a' is pressed), // event.ctrlKey may be true if Ctrl key is pressed at the same time. alert(`Combination of ctrlKey + ${keyName}`); } else { alert(`Key pressed ${keyName}`); } }, false); document.addEventListener('keyup', (event) => { const keyName = event.key; // As the user releases the Ctrl key, the key is no longer active, // so event.ctrlKey is false. if (keyName === 'Control') { alert('Control key was released'); } }, false); </script> </head> <body> </body> </html> Specifications Specification Status Comment UI EventsThe definition of...
MathMLElement - Web APIs
The MathMLElement interface represents any MathML element. ...
... The MathMLElement interface represents any MathML element. ...
...ElementEventHandlers, 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 ...
MediaQueryList.addListener() - Web APIs
presenting the callback function you want to run when the media query status changes. In the original implementation, the callback was a non-standard MediaQueryListListener object. In the new implementation the standard event mechanism is used, the callback is a standard function, and the event object is a MediaQueryListEvent, which inherits from Event. Return value Void. ...
...ack is a standard function, and the event object is a MediaQueryListEvent, which inherits from Event. Return value Void. ...
... Working Draft Initial definition ...
MediaQueryListEvent.matches - Web APIs
The matches read-only property of the MediaQueryListEvent interface is a Boolean that returns true if the document currently matches the media query list, or false if not. Syntax var matches = MediaQueryListEvent.matches; Value A Boolean; returns true if the document currently matches the media query list, false if not. ...
...e if not. Syntax var matches = MediaQueryListEvent.matches; Value A Boolean; returns true if the document currently matches the media query list, false if not. ...
... Working Draft Initial definition ...
MediaQueryListEvent - Web APIs
are available as the event object on a function referenced by a MediaQueryList.onchange property or MediaQueryList.addListener() call. Constructor MediaQueryListEvent() Creates a new MediaQueryListEvent instance. Properties The MediaQueryListEvent interface inherits properties from its parent interface, Event. MediaQueryListEvent.matchesRead only A Boolean that returns true if the document currently matches the media query list, or false if not. MediaQueryListEvent.mediaRead only A DOMString representing a serialized media query. Methods The MediaQueryListEvent interface inherits methods from its parent interface, Event. Examples var mql = window.matchMedia('(max-width: 600px)'); function screenTest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less...
...aRead only A DOMString representing a serialized media query. Methods The MediaQueryListEvent interface inherits methods from its parent interface, Event. ...
... Working Draft Initial definition ...
MediaRecorder: dataavailable event - Web APIs
The MediaRecorder interface's dataavailable event is fired when the MediaRecorder delivers media data to your application for its use. Bubbles No Cancelable No Interface BlobEvent Event handler property ondataavailable For details of the all the possible reasons this event may raise, see the documentation for the event handler property: ondataavailable. ...
...roperty ondataavailable For details of the all the possible reasons this event may raise, see the documentation for the event handler property: ondataavailable. Examples Using addEventListener to listen for dataavailable events: ... var chunks = []; mediaRecorder.addEventListener('stop', (event) => { console.log("data available after MediaRecorder.stop() called."); var audio = document.createElement('audio'); audio.controls = true; var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audioURL = window.URL.createObjectURL(blob); audio.src = audioURL; console.log("recorder stopped"); }); mediaRecorder.addEventListener('dataavailable', (event) => { chunks.push(event.data); }); ... The same, but using the ondataavailable event handler property: ..
...ow.URL.createObjectURL(blob); audio.src = audioURL; console.log("recorder stopped"); }); mediaRecorder.addEventListener('dataavailable', (event) => { chunks.push(event.data); }); ... The same, but using the ondataavailable event handler property: ... var chunks = []; mediaRecorder.onstop = function(e) { console.log("data available after MediaRecorder.stop() called."); var audio = document.createElement('audio'); audio.controls = true; var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audioURL = window.URL.createObjectURL(blob); audio.src = audioURL; console.log("recorder stopped"); } mediaRecorder.ondataavailable = function(e) { chunks.push(e.data); } ... Specifications Specification Status MediaStream Recording Working...
msFirstPaint - 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. msFirstPaint is a read-only property which gets the time when the document loaded by the window object began to be displayed to the user. Put another way, msFirstPaint utilizes the browser to measure when the first content completes being painted in the window. It is available from javascript and can be reported from the field. This proprietary property is specific to Internet Explorer and Microsoft Edge. Syntax p = object.msFirstPaint; Value An Integer value that represents the time when the...
...to be displayed to the user. Put another way, msFirstPaint utilizes the browser to measure when the first content completes being painted in the window. It is available from javascript and can be reported from the field. This proprietary property is specific to Internet Explorer and Microsoft Edge. ...
...ay, msFirstPaint utilizes the browser to measure when the first content completes being painted in the window. It is available from javascript and can be reported from the field. This proprietary property is specific to Internet Explorer and Microsoft Edge. Syntax p = object.msFirstPaint; Value An Integer value that represents the time when the document began to be displayed or 0 if the document could not be loaded. The numerical value reported represents the number of milliseconds between the recorded time and midnight January 1, 1970 (UTC). This property is supported only for documents displayed in IE9 Standards mode. Example The following example shows how to calculate the time that is required to request the document before the document begins to display for the user. var oTim...
MutationEvent - Web APIs
Note: Mutation Events (W3C DOM Level 3 Events) have been deprecated in favor of Mutation Observers (W3C DOM4). Preface The mutation events have been marked as deprecated in the DOM Events specification, as the API's design is flawed (see details in the "DOM Mutation Events Replacement: The Story So Far / Existing Points of Consensus" post to public-webapps). Mutation Observers are the proposed replacement for mutation events in DOM4. They are expected to be included in Firefox 14 and Chrome 18. ...
... "DOM Mutation Events Replacement: The Story So Far / Existing Points of Consensus" post to public-webapps). Mutation Observers are the proposed replacement for mutation events in DOM4. They are expected to be included in Firefox 14 and Chrome 18. The practical reasons to avoid the mutation events are performance issues and cross-browser support. Performance Adding DOM mutation listeners to a document profoundly degrades the performance of further DOM modifications to that document (making them 1.5 - 7 times slower!). Moreover, removing the listeners does not reverse the damage. The performance effect is limited to the documents that have the mutation event listeners. Cross-browser support These events are not implemented consistently across different browsers, for example: IE prior to v...
... 9 didn't support the mutation events at all and does not implement some of them correctly in version 9 (for example, DOMNodeInserted) WebKit doesn't support DOMAttrModified (see webkit bug 8191 and the workaround) "mutation name events", i.e. DOMElementNameChanged and DOMAttributeNameChanged are not supported in Firefox (as of version 11), and probably in other browsers as well. ... Dottoro documents browser support for mutation events. Mutation events list The following is a list of all mutation events, as defined in DOM Level 3 Events specification: DOMAttrModified DOMAttributeNameChanged DOMCharacterDataModified DOMElementNameChanged DOMNodeInserted DOMNodeInsertedIntoDocument DOMNodeRemoved DOMNodeRemovedFromDocument DOMSubtreeModified Usage You can register a listener fo...
Node.isSameNode() - Web APIs
Web › API › Node › isSameNode
hen we run some JavaScript to compare the nodes using isSameNode() and output the results. ...
...ing isSameNode() and output the results. ...
... Obsolete Initial definition ...
Node.nextSibling - Web APIs
Web › API › Node › nextSibling
The Node.nextSibling read-only property returns the node immediately following the specified one in their parent's childNodes, or returns null if the specified node is the last child in the parent element. Syntax nextNode = node.nextSibling Notes Gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. Therefore a node obtained, for example, using Node.firstChild or Node.previousSibling may refer to a whitespace text node rather than the actual element the author intended to get. See Whitespace in the DOM and W3C DOM 3 FAQ: Why are some Text nodes empty? for more information. Element.nextElementSibling may be used to obtain the next element skipping any whitespace nodes, other between-element text, or comments. Example <div id="div-1">Here is...
... rather than the actual element the author intended to get. See Whitespace in the DOM and W3C DOM 3 FAQ: Why are some Text nodes empty? for more information. Element.nextElementSibling may be used to obtain the next element skipping any whitespace nodes, other between-element text, or comments. Example <div id="div-1">Here is div-1</div> <div id="div-2">Here is div-2</div> <script> var el = document.getElementById('div-1').nextSibling, i = 1; console.group('Siblings of div-1:'); while (el) { console.log(i, '. ', el.nodeName); el = el.nextSibling; i++; } console.groupEnd(); </script> /************************************************** The console displays the following: Siblings of div-1 1. #text 2. DIV 3. #text 4. SCRIPT ***********************...
....e. after the closing tag of an element and before the opening tag of the next). The possible inclusion of text nodes must be allowed for when traversing the DOM using nextSibling. See the resources in the Notes section. Specifications Specification Status Comment DOMThe definition of 'Node.nextSibling' in that specification. Living Standard No change Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Node.nextSibling' in that specification. Obsolete No change Document Object Model (DOM) Level 1 SpecificationThe definition of 'Node.nextSibling' in that specification. Obsolete Initial definition ...
Node.normalize() - Web APIs
Web › API › Node › normalize
The Node.normalize() method puts the specified node and all of its sub-tree into a "normalized" form. In a normalized sub-tree, no text nodes in the sub-tree are empty and there are no adjacent text nodes. ...
... The Node.normalize() method puts the specified node and all of its sub-tree into a "normalized" form. In a normalized sub-tree, no text nodes in the sub-tree are empty and there are no adjacent text nodes. ...
... The Node.normalize() method puts the specified node and all of its sub-tree into a "normalized" form. In a normalized sub-tree, no text nodes in the sub-tree are empty and there are no adjacent text nodes. ...
Node.previousSibling - Web APIs
The Node.previousSibling read-only property returns the node immediately preceding the specified one in its parent's childNodes list, or null if the specified node is the first in that list. Syntax previousNode = node.previousSibling; Example <img id="b0"> <img id="b1"> <img id="b2"> console.log(document.getElementById("b1").previousSibling); // <img id="b0"> console.log(document.getElementById("b2").previousSibling.id); // "b1" Notes Gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. Therefore a node obtained, for example, using Node.firstChild or Node.previousSibling may refer to a whitespace text node rather than the actual element the author intended to get. See Whitespace in the DOM and W3C DOM 3 FAQ: Why are some Text n...
... element the author intended to get. See Whitespace in the DOM and W3C DOM 3 FAQ: Why are some Text nodes empty? for more information. To navigate the opposite way through the child nodes list use Node.nextSibling. Specifications Specification Status Comment DOMThe definition of 'Node.previousSibling' in that specification. ...
...e opposite way through the child nodes list use Node.nextSibling. Specifications Specification Status Comment DOMThe definition of 'Node.previousSibling' in that specification. Living Standard No change Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.previousSibling' in that specification. Obsolete No change Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Node.previousSibling' in that specification. Obsolete No change Document Object Model (DOM) Level 1 SpecificationThe definition of 'Node.previousSibling' in that specification. Obsolete Initial definition ...
Node.replaceChild() - Web APIs
Web › API › Node › replaceChild
newChild The new node to replace oldChild. If it already exists in the DOM, it is first removed. oldChild The child to be replaced. Return value The returned value is the replaced node. This is the same node as oldChild. ...
...urned value is the replaced node. This is the same node as oldChild. Example // Given: // <div> // <span id="childSpan">foo bar</span> // </div> // Create an empty element node // without an ID, any attributes, or any content var sp1 = document.createElement("span"); // Give it an id attribute called 'newSpan' sp1.id = "newSpan"; // Create some content for the new element. ...
... any attributes, or any content var sp1 = document.createElement("span"); // Give it an id attribute called 'newSpan' sp1.id = "newSpan"; // Create some content for the new element. var sp1_content = document.createTextNode("new replacement span element."); // Apply that content to the new element sp1.appendChild(sp1_content); // Build a reference to the existing node to be replaced var sp2 = document.getElementById("childSpan"); var parentDiv = sp2.parentNode; // Replace existing node sp2 with the new span element sp1 parentDiv.replaceChild(sp1, sp2); // Result: // <div> // <span id="newSpan">new replacement span element.</span> // </div> Specifications Specification Status Comment DOMThe definition of 'Node: replaceChild' in that specification. Living St...
Node.textContent - Web APIs
Web › API › Node › textContent
perty of the Node interface represents the text content of the node and its descendants. Note: textContent and HTMLElement.innerText are easily confused, but the two properties are different in important ways. Syntax let text = someNode.textContent someOtherNode.textContent = string Value A string or null Description The value of textContent depends on the situation: If the node is a document or a Doctype, textContent returns null. Note: To get all of the text and CDATA data for the whole document, one could use document.documentElement.textContent. If the node is a CDATA section, comment, processing instruction, or text node, textContent returns the text inside the node, i.e., the Node.nodeValue. For other node types, textContent returns the concatenation of the textContent of...
...as its name indicates. Sometimes people use innerHTML to retrieve or write text inside an element, but textContent has better performance because its value is not parsed as HTML. Moreover, using textContent can prevent XSS attacks. Examples Given this HTML fragment: <div id="divA">This is <span>some</span> text!</div> ... ...
...e because its value is not parsed as HTML. Moreover, using textContent can prevent XSS attacks. Examples Given this HTML fragment: <div id="divA">This is <span>some</span> text!</div> ... you can use textContent to get the element's text content: let text = document.getElementById('divA').textContent; // The text variable is now: 'This is some text!' ... or set the element's text content: document.getElementById('divA').textContent = 'This text is different!'; // The HTML for divA is now: // <div id="divA">This text is different!</div> Specifications Specification Status Comment DOMThe definition of 'Node.textContent' in that specification. Living Standard ...
NodeIterator.detach() - Web APIs
thod is a no-op, kept for backward compatibility only. Originally, it detached the NodeIterator from the set over which it iterates, releasing any resources used by the set and setting the iterator's state to INVALID. Once this method had been called, calls to other methods on NodeIterator would raise the INVALID_STATE_ERR exception. ...
...d compatibility only. Originally, it detached the NodeIterator from the set over which it iterates, releasing any resources used by the set and setting the iterator's state to INVALID. Once this method had been called, calls to other methods on NodeIterator would raise the INVALID_STATE_ERR exception. Syntax nodeIterator.detach(); Example var nodeIterator = document.createNodeIterator( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); nodeIterator.detach(); // detaches the iterator nodeIterator.nextNode(); // throws an INVALID_STATE_ERR exception Specifications Specification Status Comment DOMThe definition of 'NodeIterator.detach' in that specification. Living Standard Tran...
... Obsolete Initial definition. ...
NodeIterator.nextNode() - Web APIs
Node() returns the first node in the set. This method returns null when there are no nodes left in the set. In old browsers, as specified in old versions of the specifications, the method may throws the INVALID_STATE_ERR DOMException if this method is called after the NodeIterator.detach()method. Recent browsers never throw. ...
...the set. This method returns null when there are no nodes left in the set. In old browsers, as specified in old versions of the specifications, the method may throws the INVALID_STATE_ERR DOMException if this method is called after the NodeIterator.detach()method. Recent browsers never throw. Syntax node = nodeIterator.nextNode(); Example var nodeIterator = document.createNodeIterator( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false // this optional argument is not used any more ); currentNode = nodeIterator.nextNode(); // returns the next node Specifications Specification Status Comment DOMThe definition of 'NodeIterator.nextNode' in that specification. Living Standard As det...
... Obsolete Initial definition. ...
NodeIterator.previousNode() - Web APIs
backwards within the set. This method returns null when the current node is the first node in the set. In old browsers, as specified in old versions of the specifications, the method may throws the INVALID_STATE_ERR DOMException if this method is called after the NodeIterator.detach()method. Recent browsers never throw. ...
...method returns null when the current node is the first node in the set. In old browsers, as specified in old versions of the specifications, the method may throws the INVALID_STATE_ERR DOMException if this method is called after the NodeIterator.detach()method. Recent browsers never throw. ...
... Obsolete Initial definition. ...
ParentNode.lastElementChild - Web APIs
at those that are children, they have been moved into two separate pure interfaces, ParentNode and ChildNode. In this case, lastElementChild moved to ParentNode. This is a fairly technical change that shouldn't affect compatibility. Syntax const element = node.lastElementChild Example <ul id="foo"> <li>First (1)</li> <li>Second (2)</li> <li>Third (3)</li> </ul> <script> const foo = document.getElementById('foo'); console.log(foo.lastElementChild.textContent); // logs: Third (3) </script> Polyfill The code below adds support of lastElementChild() to Document and DocumentFragment in Internet Explorer and Safari. // Overwrites native 'lastElementChild' prototype. // Returns array instead of HTMLCollection. ;(function(constructor) { if(constructor && constructor.prototype && ...
... ...
... ...
Path2D.addPath() - Web APIs
Web › API › Path2D › addPath
nal 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. ...
...reate 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(). ...
...path (which now contains both rectangles) using fill(). const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Create first path and add a rectangle let p1 = new Path2D(); p1.rect(0, 0, 100, 150); // Create second path and add a rectangle let p2 = new Path2D(); p2.rect(0, 0, 100, 75); // Create transformation matrix that moves 200 points to the right let m = document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGMatrix(); m.a = 1; m.b = 0; m.c = 0; m.d = 1; m.e = 200; m.f = 0; // Add second path to the first path p1.addPath(p2, m); // Draw the first path ctx.fill(p1); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'Path2D.addPath()' in that specification. Living Stand...
PaymentRequest.show() - Web APIs
r agent to begin the process of showing and handling the user interface for the payment request to the user. For security reasons, the PaymentRequest.show() method can't just be initiated at any time. It may only be called while handling events that represent user interactions, such as click, keyup, or the like. Only one payment request can be in the process of being handled at once, across all documents. Once one PaymentRequest's show() method has been called, any other call to show() will by rejected with an AbortError until the returned promise has been concluded, either by being fulfilled with a PaymentResponse indicating the results of the payment request, or by being rejected with an error. Note: In reality, despite the fact that the specification says this can't be done, some browsers, ...
... Return value A Promise that eventually resolves with a PaymentResponse. The promise is resolved when the user accepts the payment request (such as by clicking a "Pay" button in the browser's payment sheet). Exceptions AbortError The returned promise rejects with an AbortError if the user agent is already showing a payment panel. Only one payment panel may be visible at a time across all documents loaded by the user agent. The promise is also rejected with AbortError if the user cancels the payment request. InvalidStateError The promise rejects with an InvalidStateError if the same payment has already been shown for this request (its state is interactive because it is being shown already). NotSupportedError The promise rejects with a NotSupportedError if the user agent does not su...
... // Check if the the user supports the `methods` if (!await request.canMakePayment()) { return; // no, so use a web form instead. } // Let's update the total as the sheet is shown const updatedDetails = { total: { label: "Total", amount: { value: "20", currency: "AUD" }, }, }; const response = await request.show(updatedDetails); // Check response, etc... } document.getElementById("buyButton").onclick = requestPayment; Specifications Specification Status Comment Payment Request APIThe definition of 'show(optional detailsPromise)' in that specification. Candidate Recommendation Initial definition. ...
Using the Payment Request API - Web APIs
d. Detecting availability of the Payment Request API You can effectively detect support for the Payment Request API by checking if the user's browser supports PaymentRequest, i.e. if (window.PaymentRequest). In the following snippet, a merchant page performs this check, and if it returns true updates the checkout button to use PaymentRequest instead of legacy web forms. const checkoutButton = document.getElementById('checkout-button'); if (window.PaymentRequest) { let request = new PaymentRequest(buildSupportedPaymentMethodNames(), buildShoppingCartDetails()); checkoutButton.addEventListener('click', function() { request.show().then(function(paymentResponse) { // Handle successful payment }).catch(function(error) { // Handle cancelled or failed payment. For exampl...
... payment request button depending on whether users can make payments. In the following snippet we do just this -- depending on whether the user can make a fast payment or needs to add payment credentials first, the title of the checkout button changes between "Fast Checkout with W3C" and "Setup W3C Checkout". In both cases, the checkout button calls PaymentRequest.show(). ...
... the API (e.g., additional delivery instructions), the merchant can show a page with additional <input type="text"> fields after the checkout. request.show() .then(function(paymentResponse) { // Process payment here. // Close the UI: paymentResponse.complete('success').then(function() { // Request additional shipping address details. const additionalDetailsContainer = document.getElementById('additional-details-container'); additionalDetailsContainer.style.display = 'block'; window.scrollto(additionalDetailsContainer.getBoundingClientRect().x, 0); }).catch(function(error) { // Handle error. }); }) .catch(function(error) { // Handle error. }); Note: See our Show additional user interface after successful payment demo for the full c...
PerformanceNavigationTiming.domContentLoadedEventEnd - Web APIs
Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
...tEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM complete = " + p.domComplete); console.log("DOM interactive = " + p.domInteractive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Specifications Specification Status Comment Navigation Timing Level 2The...
PerformanceNavigationTiming.domContentLoadedEventStart - Web APIs
Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
....getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM complete = " + p.domComplete); console.log("DOM interactive = " + p.interactive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Specifications Specification Status Comment Navigation Timing Level 2The...
PerformanceNavigationTiming.loadEventEnd - Web APIs
Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
...tEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM complete = " + p.domComplete); console.log("DOM interactive = " + p.domInteractive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Specifications Specification Status Comment Navigation Timing Level 2The...
PerformanceNavigationTiming.loadEventStart - Web APIs
Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
....getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM complete = " + p.domComplete); console.log("DOM interactive = " + p.interactive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Specifications Specification Status Comment Navigation Timing Level 2The...
Pinch zoom gestures - Web APIs
ew Array(); var prevDiff = -1; Register event handlers Event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup. The handler for pointerup is used for the pointercancel, pointerout and pointerleave events since these four events have the same semantics in this application. function init() { // Install event handlers for the pointer target var el=document.getElementById("target"); el.onpointerdown = pointerdown_handler; el.onpointermove = pointermove_handler; // Use same handler for pointer{up,cancel,out,leave} events since // the semantics for these events - in this app - are the same. el.onpointerup = pointerup_handler; el.onpointercancel = pointerup_handler; el.onpointerout = pointerup_handler; el.onpointerleave = pointerup_handler; } ...
...vCache.splice(i, 1); break; } } } Event logging These functions are used to send event activity to the application's window (to support debugging and learning about the event flow). ...
...s function enableLog(ev) { logEvents = logEvents ? ...
RTCDataChannel: message event - Web APIs
ent handler property onmessage Note: The message event uses as its event object type the MessageEvent interface defined by the HTML specification. Examples For a given RTCDataChannel, dc, created for a peer connection using its createDataChannel() method, this code sets up a handler for incoming messages and acts on them by adding the data contained within the message to the current document as a new <p> (paragraph) element. dc.addEventListener("message", ev => { let newParagraph = document.createElement("p"); let textNode = document.createTextNode(event.data); newParagraph.appendChild(textNode); document.body.appendChild(newParagraph); }, false); Lines 2-4 create the new paragraph element and add the message data to it as a new text node. Line 6 appends the new paragraph...
...graph) element. dc.addEventListener("message", ev => { let newParagraph = document.createElement("p"); let textNode = document.createTextNode(event.data); newParagraph.appendChild(textNode); document.body.appendChild(newParagraph); }, false); Lines 2-4 create the new paragraph element and add the message data to it as a new text node. Line 6 appends the new paragraph to the end of the document's body. ...
...aragraph.appendChild(textNode); document.body.appendChild(newParagraph); }, false); Lines 2-4 create the new paragraph element and add the message data to it as a new text node. Line 6 appends the new paragraph to the end of the document's body. You can also use an RTCDataChannel object's onmessage event handler property to set the event handler: dc.onmessage = ev => { let newParagraph = document.createElement("p"); let textNode = document.createTextNode(event.data); newParagraph.appendChild(textNode); document.body.appendChild(newParagraph); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'the <code>message</code> event' in that specification. Candidate Recommendation ...
Range.commonAncestorContainer - Web APIs
This means that if Range.startContainer and Range.endContainer both refer to the same node, this node is the common ancestor container. Since a Range need not be continuous, and may also partially select nodes, this is a convenient way to find a Node which encloses a Range. This property is read-only. To change the ancestor container of a Node, consider using the various methods available to set the start and end positions of the Range, such as Range.setStart() and Range.setEnd(). ...
... </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. ...
... Obsolete Initial specification. ...
Range.compareNode() - Web APIs
Web › API › Range › compareNode
Node is completely selected by the Range. Warning: This method has been removed from Gecko 1.9 (Firefox 3) and will not exist in future versions of Firefox, which was the only browser implementing it; you should switch to Range.compareBoundaryPoints() as soon as possible. ...
... Specifications This method is not standard and therefore not part of any specification. ...
...ndaryPoints(Range.END_TO_END, nodeRange) == -1; if (nodeIsBefore && !nodeIsAfter) return 0; if (!nodeIsBefore && nodeIsAfter) return 1; if (nodeIsBefore && nodeIsAfter) return 2; return 3; } Syntax returnValue = range.compareNode( referenceNode ); Parameters referenceNode The Node to compare with the Range. Example range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); returnValue = range.compareNode(document.getElementsByTagName("p").item(0)); Notes This method is obsolete; you should use the W3C DOM Range.compareBoundaryPoints() method. Specifications This method is not standard and therefore not part of any specification. ...
Range.setEnd() - Web APIs
Web › API › Range › setEnd
Syntax range.setEnd(endNode, endOffset); Parameters endNode The Node inside which the Range should end. endOffset An integer greater than or equal to zero representing the offset for the end of the Range from the start of endNode. Return value undefined. ...
... IndexSizeError The value specified by endOffset is either greater than or equal to the length of the node or is less than zero. Usage notes If the endNode is a Node of type Text, Comment, or CDataSection, then endOffset is the number of characters from the start of endNode. For other Node types, endOffset is the number of child nodes between the start of the endNode. Example const range = document.createRange(); const endNode = document.getElementsByTagName('p').item(3); const endOffset = endNode.childNodes.length; range.setEnd(endNode, endOffset); setEnd() is commonly used in conjunction with setStart() to fully configure a range. Specifications Specification Status Comment DOMThe definition of 'Range.setEnd()' in that specification. Living Standard No ...
... Obsolete Initial specification. ...
Response.redirected - Web APIs
ted request is as simple as checking this flag on the Response object. In the code below, a textual message is inserted into an element when a redirect occurred during the fetch operation. Note, however, that this isn't as safe as outright rejecting redirects if they're unexpected, as described under Disallowing redirects below. ...
...nexpected, as described under Disallowing redirects below. ...
... Living Standard Initial definition ...
SVGElement - Web APIs
These can also be defined in SVG using attributes of the form data-*, where * is the key nam...
...ead only An SVGSVGElement referring to the nearest ancestor <svg> element. null if the given element is the outermost <svg> element. SVGElement.viewportElementRead only The SVGElement, which established the current viewport. Often, the nearest ancestor <svg> element. null if the given element is the outermost <svg> element. Methods This interface has no methods, but inherits methods from: DocumentAndElementEventHandlers, Element, ElementCSSInlineStyle, GlobalEventHandlers, HTMLOrForeignElement, SVGElementInstance Events Listen to these events using addEventListener() or by assigning an event listener to the equivalent on... handler property defined on GlobalEventHandlers or WindowEventHandlers. abort Fired when page loading is stopped before an SVG element has been allowed to load co...
...loading is stopped before an SVG element has been allowed to load completely. Also available via the onabort property. error Fired when an SVG element does not load properly or when an error occurs during script execution. Also available via the onerror property. load Fires on an SVGElement when it is loaded in the browser. Also available via the onload property. resize Fired when an SVG document is being resized. Also available via the onresize property. scroll Fired when an SVG document view is being shifted along the X and/or Y axes. Also available via the onscroll property. unload Fired when the DOM implementation removes an SVG document from a window or frame. Also available via the onunload property. Specifications Specification Status Comment Scala...
SVGGraphicsElement: paste event - Web APIs
d a "paste" action through the browser's user interface. Bubbles Yes Cancelable Yes Interface ClipboardEvent Event handler property onpaste If the cursor is in an editable context (for example, in a <textarea> or an element with contenteditable attribute set to true) then the default action is to insert the contents of the clipboard into the document at the cursor position. A handler for this event can access the clipboard contents by calling getData() on the event's clipboardData property. To override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventDefault(), and then insert its desired data manually. It's poss...
...by calling getData() on the event's clipboardData property. To override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventDefault(), and then insert its desired data manually. It's possible to construct and dispatch a synthetic paste event, but this will not affect the document's contents. Example HTML <?xml version="1.0" encoding="UTF-8"?> <svg viewBox="0 0 140 30" width="600" height="320" xmlns="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>...
... ...
ScriptProcessorNode.bufferSize - Web APIs
scriptNode.onaudioprocess function takes the associated audioProcessingEvent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...ssociated audioProcessingEvent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...op through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
ScriptProcessorNode.onaudioprocess - Web APIs
scriptNode.onaudioprocess function takes the associated audioProcessingEvent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...ssociated audioProcessingEvent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...op through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
ScriptProcessorNode - Web APIs
scriptNode.onaudioprocess function takes the associated audioProcessingEvent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...ssociated audioProcessingEvent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...op through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
Selection.addRange() - Web APIs
ers 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. ...
...her browsers will not add new ranges to the selection if it already contains one. ...
... Working Draft Current ...
Selection API - Web APIs
The Selection API provides functionality for reading and manipulating the range of text selected by the user. Concepts and usage To retrieve the current text range the user has selected, you can use the Window.getSelection() or Document.getSelection() method, storing the return value -- a Selection object -- in a variable for futher use. Once your selection is in a variable, you perform a variety of operations on it, for example copying the selection to a text string using Selection.toString(), adding a range (as represented by a standard Range object) to the selection (or removing one) with Selection.addRange()/Selection.removeRange(), or changing the selection to be the entire contents of a DOM node using Selection.selectAllChildren(). You can run code in response to the selection being c...
...Children(). You can run code in response to the selection being changed, or a new selection being started, using the GlobalEventHandlers.onselectionchange and GlobalEventHandlers.onselectstart event handlers. Selection API interfaces Selection Represents the range of text selected by the user or the current position of the caret. Extensions to other interfaces Window.getSelection(), Document.getSelection() Returns a Selection object representing the range of text selected by the user or the current position of the caret. Document.getSelection() is basically an alias of Window.getSelection(). GlobalEventHandlers.onselectstart Represents the event handler that is called when a selectstart event is fired on the current object (i.e. when a new range of text is about to be selected by ...
... Opera Full support YesSafari Full support YesWebView Android ...
ServiceWorker.onstatechange - Web APIs
hange = function(statechangeevent) { ... } ServiceWorker.addEventListener('statechange', function(statechangeevent) { ... } ) Examples This code snippet is from the service worker registration-events sample (live demo). The code listens for any change in the ServiceWorker.state and returns its value. ...
...This code snippet is from the service worker registration-events sample (live demo). The code listens for any change in the ServiceWorker.state and returns its value. ...
...orker.state and returns its value. var serviceWorker; if (registration.installing) { serviceWorker = registration.installing; document.querySelector('#kind').textContent = 'installing'; } else if (registration.waiting) { serviceWorker = registration.waiting; document.querySelector('#kind').textContent = 'waiting'; } else if (registration.active) { serviceWorker = registration.active; document.querySelector('#kind').textContent = 'active'; } if (serviceWorker) { logState(serviceWorker.state); serviceWorker.addEventListener('statechange', function(e) { logState(e.target.state); }); } Note that when statechange fires, the service worker's references may have changed. For example: navigator.serviceWorker.register(..).then(function(swr) { swr.installing.state == "installing" ...
ServiceWorker.state - Web APIs
ing, activated, or redundant. Syntax someURL = ServiceWorker.state Value A ServiceWorkerState definition (see the spec.) Examples This code snippet is from the service worker registration-events sample (live demo). The code listens for any change in the ServiceWorker.state and returns its value. ...
...This code snippet is from the service worker registration-events sample (live demo). The code listens for any change in the ServiceWorker.state and returns its value. ...
...orker.state and returns its value. var serviceWorker; if (registration.installing) { serviceWorker = registration.installing; document.querySelector('#kind').textContent = 'installing'; } else if (registration.waiting) { serviceWorker = registration.waiting; document.querySelector('#kind').textContent = 'waiting'; } else if (registration.active) { serviceWorker = registration.active; document.querySelector('#kind').textContent = 'active'; } if (serviceWorker) { logState(serviceWorker.state); serviceWorker.addEventListener('statechange', function(e) { logState(e.target.state); }); } Specifications Specification Status Comment Service WorkersThe definition of 'state' in that specification. Working Draft Initial definition ...
ServiceWorker - Web APIs
activate -- and functional events including fetch. A ServiceWorker object has an associated ServiceWorker.state, related to its lifecycle. Properties The ServiceWorker interface inherits properties from its parent, Worker. ServiceWorker.scriptURL Read only Returns the ServiceWorker serialized script URL defined as part of ServiceWorkerRegistration. The URL must be on the same origin as the document that registers the ServiceWorker. ServiceWorker.state Read only Returns the state of the service worker. It returns one of the following values: installing, installed, activating, activated, or redundant. Event handlers ServiceWorker.onstatechange Read only An EventListener property called whenever an event of type statechange is fired; it is basically fired anytime the ServiceWorker.st...
...tion-events sample (live demo). The code listens for any change in the ServiceWorker.state and returns its value. ...
...serviceWorker.register('service-worker.js', { scope: './' }).then(function (registration) { var serviceWorker; if (registration.installing) { serviceWorker = registration.installing; document.querySelector('#kind').textContent = 'installing'; } else if (registration.waiting) { serviceWorker = registration.waiting; document.querySelector('#kind').textContent = 'waiting'; } else if (registration.active) { serviceWorker = registration.active; document.querySelector('#kind').textContent = 'active'; } if (serviceWorker) { // logState(serviceWorker.state); serviceWorker.addEventListener('statechange', function (e) { // logState(e.targ...
Service Worker API - Web APIs
est / Response object pairs that are cached as part of the ServiceWorker life cycle. CacheStorage Represents the storage for Cache objects. It provides a master directory of all the named caches that a ServiceWorker can access, and maintains a mapping of string names to corresponding Cache objects. Client Represents the scope of a service worker client. A service worker client is either a document in a browser context or a SharedWorker, which is controlled by an active worker. Clients Represents a container for a list of Client objects; the main way to access the active service worker clients at the current origin. ExtendableEvent Extends the lifetime of the install and activate events dispatched on the ServiceWorkerGlobalScope, as part of the service worker lifecycle. This ensures...
...ent, it ensures that functional events such as FetchEvent are not dispatched during installation. NavigationPreloadManager Provides methods for managing the preloading of resources with a service worker. Navigator.serviceWorker Returns a ServiceWorkerContainer object, which provides access to registration, removal, upgrade, and communication with the ServiceWorker objects for the associated document. NotificationEvent The parameter passed into the onnotificationclick handler, the NotificationEvent interface represents a notification click event that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker. ServiceWorker Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same ServiceWorker object. ServiceWorkerContai...
...nts a service worker registration. ServiceWorkerState Associated with its ServiceWorker's state. SyncEvent The SyncEvent interface represents a sync action that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker. SyncManager Provides an interface for registering and listing sync registrations. WindowClient Represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. This is a special type of Client object, with some additional methods and properties available. Specifications Specification Status Comment Service Workers Working Draft Initial definition. ...
StereoPannerNode.pan - Web APIs
nect() 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 output, respectively. ...
... 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 output, respectively. ...
...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 output, respectively. ...
StereoPannerNode - Web APIs
nect() 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 output, respectively. ...
... 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 output, respectively. ...
...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 output, respectively. ...
StorageEvent - Web APIs
A StorageEvent is sent to a window when a storage area it has access to is changed within the context of another document. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/Event" target="_top"><rect x="1" y="1" width="75" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="38.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Event</text></a><polyline points="76,25 86,20 86,30 76,25" stroke="#D4DDE4" f...
...by storage clear() method or the key has been removed from the storage. Read only. oldValue DOMString The original value of the key. The oldValue is null when the key has been newly added and therefore doesn't have any previous value. Read only. storageArea Storage Represents the Storage object that was affected. Read only. url USVString The URL of the document whose key changed. Read only. Methods initStorageEvent() Initializes the event in a manner analogous to the similarly-named initEvent() method in the DOM Events interfaces. Syntax storageEvent.initStorageEvent(type[, canBubble[, cancelable[, key[, oldValue[, newValue[, url[, storageArea]]]]]]]) Parameters typeArg The name of the event. canBubble Optional A boolean indicating ...
...ameters typeArg The name of the event. canBubble Optional A boolean indicating whether the event bubbles up through the DOM or not. cancelable Optional A boolean indicating whether the event is cancelable. key Optional The key whose value is changing as a result of this event. oldValue Optional The key's old value. newValue Optional The key's new value. url Optional The URL of the document initiating the change. storageArea Optional The Storage object representing the storage area on which this event occurred. Specifications Specification Statuc Comment HTML Living StandardThe definition of 'The StorageEvent interface' in that specification. Living Standard ...
StylePropertyMapReadOnly.get() - Web APIs
e add a bit of CSS, including a custom property and an inhertable property: p { font-weight: bold; } a { --colour: red; color: var(--colour); } We use the Element's computedStyleMap() to return a StylePropertyMapReadOnly object. We create an array of properties of interest and use the StylePropertyMapReadOnly's get() method to get only those values. ...
...nt-weight: bold; } a { --colour: red; color: var(--colour); } We use the Element's computedStyleMap() to return a StylePropertyMapReadOnly object. We create an array of properties of interest and use the StylePropertyMapReadOnly's get() method to get only those values. ...
... document.querySelector('#regurgitation'); // Retrieve all computed styles with computedStyleMap() const styleMap = myElement.computedStyleMap(); // array of properties we're interested in const ofInterest = ['font-weight', 'border-left-color', 'color', '--colour']; // iterate thru our properties of interest for ( let i = 0; i < ofInterest.length; i++ ) { // properties const cssProperty = document.createElement('dt'); cssProperty.appendChild(document.createTextNode(ofInterest[i])); stylesList.appendChild(cssProperty); // values const cssValue = document.createElement('dd'); cssValue.appendChild(document.createTextNode( styleMap.get(ofInterest[i]))); stylesList.appendChild(cssValue); } Specifications Specification Status Comment CSS Typed OM Level 1...
StylePropertyMapReadOnly - Web APIs
dl> We add a touch of CSS with a custom property to better demonstrate the output: p { --someVariable: 1.6em; --someOtherVariable: translateX(33vw); --anotherVariable: 42; line-height: var(--someVariable); } We add JavaScript to grab our paragraph and return back a definition list of all the default CSS property values using computedStyleMap(). ...
...p { --someVariable: 1.6em; --someOtherVariable: translateX(33vw); --anotherVariable: 42; line-height: var(--someVariable); } We add JavaScript to grab our paragraph and return back a definition list of all the default CSS property values using computedStyleMap(). ...
...ent.querySelector('p'); // get the <dl> we'll be populating const stylesList = document.querySelector('#output'); // Retrieve all computed styles with computedStyleMap() const stylePropertyMap = myElement.computedStyleMap(); // iterate thru the map of all the properties and values, adding a <dt> and <dd> for each for (const [prop, val] of stylePropertyMap) { // properties const cssProperty = document.createElement('dt'); cssProperty.appendChild(document.createTextNode(prop)); stylesList.appendChild(cssProperty); // values const cssValue = document.createElement('dd'); cssValue.appendChild(document.createTextNode(val)); stylesList.appendChild(cssValue); } Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'StylePropertyMapReadOn...
StyleSheet.disabled - Web APIs
Syntax bool = stylesheet.disabled Example // If the stylesheet is disabled... if (stylesheet.disabled) { // ... apply styles in-line. } Specification Specification Status Comment CSS Object Model (CSSOM)The definition of 'StyleSheet.disabled' in that specification. ...
... Syntax bool = stylesheet.disabled Example // If the stylesheet is disabled... if (stylesheet.disabled) { // ... apply styles in-line. } Specification Specification Status Comment CSS Object Model (CSSOM)The definition of 'StyleSheet.disabled' in that specification. ...
...s applied (it could be removed from the document, for instance). Syntax bool = stylesheet.disabled Example // If the stylesheet is disabled... if (stylesheet.disabled) { // ... apply styles in-line. } Specification Specification Status Comment CSS Object Model (CSSOM)The definition of 'StyleSheet.disabled' in that specification. Working Draft No change from Document Object Model (DOM) Level 2 Style Specification. Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'StyleSheet.disabled' in that specification. Obsolete Initial definition. ...
Multi-touch interaction - Web APIs
h points for processing outside of the event where they were fired. // Log events flag var logEvents = false; // Touch Point cache var tpCache = new Array(); Register event handlers Event handlers are registered for all four touch event types. The touchend and touchcancel event types use the same handler. ...
...round = "pink"; break; default: // More than two simultaneous touches ev.target.style.background = "lightblue"; } } Event logging The functions are used to log event activity to the application window, to support debugging and learning about the event flow. function enableLog(ev) { logEvents = logEvents ? false : true; } function log(name, ev, printTargetIds) { var o = document.getElementsByTagName('output')[0]; var s = name + ": touches = " + ev.touches.length + " ; targetTouches = " + ev.targetTouches.length + " ; changedTouches = " + ev.changedTouches.length; o.innerHTML += s + " "; if (printTargetIds) { s = ""; for (var i=0; i < ev.targetTouches.length; i++) { s += "... id = " + ev.targetTouches[i].identifier + " ...
...ouches.length + " ; targetTouches = " + ev.targetTouches.length + " ; changedTouches = " + ev.changedTouches.length; o.innerHTML += s + " "; if (printTargetIds) { s = ""; for (var i=0; i < ev.targetTouches.length; i++) { s += "... id = " + ev.targetTouches[i].identifier + " "; } o.innerHTML += s; } } function clearLog(event) { var o = document.getElementsByTagName('output')[0]; o.innerHTML = ""; } Related topics and resources Pointer Events ...
TreeWalker.previousNode() - Web APIs
The TreeWalker.previousNode() method moves the current Node to the previous visible node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists,or if it is before that the root node defined at the object construction, returns null and the current node is not changed. Syntax node = treeWalker.previousNode(); Example var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); var node = treeWalker.previousNode(); // returns null as there is no parent Specifications Specification Status Comment DOMThe definition of 'TreeWalker.previousNode' in that specification. Living Standard No c...
... Obsolete Initial definition. ...
... Obsolete Initial definition. ...
UIEvent.initUIEvent() - Web APIs
This method must be called to set the event before it is dispatched, using EventTarget.dispatchEvent(). Once dispatched, it doesn't do anything anymore. Do not use this method anymore as it is deprecated. Instead use specific event constructors, like UIEvent(). The page on Creating and triggering events gives more information about the way to use these. ...
...fining whether the event can be canceled. Once set, the read-only property Event.cancelable will give its value. view Is the WindowProxy associated with the event. detail Is an unsigned long specifying some detail information about the event, depending on the type of event. For mouse events, it indicates how many times the mouse has been clicked on a given screen location. ...
...ts, it indicates how many times the mouse has been clicked on a given screen location. Example var e = document.createEvent("UIEvent"); // creates a click event that bubbles, can be cancelled, // and with its view and detail property initialized to window and 1, // respectively e.initUIEvent("click", true, true, window, 1); Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'UIEvent.initUIEvent()' in that specification. Obsolete From Document Object Model (DOM) Level 2 Events Specification, deprecated. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'UIEvent.initUIEvent()' in that specification. Obsolete Initial definition. Browser compatibility Th...
UserDataHandler - Web APIs
ome browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Summary When associating user data with a key on a node, Node.setUserData() can also accept, in its third argument, a handler which will be called when the object is cloned, imported, deleted, renamed, or adopted. Per the specification, exceptions should not be thrown in a UserDataHandler. In both document.importNode() and Node.cloneNode(), although user data is not copied over, the handler will be called. Properties None. Methods handle (operation, key, data, src, dst) (no return value) This method is a callback which will be called if a node is being cloned, imported, renamed and as well, if deleted or adopted. operation (unsigned short) is an operation type integer (see below). key (DOM...
...ed or adopted. operation (unsigned short) is an operation type integer (see below). key (DOMString) is the user key. data (DOMUserData) is the user data. src (Node) is the source node (null if being deleted). dst (Node) is the destination node (if any, or null). ...
... source node (null if being deleted). dst (Node) is the destination node (if any, or null). ...
VideoTrackList: change event - Web APIs
The change event is fired when a video track is made active or inactive, for example by changing the track's selected property. ...
... Cancelable No Interface Event Event handler property onchange Examples Using addEventListener(): const videoElement = document.querySelector('video'); videoElement.videoTracks.addEventListener('change', (event) => { console.log(`'${event.type}' event fired`); }); // changing the value of `selected` will trigger the `change` event const toggleTrackButton = document.querySelector('.toggle-track'); toggleTrackButton.addEventListener('click', () => { const track = videoElement.videoTracks[0]; track.selected = !track.selected; }); Using the onchange event handler property: const videoElement = document.querySelector('video'); videoElement.videoTracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; // changing the value of `sel...
... Living Standard ...
VisualViewport - Web APIs
d with that window. You can get a window's visual viewport using Window.visualViewport. Note: Only the top-level window has a visual viewport that's distinct from the layout viewport. Therefore, it's generally only the VisualViewport object of the top-level window that's useful. For an <iframe>, visual viewport metrics like VisualViewport.width always correspond to layout viewport metrics like document.documentElement.clientWidth. Properties VisualViewport also inherits properties from its parent, EventTarget. VisualViewport.offsetLeft Read only Returns the offset of the left edge of the visual viewport from the left edge of the layout viewport in CSS pixels. VisualViewport.offsetTop Read only Returns the offset of the top edge of the visual viewport from the top edge of the layout v...
...e via the VisualViewport.onscroll property. Examples Hiding an overlaid box on zoom This example, taken from the Visual Viewport README, shows how to write a simple bit of code that will hide an overlaid box (which might contain an advert, say) when the user zooms in. This is a nice way to improve the user experience when zooming in on pages. A live sample is also available. ...
...ottomBar.style.display = "none"; else bottomBar.style.display = "block"; } window.visualViewport.addEventListener('resize', resizeHandler); Simulating position: device-fixed This example, also taken from the Visual Viewport README, shows how to use this API to simulate position: device-fixed, which fixes elements to the visual viewport. A live sample is also available. var bottomBar = document.getElementById('bottombar'); var viewport = window.visualViewport; function viewportHandler() { var layoutViewport = document.getElementById('layoutViewport'); // Since the bar is position: fixed we need to offset it by the visual // viewport's offset from the layout viewport origin. var offsetLeft = viewport.offsetLeft; var offsetTop = viewport.height - layoutViewport.ge...
A basic 2D WebGL animation example - Web APIs
mponents; let vertexCount; // Rendering data shared with the // scalers. ...
... the shaders are compiled, the program is linked using gl.linkProgram(). If an error occurrs while linking the program, the error message is logged to console. Finally, the compiled program is returned to the caller. Compiling an individual shader The compileShader() function, below, is called by buildShaderProgram() to compile a single shader. ...
...Then a new shader of the specified type is created using gl.createShader(). The source code is sent into the new shader by passing it into gl.shaderSource(), and then the shader is compiled using gl.compileShader() Compile errors are logged to the console. Note the use of a template literal stri...
Hello GLSL - Web APIs
<script type="x-shader/x-fragment" id="fragment-shader"> #version 100 void main() { gl_FragColor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function(){ "use strict" window.addEventListener("load", setupWebGL, false); var gl, program; function setupWebGL (evt) { window.removeEventListener(evt.type, setupWebGL, false); if (!(gl = getRenderingContext())) return; var source = document.querySelector("#vertex-shader").innerHTML; var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader,source); gl.compileShader(vertexShader); source = document.querySelector("#fragment-shader").innerHTML var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader,source); gl.compileShader(fragmentShader); program = gl.createPro...
..." + "Error log: " + linkErrLog; return; } initializeAttributes(); gl.useProgram(program); gl.drawArrays(gl.POINTS, 0, 1); cleanup(); } var buffer; function initializeAttributes() { gl.enableVertexAttribArray(0); buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.vert...
... cleanup(); } var buffer; function initializeAttributes() { gl.enableVertexAttribArray(0); buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.vertexAttribPointer(0, 1, gl.FLOAT, false, 0, 0); } function cleanup() { gl.useProgram(null); if (buffer) gl.deleteBuffer(buffer); if (program) gl.deleteProgram(program); } function getRenderingContext() { var canvas = document.querySelector("canvas"); canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { var paragraph = document.querySelector("p"); paragraph.innerHTML = "Failed to get WebGL context." + "Your browser or device may not support WebGL."; return null; } gl.viewport(0...
Hello vertex attributes - Web APIs
x-fragment" id="fragment-shader"> #version 100 precision mediump float; void main() { gl_FragColor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function(){ "use strict" window.addEventListener("load", setupWebGL, false); var gl, program; function setupWebGL (evt) { window.removeEventListener(evt.type, setupWebGL, false); if (!(gl = getRenderingContext())) return; var source = document.querySelector("#vertex-shader").innerHTML; var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader,source); gl.compileShader(vertexShader); source = document.querySelector("#fragment-shader").innerHTML var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader,source); gl.compileShader(fragmentShader); program = gl.createPro...
...(); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); gl.detachShader(program, vertexShader); gl.detachShader(program, fragmentShader); gl.deleteShader(vertexShader); gl.deleteShader(fragmentShader); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { var linkErrLog = gl.getProgramInfoLog(program); cleanup(); document.querySelector("p").innerHTML = "Shader program did not link successfully. " + "Error log: " + linkErrLog; return; } initializeAttributes(); gl.useProgram(program); gl.drawArrays(gl.POINTS, 0, 1); document.querySelector("canvas").addEventListener("click", function (evt) { var clickXrelativToCanvas = evt.pageX - evt.target.offsetLeft; var clickX...
...l.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.0]), gl.STATIC_DRAW); gl.vertexAttribPointer(0, 1, gl.FLOAT, false, 0, 0); } window.addEventListener("beforeunload", cleanup, true); function cleanup() { gl.useProgram(null); if (buffer) gl.deleteBuffer(buffer); if (program) gl.deleteProgram(program); } function getRenderingContext() { var canvas = document.querySelector("canvas"); canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { var paragraph = document.querySelector("p"); paragraph.innerHTML = "Failed to get WebGL context." + "Your browser or device may not support WebGL."; return null; } gl.viewport(0...
Textures from code - Web APIs
on); float distanceSqrd = distance * distance; gl_FragColor = vec4( 0.2/distanceSqrd, 0.1/distanceSqrd, 0.0, 1.0 ); } </script> ;(function(){ "use strict" window.addEventListener("load", setupWebGL, false); var gl, program; function setupWebGL (evt) { window.removeEventListener(evt.type, setupWebGL, false); if (!(gl = getRenderingContext())) return; var source = document.querySelector("#vertex-shader").innerHTML; var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader,source); gl.compileShader(vertexShader); source = document.querySelector("#fragment-shader").innerHTML var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader,source); gl.compileShader(fragmentShader); program = gl.createPro...
..." + "Error log: " + linkErrLog; return; } initializeAttributes(); gl.useProgram(program); gl.drawArrays(gl.POINTS, 0, 1); cleanup(); } var buffer; function initializeAttributes() { gl.enableVertexAttribArray(0); buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferD...
...tribArray(0); buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.0, 0.0]), gl.STATIC_DRAW); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); } function cleanup() { gl.useProgram(null); if (buffer) gl.deleteBuffer(buffer); if (program) gl.deleteProgram(program); } function getRenderingContext() { var canvas = document.querySelector("canvas"); canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { var paragraph = document.querySelector("p"); paragraph.innerHTML = "Failed to get WebGL context." + "Your browser or device may not support WebGL."; return null; } gl.viewport(0...
Using DTMF with WebRTC - Web APIs
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; let mediaConstraints = { audio: true, video: false }; let offerOptions = { offerToReceiveAudio: 1, offerToReceiveVideo: 0 }; let dialButton = null; let logElement = null; These are, in order: dialSt...
... first loaded. See Initialization below. Initialization When the page loads, we do some basic setup: we fetch references to the dial button and the log output box elements, and we use addEventListener() to add an event listener to the dial button so that clicking it calls the connectAndDial() function to begin the connection process. window.addEventListener("load", function() { logElement = document.querySelector(".log"); dialButton = document.querySelector("#dial"); dialButton.addEventListener("click", connectAndDial, false); }); Starting the connection process When the dial button is clicked, connectAndDial() is called. This starts building the WebRTC connection in preparation for sending the DTMF codes. function connectAndDial() { callerPC = new RTCPeerConnection(); hasAddTr...
...teDTMFSender() to get the RTCDTMFSender object. Although this method is obsolete, this example supports it as a fallback to let older browsers (and those not yet updated to support the current WebRTC DTMF API) run the example. Finally, we set the DTMF sender's ontonechange event handler so we get notified each time a DTMF tone finishes playing. You can find the log function at the bottom of the documentation. When a tone finishes playing Each time a DTMF tone finishes playing, a tonechange event is delivered to callerPC. The event listener for these is implemented as the handleToneChangeEvent() function. function handleToneChangeEvent(event) { if (event.tone !== "") { log("Tone played: " + event.tone); } else { log("All tones have played. Disconnecting."); callerPC.getLocalStr...
Fundamentals of WebXR - Web APIs
acts being left behind. Some platforms may provide previously-cleared frames to you, while others may optimize performance by not erasing the framebuffers in order to avoid having to touch each pixel twice per frame. There are two VR session modes available in WebXR: inline and immersive. The former, specified by the session mode string inline, presents the rendered scene within the context of a document in a web browser, and doesn't require special XR hardware to view. The immersive session mode is indicated using the session mode immersive-vr. This session mode requires an XR device such as a headset, and replaces the entire world with the rendered scene using the displays shown to each of the user's eyes. Augmented reality In augmented reality (AR), the user sees the imagery you render prese...
...on top of the physical, real-world environment around them. Because AR is always an immersive experience, in which the scene is the entire world around the user (rather than being enclosed in a box on a screen), the only AR session mode is immersive-ar. The WebXR Augmented Reality Module is still in a state of early development and is not yet stable enough for regular use. We do not yet include documentation for it here on MDN, but it will come as soon as the module's specification settles down. There are two basic types of AR device: Devices which use cameras to capture the world in front of the user, render the WebXR content atop that image, then display the image on a screen. These devices include phones, which show the resulting scene on the device's screen in a 2D presentation, as well...
...d the rendering process is almost exactly the same as for VR, except you don't erase the background or skybox before rendering each frame. For more information about using WebXR to create augmented reality experiences, see Augmented reality with WebXR. Types of WebXR hardware The simplest XR presentation involves rendering the scene directly to the user's screen, either in the context of a web document, or in full screen mode. This is most common when the user either doesn't have a dedicated XR device, or when the user is viewing the AR or VR app on a phone or other handheld device. Simpler and lower-priced XR devices typically use an integrated computer or connect to a smartphone, essentially using the mobile CPU and GPU to run apps, render images, and display them to the user. Higher-powered...
Window.getDefaultComputedStyle() - Web APIs
to get the computed style. pseudoElt Optional A string specifying the pseudo-element to match. Must be null (or not specified) for regular elements. Return value The returned style is a CSSStyleDeclaration object. The object is of the same type as the object returned by Window.getComputedStyle(), but only takes into account user-agent and user rules. ...
..., but only takes into account user-agent and user rules. Example Simple example var elem1 = document.getElementById("elemId"); var style = window.getDefaultComputedStyle(elem1); Longer example <style> #elem-container { position: absolute; left: 100px; top: 200px; height: 100px; } </style> <div id="elem-container">dummy</div> <div id="output"></div> <script> var elem = document.getElementById("elem-container"); var theCSSprop = window.getDefaultComputedStyle(elem).position; document.getElementById("output").innerHTML = theCSSprop; // Will output "static" </script> Use with pseudo-elements The getDefaultComputedStyle() method can pull style info from pseudo-elements (e.g., ::before or ::after). <style> h3:after { content: ' rocks!'; } </style> <h3>generated ...
... theCSSprop = window.getDefaultComputedStyle(elem).position; document.getElementById("output").innerHTML = theCSSprop; // Will output "static" </script> Use with pseudo-elements The getDefaultComputedStyle() method can pull style info from pseudo-elements (e.g., ::before or ::after). <style> h3:after { content: ' rocks!'; } </style> <h3>generated content</h3> <script> var h3 = document.querySelector('h3'), result = getDefaultComputedStyle(h3, ':after').content; console.log('the generated content is: ', result); // returns 'none' </script> Notes The returned value is, in certain known cases, expressly incorrect by deliberate intent. In particular, to avoid the so called CSS History Leak security issue, browsers may expressly "lie" about the used value for a link an...
Window.getSelection() - Web APIs
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 it is passed to window.alert(). However, attempting to use a JavaScript String property or me...
...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 objects You can call Document.getSelection(), which works identically to Window.getSelection(). It is worth noting that currently getSelection() doesn't work on the content of <textarea> and <input> elements in Firefox, Edge (Legacy) and Internet Explorer. HTMLInputElement.setSelectionRange() or the selectionStart and selectionEnd properties could be used to work around this. Notice also the difference between selection and...
...ction(), which works identically to Window.getSelection(). It is worth noting that currently getSelection() doesn't work on the content of <textarea> and <input> elements in Firefox, Edge (Legacy) and Internet Explorer. HTMLInputElement.setSelectionRange() or the selectionStart and selectionEnd properties could be used to work around this. Notice also the difference between selection and focus. Document.activeElement returns the focused element. Specifications Specification Status Comment Selection APIThe definition of 'Window.getSelection()' in that specification. Working Draft New spec. ...
Window.matchMedia() - Web APIs
Web › API › Window › matchMedia
The Window interface's matchMedia() method returns a new MediaQueryList object that can then be used to determine if the document matches the media query string, as well as to monitor the document to detect when it matches (or stops matching) that media query. Syntax mqList = window.matchMedia(mediaQueryString) Parameters mediaQueryString A string specifying the media query to parse into a MediaQueryList. Return value A new MediaQueryList object for the media query. Use this object's properties and events to detect matches and to monitor for changes to those matches over time. Usage notes You can use the returned media query to perform both instantanteous and event-driven checks to see if the document matches the media query. To perform a one-time, instantaneous check to see if the d...
... and events to detect matches and to monitor for changes to those matches over time. Usage notes You can use the returned media query to perform both instantanteous and event-driven checks to see if the document matches the media query. To perform a one-time, instantaneous check to see if the document matches the media query, look at the value of the matches property, which will be true if the document meets the media query's requirements. If you need to be kept aware of whether or not the document matches the media query at all times, you can instead watch for the change event to be delivered 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 MediaQuer...
...e 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. HTML <span class="mq-value"></span> A simple <span> to receive...
Window.open() - Web APIs
Web › API › Window › open
his will NOT be used as the window's title. windowFeatures Optional A DOMString containing a comma-separated list of window features given with their corresponding values in the form "name=value". These features include options such as the window's default size and position, whether or not to include toolbar, and so forth. There must be no whitespace in the string. See Window features below for documentation of each of the features that can be specified. Return value A WindowProxy object, which is basically a thin wrapper for the Window object representing the newly created window, and has all its features available. If the window couldn't be opened, the returned value is instead null. The returned reference can be used to access properties and methods of the new window as long as it complies...
...eatures is non-empty, status detaults to off. resizable If this feature is on, the new secondary window will be resizable. If windowFeatures is non-empty, resizable detaults to on. Tip: For accessibility reasons, it is strongly recommended to set this feature always on scrollbars If this feature is on, the new secondary window will show horizontal and/or vertical scrollbar(s) if the document doesn't fit into the window's viewport. If windowFeatures is non-empty, scrollbars detaults to off. See note on scrollbars. Tip: For accessibility reasons, it is strongly encouraged to set this feature always on Window functionality features noopener If this feature is set, the newly-opened window will open as normal, except that it will not have access back to the originating ...
... Always use the target attribute If javascript support is disabled or non-existent, then the user agent will create a secondary window accordingly or will render the referenced resource according to its handling of the target attribute: e.g. some user agents that cannot create new windows, like MS Web TV, will fetch the referenced resource and append it at the end of the current document. The goal and the idea is to try to provide - not impose - to the user a way to open the referenced resource, a mode of opening the link. Your code should not interfere with the features of the browser at the disposal of the user and your code should not interfere with the final decision resting with the user. Do not use target="_blank" Always provide a meaningful name to your target attribute ...
XMLHttpRequest.send() - Web APIs
s primarily used for requests such as PUT. If the request method is GET or HEAD, the body parameter is ignored and the request body is set to null. If no Accept header has been set using the setRequestHeader(), an Accept header with the type "*/*" (any type) is sent. Syntax XMLHttpRequest.send(body) Parameters body Optional A body of data to be sent in the XHR request. This can be: A Document, in which case it is serialized before being sent. An XMLHttpRequestBodyInit, which per the Fetch spec can be a Blob, BufferSource, FormData, URLSearchParams, or USVString object. null If no value is specified for the body, a default value of null is used. The best way to send binary content (e.g. in file uploads) is by using an ArrayBufferView or Blob in conjunction with the send() meth...
...est, and/or the request is complete. NetworkError The resource type to be fetched is a Blob, and the method is not GET. Example: GET var xhr = new XMLHttpRequest(); xhr.open('GET', '/server', true); xhr.onload = function () { // Request finished. Do processing here. }; xhr.send(null); // xhr.send('string'); // xhr.send(new Blob()); // xhr.send(new Int8Array()); // xhr.send(document); Example: POST var xhr = new XMLHttpRequest(); xhr.open("POST", '/server', true); //Send the proper header information along with the request xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { // Call a function when the state changes. if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { // Request fi...
...r information along with the request xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { // Call a function when the state changes. if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { // Request finished. Do processing here. } } xhr.send("foo=bar&lorem=ipsum"); // xhr.send(new Int8Array()); // xhr.send(document); Specifications Specification Status Comment XMLHttpRequestThe definition of 'send()' in that specification. Living Standard WHATWG living standard ...
XMLHttpRequest - Web APIs
e any other 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. XMLH...
...ly 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.responseURL Read only Returns the serialized URL of the response or the empty string if the URL is null. XMLHttpRequest.responseXML Read only Returns a Document containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers. XMLHttpRequest.status Read only Returns an unsigned short with the status of the response of the request. XMLHttpRequest.statusText Read only Returns a DOMString containing the response string returned by the HTTP server. Unlik...
...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 XMLHttpRequest.abort(). Also available via the onabort property. error Fired when the request encountered an error. Also available via the onerror property. load Fired when an XMLHttpRequest ...
XPathEvaluator.evaluate() - Web APIs
Syntax XPathResult XPathEvaluator.evaluate(expression, contextNode, resolver, type, result); Parameters expression A DOMString representing the XPath expression to be parsed and evaluated. contextNode A Node representing the context to use for evaluating the expression. resolver Optional Permits translation of all prefixes, including the xml namespace prefix, within the XPath expression into appropriate namespace URIs. type Optional Specifies the type of result to be returned by evaluating the expression. ...
... according to the rules of the XPathEvaluator, an XPathException of type INVALID_EXPRESSION_ERR is raised. TYPE_ERR In case result cannot be converted to the specified type, an XPathException of type TYPE_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. WRONG_DOCUMENT_ERR If the provided context node is from a document that is not supported by the XPathEvaluator, a DOMException of type WRONG_DOCUMENT_ERR is raised. NOT_SUPPORTED_ERR If the provided context node is not a type permitted as an XPath context node or the request type is not permitted by the XPathEvaluator, a DOMException of type NOT_SUPPORTED_ERR is raised. Example The following example shows ...
...pe permitted as an XPath context node or the request type is not permitted by the XPathEvaluator, a DOMException of type NOT_SUPPORTED_ERR is raised. Example The following example shows the use of the evaluate() method. HTML <div>XPath example</div> <div>Number of &lt;div&gt;s: <output></output></div> JavaScript var evaluator = new XPathEvaluator(); var result = evaluator.evaluate("//div", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE); document.querySelector("output").textContent = result.snapshotLength; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathEvaluator.evaluate()' in that specification. Recommendation Initial definition ...
XPathExpression.evaluate() - Web APIs
Syntax XPathResult node.evaluate(contextNode, type, result); Parameters contextNode A Node representing the context to use for evaluating the expression. type Optional Specifies the type of result to be returned by evaluating the expression. This must be one of the XPathResult.Constants. result Optional Allows to specify a result object which may be reused and returned by this method. If this is specified as null or the implementation does not reuse the specified result, a new result object will be returned. ...
... according to the rules of the XPathEvaluator, an XPathException of type INVALID_EXPRESSION_ERR is raised. TYPE_ERR In case result cannot be converted to the specified type, an XPathException of type TYPE_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. WRONG_DOCUMENT_ERR If the provided context node is from a document that is not supported by the XPathEvaluator, a DOMException of type WRONG_DOCUMENT_ERR is raised. NOT_SUPPORTED_ERR If the provided context node is not a type permitted as an XPath context node or the request type is not permitted by the XPathEvaluator, a DOMException of type NOT_SUPPORTED_ERR is raised. Example The following example shows ...
...rmitted by the XPathEvaluator, a DOMException of type NOT_SUPPORTED_ERR is raised. Example The following example shows the use of the evaluate() method. HTML <div>XPath example</div> <div>Number of &lt;div&gt;s: <output></output></div> JavaScript var xpath = "//div"; var evaluator = new XPathEvaluator(); var expression = evaluator.createExpression("//div"); var result = expression.evaluate(document, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE); document.querySelector("output").textContent = result.snapshotLength; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathExpression.evaluate()' in that specification. Recommendation Initial definition ...
XPathExpression - Web APIs
Example The following example shows the use of the XPathExpression interface. ...
...ic node to return information from its DOM tree. This is useful when an expression will be reused in an application, because it is just compiled once and all namespace prefixes which occur within the expression are preresolved. Objects of this type are created by calling XPathEvaluator.createExpression(). Methods XPathExpression.evaluate() Evaluates the XPath expression on the given node or document. ...
...n.evaluate() Evaluates the XPath expression on the given node or document. Example The following example shows the use of the XPathExpression interface. HTML <div>XPath example</div> <div>Number of &lt;div&gt;s: <output></output></div> JavaScript var xpath = "//div"; var evaluator = new XPathEvaluator(); var expression = evaluator.createExpression(xpath); var result = expression.evaluate(document, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE); document.querySelector("output").textContent = result.snapshotLength; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathExpression' in that specification. Recommendation Initial definition ...
XSLT Basic Example - Web APIs
Using the ?xml-stylesheet? processing instruction, it links to the XSLT stylesheet (example.xsl) via its href attribute. An XSLT stylesheet starts with the xsl:stylesheet element, which contains all the templates used to create the final output. ...
...Using the ?xml-stylesheet? processing instruction, it links to the XSLT stylesheet (example.xsl) via its href attribute. An XSLT stylesheet starts with the xsl:stylesheet element, which contains all the templates used to create the final output. ...
... contains all the templates used to create the final output. The example in Figure 1 has two templates - one that matches the root node and one that matches Author nodes. The template that matches the root node outputs the article's title and then says to process all templates (via apply-templates) that match Author nodes which are children of the Authors node. Figure 1 : Simple XSLT Example XML Document (example.xml) : <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="example.xsl"?> <Article> <Title>My Article</Title> <Authors> <Author>Mr. Foo</Author> <Author>Mr. Bar</Author> </Authors> <Body>This is my article text.</Body> </Article> XSL Stylesheet (example.xsl) : <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"...
Introduction - Web APIs
oduction One noticeable trend in W3C standards has been the effort to separate content from style. This would allow the same style to be reused for multiple content, as well as simplify maintenance and allow a quick (only modify one file) way to change the look of content. CSS (Cascade Style Sheets) was one of the first ways proposed by the W3C. CSS is a simple way to apply style rules to a web document. These style rules define how the document (the content) should be laid out. However, it has several limitations, such as lack of programming structures and ability to create complex layout models. CSS also has limited support for changing the position of an element. XSL (Extensible Stylesheet Language) Transformations are composed of two parts: XSL elements, which allow the transformation of an...
...veral limitations, such as lack of programming structures and ability to create complex layout models. CSS also has limited support for changing the position of an element. XSL (Extensible Stylesheet Language) Transformations are composed of two parts: XSL elements, which allow the transformation of an XML tree into another markup tree and XPath, a selection language for trees. XSLT takes an XML document (the content) and creates a brand new document based on the rules in the XSL stylesheet. This allows XSLT to add, remove and reorganize elements from the original XML document and thus allows more fine-grain control of the resulting document's structure. Transformations in XSLT are based on rules that consist of templates. Each template matches (using XPath) a certain fragment of the input XML d...
...is allows XSLT to add, remove and reorganize elements from the original XML document and thus allows more fine-grain control of the resulting document's structure. Transformations in XSLT are based on rules that consist of templates. Each template matches (using XPath) a certain fragment of the input XML document and then applies the substitution part on that fragment to create the new resulting document. ...
msthumbnailclick - Web APIs
on in the taskbar. This proprietary method is specific to Internet Explorer and Microsoft Edge. ...
...pture) General info Synchronous No Bubbles No Cancelable No Note The onmsthumbnailclick event is available only to documents that are launched from a pinned site shortcut. Parameters pEvtObj [in] Type: IHTMLEventObj Pointer to an IHTMLEventObj interface for the current event. ...
...nt.addEventListener('msthumbnailclick', thumbnailClickHandler); Example 2 // Adds an overlay icon on your app pinned to the taskbar window.external.msSiteModeSetIconOverlay(iconUri, toolTip); // removes an overlay icon window.external.msSiteModeClearIconOverlay(); // 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 Micr...
ARIA: application role - Accessibility
to handle mouse, keyboard, or touch interaction. In this mode, the web author is completely responsible for handling any and all keyboard input, focus management, and other interactions and cannot assume assistive technologies would do any processing on their end. If the web application encompassed by the application role contains parts that should be treated like normal web content, a role of document or article should be used. Background For historic reasons, especially on Windows, screen readers and some other assistive technologies (AT) have traditionally grabbed the whole web content from the browser at once after it had finished loading. The ATs build their own representation of it that makes the most sense for a blind user to consume the content. This is often referred to as virtual do...
...r historic reasons, especially on Windows, screen readers and some other assistive technologies (AT) have traditionally grabbed the whole web content from the browser at once after it had finished loading. The ATs build their own representation of it that makes the most sense for a blind user to consume the content. This is often referred to as virtual document, browse mode, or similar terms. The document is streamlined to a single-column view. A keyboard interaction model is generated that is very similar to a word processor where users can read line by line, sentence by sentence, or paragraph by paragraph. The AT will read any semantics like links, headings, form controls, tables, lists, or images. In addition, a set of so-called quick navigation keys has been established over the years that al...
...de, lets all keyboard input go through to the browser again. Escape is the most common way of switching back to browse mode. The application role is designed to provide a means for widgets that are not part of the standard set to be accessible for direct interaction in ATs that use both browse and focus modes for interacting with web content. Associated WAI-ARIA roles, states, and properties document, article Used to indicate parts of the application that should be treated as normal web content aria-activedescendant Used to manage focus inside the application. aria-label Used to provide the name of the application or purpose of the widget that is being exposed. aria-describedby Used to indicate the idref of an element that contains additional instructions for navigating or operating th...
ARIA: article role - Accessibility
It is usually set on related content items such as comments, forum posts, newspaper articles or other items grouped together on one page. <div role="article"> <h2>Heading of the segment</h2> <p>Paragraph for the segment.</p> <p>Another paragraph.</p> ... controls to interact with the article, share it, etc. ... </div> <div role="article"> ... </div> This example shows two articles side by side on one page that could be structured similarly and are related. Instead of a div with an article role, use the <article> element. Always use native element if available. ...
... role, use the <article> element. Always use native element if available. Instead of using role="article", the <article> element can be used. <article> <h2>Heading of the segment</h2> <p>Paragraph for the segment.</p> <p>Another paragraph.</p> ... controls to interact with the article, share it, etc. ... </article> <article> ... </article> Description The article role denotes a section of a document, page, or site that, if it were standing on its own, could be viewed as a complete document, page or site. The aim of a set of article sections is to indicate their relationship to one another. Articles are not considered a navigational landmark, but many assistive technologies that support landmarks also support a means to navigate among articles. They may also support indication of nesting rel...
...hanging 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 be used. Examples The restaurant recommendations feed display along with its separate documentation from the WAI-ARIA 1.1 authoring practices feed design pattern Specifications Specification Status Accessible Rich Internet Applications (WAI-ARIA) 1.1The definition of 'article' in that specification. Recommendation WAI-ARIA Authoring PracticesThe definition of 'feed' in that specification. Working Draft Precedence order This role corresponds to...
ARIA: form role - Accessibility
ly communicate a section of content as a form landmark, if it is provided an accessible name. Developers should always prefer using the correct semantic HTML element over using ARIA. Use the HTML <form> element if possible. The <form> element defines a form landmark when it has an accessible name (e.g. aria-labelledby, aria-label or title). Make sure to have a unique label on each form in a document to help users understand the purpose of the form. This label should be visible to all users, not just assistive technology users. Use the search landmark instead of the form landmark when the form is used for search functionality. Use the role="form" to identify a region of the page; do not use it to identify every form field. Even if you are using the form landmark instead of <form>, you are en...
...off" spellcheck="false" type="text"> <label for="comment">Comment</label> <textarea id="comment" name="comment"></textarea> <input value="Comment" type="submit"> </div> It is recommended to use <form> instead. <form id="send-comment" aria-label="Add a comment"> .... </form> Accessibility concerns Use sparingly Landmark roles are intended to identify larger overall sections of the document. Using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. Inputs are not forms You do not need to declare role="form" on every form element (inputs, text areas, selects, etc.). It should be declared on the HTML element that wraps the form elements. Ideally, use the <form> element as the wrapping element and do not decl...
...ntact form form". Best practices Prefer HTML Using the <form> element will automatically communicate a section has a role of form. If at all possible, prefer using it instead. Added benefits Certain technologies such as browser extensions can generate lists of all landmark roles present on a page, allowing non-screen reader users to also quickly identify and navigate to large sections of the document. Landmarks browser extension Specifications Specification Status Accessible Rich Internet Applications (WAI-ARIA) 1.1The definition of 'ARIA Form Role' in that specification. Recommendation WAI-ARIA Authoring PracticesThe definition of 'Role Form' in that specification. Working Draft Screen reader support TBD ...
ARIA: button role - Accessibility
or: 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 additional name. // Don't add blank entries to the list. if(name.length > 0) { listItem = document.createElement('li'); listItem.appendChild(document.createTextNode(name)); ...
...t.value; newNameInput.value = ''; // clear the text field newNameInput.focus(); // give the text field focus to enable entering and additional name. // Don't add blank entries to the list. if(name.length > 0) { listItem = document.createElement('li'); listItem.appendChild(document.createTextNode(name)); // Add the new name to the list. let list = document.getElementById('nameList'); list.appendChild(listItem); } } Toggle button example In this snippet a <span> element is converted to a toggle button using the button role and the aria-pressed attribute. When the button is activated, the aria-pressed value switches states; changing from true to false and back again. HTML <button type="button" onclick="handleBtnClick()" onKeyDown="h...
...vent.target); } function handleBtnKeyDown(event) { // Check to see if space or enter were pressed if (event.key === " " || event.key === "Enter" || event.key === "Spacebar") { // "Spacebar" for IE11 support // Prevent the default action to stop scrolling when space is pressed event.preventDefault(); toggleButton(event.target); } } function toggleButton(element) { var audio = document.getElementById('audio'); // Check to see if the button is pressed var pressed = (element.getAttribute("aria-pressed") === "true"); // Change aria-pressed to the opposite state element.setAttribute("aria-pressed", !pressed); // toggle the play state of the audio file if(pressed) { audio.pause(); } else { audio.play(); } } Result Accessibility concerns Buttons are int...
Web applications and ARIA FAQ - Accessibility
d 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. 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", "progressbar"); progressBar.setAttribute("aria-valuemin", 0); progressBar.setAttribute("aria-valuemax", 100); // Create a function that can be called at any time to update the value of the progress bar. function updateProgress(percen...
...he markup used for an HTML5 progress bar: <!DOCTYPE html> <html> <head><title>Gracefully degrading progress bar</title></head> <body> <progress id="progress-bar" value="0" max="100">0% complete</progress> <button id="update-button">Update</button> </body> </html> ... and here is the JavaScript code that will ensure the progress bar still works in older browsers: var progressBar = document.getElementById("progress-bar"); // Check to see if the browser supports the HTML5 <progress> tag. var supportsHTML5Progress = (typeof (HTMLProgressElement) !== "undefined"); function setupProgress() { if (!supportsHTML5Progress) { // HTML5 <progress> isn't supported in this browser, so we need to add // ARIA roles and states to the element. progressBar.setAttribute("role", "progre...
...ria-valuenow", percentComplete); } else { // HTML5 <progress> is supported, so update the value attribute instead. progressBar.setAttribute("value", percentComplete); } progressBar.textContent = percentComplete + "% complete"; } function initDemo() { setupProgress(); // Setup the progress bar. // Bind a click handler to the button, which will update the progress bar to 75%. document.getElementById("update-button").addEventListener("click", function (e) { updateProgress(75); e.preventDefault(); }, false); } initDemo(); How do assistive technologies work? Assistive technologies use an API built into each operating system specifically designed to describe the roles, states, and structure of an application's user interface. For example, a screen reader uses this API...
Architecture - Accessibility
Sometimes the embedded object is really just another text container with more embedded objects. However in accessibility hierarchies such as ATK and IAccessible2, text is not exposed in leaf nodes as it is in a W3C DOM. The text is actually exposed via a special text interface in the parent of the text nodes. ...
...en not a link As explained above, anything that is embedded in text implements the Hyperlink interface. While it is odd to call non-link objects a link, this was a necessary compromise in the newatk design because it is necessary to know where objects exist within their containing text. Previously the hyper link interface was really only for links, but the design could not fully represent an HTML document hierarchy. Keeping the link name of the interface is unfortunate but necessary for backwards compatibility, without introducing superfluous interfaces. API comparison nsIAccessible (internal). When you have an nsIAccessibleHyperText, you can ask for its links, which is the subset of children from the nsIAccessible hierarchy that are not text or whitespace. ATK: Same as nsIAccessible, except ...
...ke a character offset. This value of -2 means, use the caret position. Not only can this save extra calls, but it will always return the visual line of text when used with the getText methods and line boundaries. The following magic offsets are useful to define in your code: #define CHAR_OFFSET_END_OF_LINE = -1 #define CHAR_OFFSET_CARET = -2 More information Many more details on the Mozilla document hierarchy are in the original design document for newatk. There are also details on the general implementation of Mozilla accessibility architecture (needs updating). ...
Keyboard-navigable JavaScript widgets - Accessibility
Overview Web applications often use JavaScript to mimic desktop widgets such as menus, tree views, rich text fields, and tab panels. These widgets are typically composed of <div> and <span> elements that do not, by nature, offer the same keyboard functionality that their desktop counterparts do. This document describes techniques to make JavaScript widgets accessible with the keyboard. 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. When set to -1, the element becomes focusable by script, but it does not become part of the keyboard focus order...
...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 relative to element's position in document (note that interactive elements like <a> have this behavior by default, they don't need the attribute). Positive (e.g. tabindex="33") Yes tabindex value determines where this element is positioned in the tab order: smaller values will position elements earlier in the tab order than larger values (for example, tabindex="7" will be positioned before tabindex="11"). Non-native ...
... set focus. Use element.focus() instead. Use onfocus to track the current focus Don't assume that all focus changes will come via key and mouse events: assistive technologies such as screen readers can set the focus to any focusable element. Track focus using onfocus and onblur instead. onfocus and onblur can now be used with every element. There is no standard DOM interface to get the current document focus. If you want to track the focus status, you can use the document.activeElement to get the active element. You can also use document.hasFocus to make sure if the current document focus. Technique 2: aria-activedescendant This technique involves binding a single event handler to the container widget and using the aria-activedescendant to track a "virtual" focus. (For more information about...
Mobile accessibility checklist - Accessibility
It is intended to continuously evolve as more patterns arise. Colour Colour contrast MUST comply with WCAG 2.1 AA level requirements: Contrast ratio of 4.5:1 for normal text (less than 18 point or 14 point bold.) Contrast ratio of 3:1 for large text (at least 18 point or 14 point bold.) Information conveyed via colour MUST be also available by other means too (underlined text for links, etc.) Visibility Content hiding techniques such as zero opacity, z-index order and off-screen placement MUST NOT be used exclusively to handle visibility. ...
...Orientation Examples of when an orientation is esssential is a piano application or a bank cheque. General Guidelines An app title MUST be provided. Headings MUST not break hierarchical structure <h1>Top level heading</h1> <h2>Secondary heading</h2> <h2>Another secondary heading</h2> <h3>Low level heading</h3> ARIA Landmark Roles SHOULD be used to describe an app or document structure, such as banner, complementary, contentinfo, main, navigation, search. For touch events, at least one of the following must be true (WCAG 2.1: Pointer Cancellation): The down-event should not be used to trigger any action The action is triggered on the up event and an option to abort the action before its completion is available or an option to undo the action after its comple...
... ...
:fullscreen - CSS: Cascading Style Sheets
ve been put into full-screen mode, this selects them all. Syntax :fullscreen Usage notes The :fullscreen 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-tog...
... CSS The magic happens in the CSS. There are two rules here. The first establishes the background color of the "Toggle Full-screen Mode" button when the element is not in a full-screen state. The key is the use of the :not(:fullscreen), which looks for the element to not have the :fullscreen pseudo-class applied to it. #fs-toggle:not(:fullscreen) { background-color: #a...
...n mode. CSS The magic happens in the CSS. There are two rules here. The first establishes the background color of the "Toggle Full-screen Mode" button when the element is not in a full-screen state. The key is the use of the :not(:fullscreen), which looks for the element to not have the :fullscreen pseudo-class applied to it. #fs-toggle:not(:fullscreen) { background-color: #afa; } When the document is in full-screen mode, the following CSS applies instead, setting the background color to a pale shade of red. #fs-toggle:fullscreen { background-color: #faa; } Specifications Specification Status Comment Fullscreen APIThe definition of ':fullscreen' in that specification. Living Standard Initial definition. ...
:host() - CSS: Cascading Style Sheets
Web › CSS › :host()
lectors example (see it live also). ...
... example we have a simple custom element -- <context-span> -- that you can wrap around text: <h1>Host selectors <a href="#"><context-span>example</context-span></a></h1> Inside the element's constructor, we create style and span elements, fill the span with the content of the custom element, and fill the style element with some CSS rules: let style = document.createElement('style'); let span = document.createElement('span'); span.textContent = this.textContent; const shadowRoot = this.attachShadow({mode: 'open'}); shadowRoot.appendChild(style); shadowRoot.appendChild(span); style.textContent = 'span:hover { text-decoration: underline; }' + ':host-context(h1) { font-style: italic; }' + ':host-context(h1):after { content: " - no links in headers!" }' + ...
... Specifications Specification Status Comment CSS Scoping Module Level 1The definition of ':host()' in that specification. Working Draft Initial definition. Browser compatibility DesktopMobileChromeEdgeFirefoxInternet ExplorerOpera...
:host-context() - CSS: Cascading Style Sheets
when a .dark-theme class is applied to <body>. Note: This has no effect when used outside a shadow DOM. ...
...lectors example (see it live also). ...
... example we have a simple custom element -- <context-span> -- that you can wrap around text: <h1>Host selectors <a href="#"><context-span>example</context-span></a></h1> Inside the element's constructor, we create style and span elements, fill the span with the content of the custom element, and fill the style element with some CSS rules: let style = document.createElement('style'); let span = document.createElement('span'); span.textContent = this.textContent; const shadowRoot = this.attachShadow({mode: 'open'}); shadowRoot.appendChild(style); shadowRoot.appendChild(span); style.textContent = 'span:hover { text-decoration: underline; }' + ':host-context(h1) { font-style: italic; }' + ':host-context(h1):after { content: " - no links in headers!" }' + ...
:host - CSS: Cascading Style Sheets
Web › CSS › :host
lectors example (see it live also). ...
... example we have a simple custom element -- <context-span> -- that you can wrap around text: <h1>Host selectors <a href="#"><context-span>example</context-span></a></h1> Inside the element's constructor, we create style and span elements, fill the span with the content of the custom element, and fill the style element with some CSS rules: let style = document.createElement('style'); let span = document.createElement('span'); span.textContent = this.textContent; const shadowRoot = this.attachShadow({mode: 'open'}); shadowRoot.appendChild(style); shadowRoot.appendChild(span); style.textContent = 'span:hover { text-decoration: underline; }' + ':host-context(h1) { font-style: italic; }' + ':host-context(h1):after { content: " - no links in headers!" }' + ...
...: " - no links in headers!" }' + ':host-context(article, aside) { color: gray; }' + ':host(.footer) { color : red; }' + ':host { background: rgba(0,0,0,0.1); padding: 2px 5px; }'; The :host { background: rgba(0,0,0,0.1); padding: 2px 5px; } rule styles all instances of the <context-span> element (the shadow host in this instance) in the document. Specifications Specification Status Comment CSS Scoping Module Level 1The definition of ':host' in that specification. Working Draft Initial definition. 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 s...
:scope - CSS: Cascading Style Sheets
Web › CSS › :scope
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 prove to be useful is whe...
...":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. ...
...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. ...
zoom - CSS: Cascading Style Sheets
Web › CSS › @viewport › zoom
<number> A non-negative number used as the zoom factor. <percentage> A non-negative percentage value used as the zoom factor. ...
... <number> A non-negative number used as the zoom factor. <percentage> A non-negative percentage value used as the zoom factor. ...
... @viewport at-rule. A zoom factor of 1.0 or 100% corresponds to no zooming. Larger values are zoomed in. Smaller values are zoomed out. Syntax /* Keyword value */ zoom: auto; /* <number> values */ zoom: 0.8; zoom: 2.0; /* <percentage> values */ zoom: 150%; Values auto The user agent will set the document's initial zoom factor. The user agent may use the size of canvas area on which the document is rendered to determine that factor. <number> A non-negative number used as the zoom factor. <percentage> A non-negative percentage value used as the zoom factor. Formal definition Related at-rule@viewportInitial valueautoPercentagesthe zoom factor itselfComputed valueauto, or a non-negative number or percentage as specified Formal syntax auto | <number> | <percentage> Examples Setti...
CSS Box Alignment - CSS: Cascading Style Sheets
Older alignment methods CSS traditionally had very limited alignment capabilities. ...
... Older alignment methods CSS traditionally had very limited alignment capabilities. ...
... methods. Relationship to writing modes Alignment is linked to writing modes in that when we align an item we do not consider whether we are aligning it to the physical dimensions of top, right, bottom and left. Instead we describe alignment in terms of the start and end of the particular dimension we are working with. This ensures that alignment works in the same way whichever writing mode the document has. Two dimensions of alignment When using the box alignment properties you will align content on one of two axes -- the inline (or main) axis, and the block (or cross) axis. The inline axis is the axis along which words in a sentence flow in the writing mode being used -- for English, for example, the inline axis is horizontal. The block axis is the axis along which blocks, such as paragraph ...
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
operty behaves when we are working by column. As before, we need enough space in the cross axis to have some free space after displaying all of the items. Note: the value space-evenly is not defined in the flexbox specification and is a later addition to the Box Alignment specification. Browser support for this value is not as good as that of the values defined in the flexbox spec. See the documentation for justify-content on MDN for more details on all of these values and browser support. Aligning content on the main axis Now that we have seen how alignment works on the cross axis, we can take a look at the main axis. Here we only have one property available to us -- justify-content. This is because we are only dealing with items as a group on the main axis. With justify-content we contr...
... In a left to right language the items all line up on the left. Try changing flex-direction: row-reverse to flex-direction: row. You will see that the items now move to the right hand side. While this may all seem a little confusing, the rule to remember is that unless you do something to change it, flex items lay themselves out in the direction that words are laid out in the language of your document along the inline, row axis. flex-start will be where the start of a sentence of text would begin. You can switch them to display in the block direction for the language of your document by selecting flex-direction: column. Then flex-start will then be where the top of your first paragraph of text would start. If you change flex-direction to one of the reverse values, then they will lay them...
...flex-start will then change to the end of that axis -- so to the location where your lines would wrap if working in rows, or at the end of your last paragraph of text in the block direction. ...
Block and inline layout in normal flow - CSS: Cascading Style Sheets
ng at the top of a containing block. Horizontal margins, borders, and padding are respected between these boxes. The boxes may be aligned vertically in different ways: their bottoms or tops may be aligned, or the baselines of text within them may be aligned. The rectangular area that contains the boxes that form a line is called a line box." - 9.4.2 Note that the CSS 2.1 specification describes documents as being in a horizontal, top to bottom writing mode. For example, by describing vertical distance between block boxes. The behavior on block and inline elements is the same when working in a vertical writing mode, and we will explore this in a future guide on Flow Layout and Writing Modes. Elements participating in a block formatting context Block elements in a horizontal writing mode such as...
...Layout and Writing Modes. Elements participating in a block formatting context Block elements in a horizontal writing mode such as English, layout vertically, one below the other. In a vertical writing mode then would lay out horizontally. In this guide, we will be working in English and therefore a horizontal writing mode. However, everything described should work in the same way if your document is in a vertical writing mode. As defined in the specification, the margins between two block boxes are what creates separation between the elements. We see this with a very simple layout of two paragraphs, to which I have added a border. The default browser stylesheet adds spacing between the paragraphs by way of adding a margin to the top and bottom. If we set margins on the paragraph eleme...
...ments to display as block elements, you could do so by setting display: block on <strong>. This means that you can always use most of the semantic HTML elements to markup your content, and then change the way it displays using CSS. Summary In this guide, we have looked at how elements display in normal flow, as block and inline elements. Due to the default behaviour of these elements, an HTML document with no CSS styling at all, will display in a readable way. By understanding how normal flow works you will find layout easier, as you understand the starting point for making changes to how elements are displayed. See Also CSS Basic Box Model Normal Flow - Learn Layout Inline elements Block-level elements ...
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
color: #d9480f; } <div class="wrapper"> <div>One</div> <div>Two</div> <div>Three</div> <div>Four</div> <div>Five</div> <div>Six</div> <div>Seven</div> <div>Eight</div> </div> The order of auto placed items A grid can contain a mixture of items. Some of the items may have a position on the grid, but others may be auto-placed. ...
... the grid, but others may be auto-placed. This can be helpful, if you have a document order that reflects the order in which items sit on the grid you may not need to write CSS rules to place absolutely everything. The specification contains a long section detailing the Grid item placement algorithm, however for most of us we just need to remember a few simple rules for our items. Order modified document order Grid places items that have not been given a grid position in what is described in the specification as "order modified document order". This means that if you have used the order property at all, the items will be placed by that order, not their DOM order. Otherwise they will stay by default in the order that they are entered in the document source. Items with placement properties The f...
... values grid-auto-flow: column dense. Having done this, grid will now backfill the gaps, as it moves through the grid it leaves gaps as before, but then if it finds an item that will fit in a previous gap it will pick it up and take it out of DOM order to place it in the gap. As with any other reordering in grid this does not change the logical order. Tab order for example, will still follow the document order. We will take a look at the potential accessibility issues of Grid Layout in a later guide, but you should take care when creating this disconnect between the visual order and display order. * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px;...
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
the right, rather than the left. Browsers are pretty good at dealing with text direction, and you don't even need to be working in a rtl language to take a look. In the example below, I have two paragraphs. One has no text-align property set, the second has text-align set to left. I have added dir="rtl" to the html element, which switches the writing mode from the default for an English language document of ltr. You can see that the first paragraph remains left to right, due to the text-align value being left . The second however, switches direction and the text runs from right to left . This is a very simple example of the problem with physical values and properties being used in CSS. They prevent the browser being able to do the work to switch writing mode, as they make the assumption that t...
... right to left text, and the writing-mode property helps us display text running in other directions. The writing-mode property can have values of: horizontal-tb vertical-rl vertical-lr sideways-rl sideways-lr The value horizontal-tb is the default for text on the web. It is the direction in which you are reading this guide. The other properties will change the way that text flows in our document, matching the different writing modes found around the world. Again, for full details of these see Jen's article. As a simple example, I have two paragraphs below. The first uses the default horizontal-tb, and the second uses vertical-rl. In the mode text still runs left to right, however the direction of the text is vertical - inline text now runs down the page, from top to bottom. .wrapper >...
...ish, in left-to-right means the order is: top left bottom right This is anti-clockwise! So the reverse of what we do for margins and padding. Once you realize that grid-area sees the world as "block and inline", you can remember that we are setting the two starts, then the two ends. It becomes much more logical once you know! Mixed writing modes and grid layout In addition to displaying documents, using the correct writing mode for the language, writing modes can be used creatively within documents that are otherwise ltr. In this next example I have a grid layout with a set of links down one side. I've used writing modes to turn these on their side in the column track: .wrapper { display: grid; grid-gap: 20px; grid-template-columns: 1fr auto; font: 1em Helvetica, Arial,...
CSS selectors - CSS: Cascading Style Sheets
SS selectors define the elements to which a set of CSS rules apply. Note: There are no selectors or combinators to select parent items, siblings of parents, or children of parent siblings. Basic selectors Universal selector Selects all elements. Optionally, it may be restricted to a specific namespace or to all namespaces. Syntax: * ns|* *|* Example: * will match all the elements of the document. Type selector Selects all elements that have the given node name. Syntax: elementname Example: input will match any <input> element. Class selector Selects all elements that have the given class attribute. Syntax: .classname Example: .index will match any element that has a class of "index". ID selector Selects an element based on the value of its id attribute. There should be only one...
...elements that have the given node name. Syntax: elementname Example: input will match any <input> element. Class selector Selects all elements that have the given class attribute. Syntax: .classname Example: .index will match any element that has a class of "index". ID selector Selects an element based on the value of its id attribute. There should be only one element with a given ID in a document. Syntax: #idname Example: #toc will match the element that has the ID "toc". Attribute selector Selects all elements that have the given attribute. Syntax: [attr] [attr=value] [attr~=value] [attr|=value] [attr^=value] [attr$=value] [attr*=value] Example: [autoplay] will match all elements that have the autoplay attribute set (to any value). Grouping selectors Selector list The , is a ...
...ntax: A + B Example: h2 + p will match all <p> elements that directly follow an <h2>. Column combinator The || combinator selects nodes which belong to a column. Syntax: A || B Example: col || td will match all <td> elements that belong to the scope of the <col>. Pseudo Pseudo classes The : pseudo allow the selection of elements based on state information that is not contained in the document tree. Example: a:visited will match all <a> elements that have been visited by the user. Pseudo elements The :: pseudo represent entities that are not included in HTML. Example: p::first-line will match the first line of all <p> elements. Specifications Specification Status Comment Selectors Level 4 Working Draft Added the || column combinator, grid struct...
Syntax - CSS: Cascading Style Sheets
Web › CSS › Syntax
e diagram below. Note: The content of a CSS declaration block, that is a list of semi-colon-separated declarations, without the initial and closing braces, can be put inside an HTML style attribute. CSS rulesets If style sheets could only apply a declaration to each element of a Web page, they would be pretty useless. The real goal is to apply different declarations to different parts of the document. CSS allows this by associating conditions with declarations blocks. Each (valid) declaration block is preceded by one or more comma-separated selectors, which are conditions selecting some elements of the page. A selector group and an associated declarations block, together, are called a ruleset, or often simply a rule. A CSS ruleset (or rule) is visualized in the diagram below. As an eleme...
...CIAL AT), followed by an identifier and then continuing up to the end of the statement, that is up to the next semi-colon (;) outside of a block, or the end of the next block. Each type of at-rules, defined by the identifier, may have its own internal syntax, and semantics of course. They are used to convey meta-data information (like @charset or @import), conditional information (like @media or @document), or descriptive information (like @font-face). Any statement which isn't a ruleset or an at-rule is invalid and ignored. There is another group of statements - the nested statements. These are statements that can be used in a specific subset of at-rules - the conditional group rules. These statements only apply if a specific condition is matched: the @media at-rule content is applied only if ...
...t a ruleset or an at-rule is invalid and ignored. There is another group of statements - the nested statements. These are statements that can be used in a specific subset of at-rules - the conditional group rules. These statements only apply if a specific condition is matched: the @media at-rule content is applied only if the device on which the browser runs matches the expressed condition; the @document at-rule content is applied only if the current page matches some conditions, and so on. In CSS1 and CSS2.1, only rulesets could be used inside conditional group rules. That was very restrictive and this restriction was lifted in CSS Conditionals Level 3. Now, though still experimental and not supported by every browser, conditional group rules can contain a wider range of content: rulesets but al...
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
They are set using custom property notation (e.g., --main-color: black;) and are accessed using the var() function (e.g., color: var(--main-color);). Complex websites have very large amounts of CSS, often with a lot of repeated values. For example, the same color might be used in hundreds of different places, requiring global search and replace if that color needs to change. ...
... and a property value that can be any valid CSS value. Like any other property, this is written inside a ruleset, like so: element { --main-bg-color: brown; } Note that the selector given to the ruleset defines the scope that the custom property can be used in. A common best practice is to define custom properties on the :root pseudo-class, so that it can be applied globally across your HTML document: :root { --main-bg-color: brown; } However, this doesn't always have to be the case: you maybe have a good reason for limiting the scope of your custom properties. Note: Custom property names are case sensitive -- --my-color will be treated as a separate custom property to --My-color. As mentioned earlier, you use the custom property value by specifying your custom property name inside th...
...h leads us to this: Notice the repetition in the CSS. The background color is set to brown in several places. For some CSS declarations, it is possible to declare this higher in the cascade and let CSS inheritance solve this problem naturally. For non-trivial projects, this is not always possible. ...
font-kerning - CSS: Cascading Style Sheets
d ::first-line.InheritedyesComputed valueas specifiedAnimation typediscrete Formal syntax auto | normal | none Examples Enabling and disabling kerning HTML <div id="kern"></div> <div id="nokern"></div> <textarea id="input">AV T. ...
...cifiedAnimation typediscrete Formal syntax auto | normal | none Examples Enabling and disabling kerning HTML <div id="kern"></div> <div id="nokern"></div> <textarea id="input">AV T. ...
...uto | normal | none Examples Enabling and disabling kerning HTML <div id="kern"></div> <div id="nokern"></div> <textarea id="input">AV T. ...
grid-auto-flow - CSS: Cascading Style Sheets
"row" : "column"; if (dense.checked) { gridAutoFlow += " dense"; } grid.style.gridAutoFlow = gridAutoFlow; } Result Specifications Specification Status Comment CSS Grid LayoutTh...
..."row" : "column"; if (dense.checked) { gridAutoFlow += " dense"; } grid.style.gridAutoFlow = gridAutoFlow; } Result Specifications Specification Status Comment CSS Grid LayoutThe definition of 'grid-auto-flow' in that specificat...
... Candidate Recommendation Initial definiti...
Specified value - CSS: Cascading Style Sheets
If none of the above pertain, the element's initial value will be used. ...
... If none of the above pertain, the element's initial value will be used. ...
... If none of the above pertain, the element's initial value will be used. ...
Content categories - Developer guides
in a specific context. Note: A more detailed discussion of these content categories and their comparative functionalities is beyond the scope of this article; for that, you may wish to read the relevant portions of the HTML specification. Main content categories Metadata content Elements belonging to the metadata content category modify the presentation or the behavior of the rest of the document, set up links to other documents, or convey other out of band information. Elements belonging to this category are <base>, <command>, <link>, <meta>, <noscript>, <script>, <style> and <title>. Flow content Elements belonging to the flow content category typically contain text or embedded content. They are: <a>, <abbr>, <address>, <article>, <aside>, <audio>, <b>,<bdo>, <bdi>, <blockquote>, <b...
...f it is a descendant of a <map> element <del>, if it contains only phrasing content <ins>, if it contains only phrasing content <link>, if the itemprop attribute is present <map>, if it contains only phrasing content <meta>, if the itemprop attribute is present Embedded content Embedded content imports another resource or inserts content from another mark-up language or namespace into the document. Elements that belong to this category include: <audio>, <canvas>, <embed>, <iframe>, <img>, <math>, <object>, <picture>, <svg>, <video>. Interactive content Interactive content includes elements that are specifically designed for user interaction. Elements that belong to this category include: <a>, <button>, <details>, <embed>, <iframe>, <keygen>, <label>, <select>, and <textarea>. Some elem...
...ect>, and <textarea>. resettable Elements that can be affected when a form is reset. Contains <input>, <keygen>, <output>,<select>, and <textarea>. Secondary categories There are some secondary classifications of elements that can be useful to be aware of as well. Script-supporting elements Script-supporting elements are elements which don't directly contribute to the rendered output of a document. Instead, they serve to support scripts, either by containing or specifying script code directly, or by specifying data that will be used by scripts. The script-supporting elements are: <script> <template> Transparent content model If an element has a transparent content model, then its contents must be structured such that they would be valid HTML 5, even if the transparent element were ...
Index - Developer guides
Web › Guide › Index
them here. 4 Getting Started AJAX, API, Advanced, JavaScript, WebMechanics, XMLHttpRequest This article guides you through the AJAX basics and gives you some simple hands-on examples to get you started. 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. 6 Audio and Video Delivery Audio, Guide, HTML, HTML5, Media, Video Whether we are dealing with pre-recorded audio files or live streams, the mechanism for making them available through the browser's <audio> and <video> elements remains pretty much the same. Currently, to support all browsers we need to specify two formats, although with the adoption of MP3 and MP4 formats in...
... browser itself. 19 DOM onevent handlers Beginner, DOM, DOM Beginner, NeedsBeginnerUpdate, NeedsUpdate The Web platform provides several ways to be notified of DOM events. Two common approaches are addEventListener() and the specific onevent handlers. 20 Media events Intermediate, Media Various events are sent when handling media that are embedded in HTML documents using the <audio> and <video> elements; this section lists them and provides some helpful information about using them. 21 Mouse gesture events Advanced, DOM Gecko 1.9.1 added support for several Mozilla-specific DOM events used to handle mouse gestures. These are special movements that can be made with a mouse or trackpad and can be interpreted to perform specific tasks. ...
...our content perform well. That is, to make it work quickly and efficiently. This lets it work effectively both for users of powerful desktop systems as well as for handheld devices with less power. There are several tools available to check the performance of a website or blog. The most notable tools are listed below. 37 Parsing and serializing XML AJAX, Add-ons, DOM, DOM Parsing, Document, Extensions, Guide, HTMLDocument, JSON, Parsing, Parsing XML, Serializing, Serializing XML, XML, XMLDocument, XMLHttpRequest In this article, we'll look at the objects provided by the web platform to make the common tasks of serializing and parsing XML easy. 38 Printing DOM, Guide, NeedsContent, NeedsRelocation, printing There may be times in which your web site or appl...
HTML attribute: accept - HTML: Hypertext Markup Language
a thorough set of type specifiers when you need files of specific type, or use the wild card to denote a type of any format is acceptable. ...
...ecifiers when you need files of specific type, or use the wild card to denote a type of any format is acceptable. ...
...me examples: accept="image/png" or accept=".png" -- Accepts PNG files. accept="image/png, image/jpeg" or accept=".png, .jpg, .jpeg" -- Accept PNG or JPEG files. accept="image/*" -- Accept any file with an image/* MIME type. (Many mobile devices also let the user take a picture with the camera when this is used.) accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" -- accept anything that smells like an MS Word document. Let's look at a more complete example: <form method="post" enctype="multipart/form-data"> <div> <label for="profile_pic">Choose file to upload</label> <input type="file" id="profile_pic" name="profile_pic" accept=".jpg, .jpeg, .png"> </div> <div> <button>Submit</button> </div> </fo...
<embed>: The Embed External Content element - HTML: Hypertext Markup Language
Web › HTML › Element › embed
It does not address earlier, non-standardized implementation of the element. ...
...It does not address earlier, non-standardized implementation of the element. Keep in mind that most modern browsers have deprecated and removed support for browser plug-ins, so relying upon <embed> is generally not wise if you want your site to be operable on the average user's browser. ...
... Flow content, phrasing content, embedded content, interactive content, palpable content. Permitted content None, it is an empty element. Tag omission Must have a start tag, and must not have an end tag. Permitted parents Any element that accepts embedded content. Implicit ARIA role No corresponding role Permitted ARIA roles application, document, img, none, presentation DOM interface HTMLEmbedElement Attributes This element's attributes include the global attributes. height The displayed height of the resource, in CSS pixels. This must be an absolute value; percentages are not allowed. src The URL of the resource being embedded. type The MIME type to use to select the plug-in to instantiate. width The displa...
<input type="checkbox"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › checkbox
cked 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 recipe is not yet complete. ...
...x 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 recipe is not yet complete. ...
...Value" name="other"> </div> <div> <button type="submit">Submit form</button> </div> </fieldset> </form> CSS html { font-family: sans-serif; } form { width: 600px; margin: 0 auto; } div { margin-bottom: 10px; } fieldset { background: cyan; border: 5px solid blue; } legend { padding: 10px; background: blue; color: cyan; } JavaScript var otherCheckbox = document.querySelector('input[value="other"]'); var otherText = document.querySelector('input[id="otherValue"]'); otherText.style.visibility = 'hidden'; otherCheckbox.addEventListener('change', () => { if(otherCheckbox.checked) { otherText.style.visibility = 'visible'; otherText.value = ''; } else { otherText.style.visibility = 'hidden'; } }); Specifications Specification ...
<input type="number"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › number
this input placeholder An example value to display inside the field when it's empty readonly A Boolean attribute indicating whether the value is read-only step A stepping interval to use when using up and down arrows to adjust the value, as well as for validation list The values of the list attribute is the id of a <datalist> element located in the same document. The <datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. max The maximum value to accept for this input. If the value entered into...
...before; nothing remarkable here. ...
...osition: 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; } And finally, the JavaScript: let metersInputGroup = document.querySelector('.metersInputGroup'); let feetInputGroup = document.querySelector('.feetInputGroup'); let metersInput = document.querySelector('#meters'); let feetInput = document.querySelector('#feet'); let inchesInput = document.querySelector('#inches'); let switchBtn = document.querySelector('input[type="button"]'); switchBtn.addEventListener('click', function() { if(switchBtn.getAttribute('class') === 'meters') { switchBtn.setAttribute('class', 'feet')...
<isindex> - HTML: Hypertext Markup Language
Web › HTML › Element › isindex
<isindex> provided a single line text input for entering a query string. When sent, the server would return a list of pages matching the query. Its support depended on both the browser and the server to react to the query. <isindex> is removed HTML Standard. It was deprecated in HTML 4.01. The same behaviour can be achieved with an HTML form. All major browsers have now removed <isindex>. Attributes Like all other HTML elements, this element accepted the global attributes. prompt This attribute added its value as a prompt for text field. ...
...ted in HTML 4.01. The same behaviour can be achieved with an HTML form. All major browsers have now removed <isindex>. Attributes Like all other HTML elements, this element accepted the global attributes. prompt This attribute added its value as a prompt for text field. action This attribute determined the server URL to which the query was sent. Example <head> <isindex prompt="Search Document..." action="/search"> </head> In past browsers, this would generate, at parse time, a DOM tree equivalent to the following HTML: <form action="/search"> <hr> <label> Search Document... <input name="isindex"> </label> <hr> </form> History On June 1992, Dan Connolly would prefer a different anchor type instead of isindex. On November 1992, indexes as links rather than document...
...In this thread, different type of solutions are proposed. ...
<section>: The Generic Section element - HTML: Hypertext Markup Language
Web › HTML › Element › section
Typically, but not always, sections have a heading. 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. ...
...g and ending tag are mandatory. Permitted parents Any element that accepts flow content. Note that a <section> element must not be a descendant of an <address> element. Implicit ARIA role region if the element has an accessible name, otherwise no corresponding role Permitted ARIA roles alert, alertdialog, application, banner, complementary, contentinfo, dialog, document, feed, log, main, marquee, navigation, none, note, presentation, search, status, tabpanel DOM interface HTMLElement Attributes This element only includes the global attributes. Usage notes Each <section> should be identified, typically by including a heading (<h1>-<h6> element) as a child of the <section> element. If it makes sense to separately syndicate the content of a...
...ading (<h1>-<h6> element) as a child of the <section> element. If it makes sense to separately syndicate the content of a <section> element, use an <article> element instead. Do not use the <section> element as a generic container; this is what <div> is for, especially when the sectioning is only for styling purposes. A rule of thumb is that a section should logically appear in the outline of a document. Example Before <div> <h1>Heading</h1> <p>Bunch of awesome content</p> </div> After <section> <h1>Heading</h1> <p>Bunch of awesome content</p> </section> Specifications Specification Status Comment HTML Living StandardThe definition of '<section>' in that specification. Living Standard HTML 5.1The definition of '<section>' in that speci...
<textarea> - HTML: Hypertext Markup Language
Web › HTML › Element › textarea
omatically capitalize the first letter of words. characters: Automatically capitalize all characters. on: Deprecated since iOS 5. off: Deprecated since iOS 5. autocomplete This attribute indicates whether the value of the control can be automatically completed by the browser. Possible values are: off: The user must explicitly enter a value into this field for every use, or the document provides its own auto-completion method; the browser does not automatically complete the entry. on: The browser can automatically complete the value based on values that the user has entered during previous uses. If the autocomplete attribute is not specified on a <textarea> element, then the browser uses the autocomplete attribute value of the <textarea> element's form owner. The form owne...
... The form owner is either the <form> element that this <textarea> element is a descendant of or the form element whose id is specified by the form attribute of the input element. For more information, see the autocomplete attribute in <form>. autofocus This Boolean attribute lets you specify that a form control should have input focus when the page loads. Only one form-associated element in a document can have this attribute specified. cols The visible width of the text control, in average character widths. If it is specified, it must be a positive integer. If it is not specified, the default value is 20. disabled This Boolean attribute indicates that the user cannot interact with the control. If this attribute is not specified, the control inherits its setting from the containing element...
...ct with the control. If this attribute is not specified, the control inherits its setting from the containing element, for example <fieldset>; if there is no containing element when the disabled attribute is set, the control is enabled. form The form element that the <textarea> element is associated with (its "form owner"). The value of the attribute must be the id of a form element in the same document. If this attribute is not specified, the <textarea> element must be a descendant of a form element. This attribute enables you to place <textarea> elements anywhere within a document, not just as descendants of form elements. maxlength The maximum number of characters (UTF-16 code units) that the user can enter. If this value isn't specified, the user can enter an unlimited number of characters...
<track>: The Embed Text Track element - HTML: Hypertext Markup Language
Web › HTML › Element › track
be used when the user is navigating the media resource. metadata Tracks used by scripts. Not visible to the user. label A user-readable title of the text track which is used by the browser when listing available text tracks. src Address of the track (.vtt file). Must be a valid URL. This attribute must be specified and its URL value must have the same origin as the document -- unless the <audio> or <video> parent element of the track element has a crossorigin attribute. srclang Language of the track text data. It must be a valid BCP 47 language tag. If the kind attribute is set to subtitles, then srclang must be defined. Usage notes Track data types The type of data that track adds to the media is set in the kind attribute, which can take values of subtitles, ...
...rlying TextTrack, indicated by the track property, receives a cuechange event every time the currently-presented cue is changed. This happens even if the track isn't associated with a media element. If the track is associated with a media element, using the <track> element as a child of the <audio> or <video> element, the cuechange event is also sent to the HTMLTrackElement. ...
...ted with a media element, using the <track> element as a child of the <audio> or <video> element, the cuechange event is also sent to the HTMLTrackElement. ...
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
You can use <video> for audio content as well, but the <audio> element may provide a more appropriate user experience. 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. The above example shows simple usage of the <video> element. ...
...he attribute is there in the <video> tag at all. To remove autoplay, the attribute needs to be removed altogether. In some browsers (e.g. Chrome 70.0) autoplay doesn't work if no muted attribute is present. autoPictureInPicture A Boolean attribute which if true indicates that the element should automatically toggle picture-in-picture mode when the user switches back and forth between this document and another document or application. buffered An attribute you can read to determine the time ranges of the buffered media. This attribute contains a TimeRanges object. controls If this attribute is present, the browser will offer controls to allow the user to control video playback, including volume, seeking, and pause/resume playback. controlslist The controlslist attribute, when specif...
...eoTracks Add an addtrack listener to this VideoTrackList object to be informed when video tracks are added to the element. HTMLMediaElement.textTracks Add an addtrack event listener to this TextTrackList to be notified when new text tracks are added to the element. ...
contextmenu - HTML: Hypertext Markup Language
</menu> </li> </ol> </body> JavaScript function shareViaTwitter() { window.open("https://twitter.com/intent/tweet?text=" + "Hurray! ...
...("https://twitter.com/intent/tweet?text=" + "Hurray! ...
... Recommendation Snapshot of HTML Living Standard, initial definition. ...
Feature Policy - HTTP
s restrict what APIs the site can access or modify the browser's default behavior for certain features. Examples of what you can do with Feature Policy: Change the default behavior of autoplay on mobile and third party videos. Restrict a site from using sensitive APIs like camera or microphone. Allow iframes to use the fullscreen API. Block the use of outdated APIs like synchronous XHR and document.write(). Ensure images are sized properly and are not too big for the viewport. Concepts and usage Feature Policy allows you to control which origins can use which features, both in the top-level page and in embedded frames. Essentially, you write a policy, which is an allowed list of origins for each feature. For every feature controlled by Feature Policy, the feature is only enabled in the ...
.... Ensure images are sized properly and are not too big for the viewport. Concepts and usage Feature Policy allows you to control which origins can use which features, both in the top-level page and in embedded frames. Essentially, you write a policy, which is an allowed list of origins for each feature. For every feature controlled by Feature Policy, the feature is only enabled in the current document or frame if its origin matches the allowed list of origins. For each policy-controlled feature, the browser maintains a list of origins for which the feature is enabled, known as an allowlist. If you do not specify a policy for a feature, then a default allowlist will be used. The default allowlist is specific to each feature. Writing a policy A policy is described using a set of individual po...
...difference between the HTTP header and the allow attribute is that the allow attribute only controls features within an iframe. The header controls features in the response and any embedded content within the page. For more details see Using Feature Policy. Inferring the policy Scripts can programatically query information about the feature policy via the FeaturePolicy object located at either Document.featurePolicy or HTMLIFrameElement.featurePolicy. Types of policy-controlled features Though Feature Policy provides control of multiple features using a consistent syntax, the behavior of policy controlled features varies and depends on several 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 featu...
Feature-Policy: accelerometer - HTTP
The HTTP Feature-Policy header accelerometer directive controls whether the current document is allowed to gather information about the acceleration of the device through the Accelerometer interface. Syntax Feature-Policy: accelerometer <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The default value is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. AccelerometerThe definition of 'Accelerometer' in that specification. Candidate Recommendation ...
Feature-Policy: ambient-light-sensor - HTTP
The HTTP Feature-Policy header ambient-light-sensor directive controls whether the current document is allowed to gather information about the amount of light in the environment around the device through the AmbientLightSensor interface. Syntax Feature-Policy: ambient-light-sensor <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The default value is 'self'. Specification Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Feature-Policy: autoplay - HTTP
The HTTP Feature-Policy header autoplay directive controls whether the current document is allowed to autoplay media requested through the HTMLMediaElement interface. When this policy is enabled and there were no user gestures, the Promise returned by HTMLMediaElement.play() will reject with a DOMException. The autoplay attribute on <audio> and <video> elements will be ignored. For more details on autoplay and autoplay blocking, see the article Autoplay guide for media and Web Audio APIs. Syntax Feature-Policy: autoplay <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The ...
...ing, see the article Autoplay guide for media and Web Audio APIs. Syntax Feature-Policy: autoplay <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (f...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The default value in Google Chrome is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Feature-Policy: battery - HTTP
The HTTP Feature-Policy header battery directive controls whether the current document is allowed to gather information about the acceleration of the device through the BatteryManager interface obtained via Navigator.getBattery(). Syntax Feature-Policy: battery <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The default value is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. Battery Status APIThe definition of 'Feature Policy integration' in that specification. Candidate Recom...
Feature-Policy: camera - HTTP
The HTTP Feature-Policy header camera directive controls whether the current document is allowed to use video input devices. When this policy is enabled, the Promise returned by MediaDevices.getUserMedia() will reject with a NotAllowedError. Syntax Feature-Policy: camera <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The default value is 'self'. Specification Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Feature-Policy: display-capture - HTTP
The HTTP Feature-Policy header display-capture directive controls whether or not the document is permitted to use Screen Capture API, i.e.,getDisplayMedia() to capture the screen's contents. If display-capture is disabled in a document, the document will not be able to initiate screen capture via getDisplayMedia(). Syntax Feature-Policy: display-capture <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed ...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The default alowlist is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. Screen CaptureThe definition of 'display-capture' in that specification. Working Draft Feature po...
Feature-Policy: magnetometer - HTTP
The HTTP Feature-Policy header magnetometer directive controls whether the current document is allowed to gather information about the orientation of the device through the Magnetometer interface. Syntax Feature-Policy: magnetometer <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. The default value is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Feature-Policy: microphone - HTTP
The HTTP Feature-Policy header microphone directive controls whether the current document is allowed to use audio input devices. When this policy is enabled, the Promise returned by MediaDevices.getUserMedia() will reject with a NotAllowedError. Syntax Feature-Policy: microphone <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. The default value is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Feature-Policy: midi - HTTP
The HTTP Feature-Policy header midi directive controls whether the current document is allowed to use the Web MIDI API. When this policy is enabled, the Promise returned by Navigator.requestMIDIAccess() will reject with a DOMException. Syntax Feature-Policy: midi <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The allow list is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Feature-Policy: payment - HTTP
The HTTP Feature-Policy header field's payment directive controls whether the current document is allowed to use the Payment Request API. When this policy is disabled, the PaymentRequest() constructor will throw a SyntaxError. Syntax Feature-Policy: payment <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The payment feature's default allowlist value is 'self'. Specifications Specification Status Comment Payment Request API Candidate Recommendation See Section 16. Feature Policy integration. Feature Policy Editor's Draft Ini...
Feature-Policy: publickey-credentials-get - HTTP
The HTTP Feature-Policy header publickey-credentials-get directive controls whether the current document is allowed to access Web Authentcation API to create new public-key credentials, i.e, via navigator.credentials.get({publicKey: ..., ...}). When this policy is enabled, any attempt to query public key credentials will result in an error. Syntax Feature-Policy: publickey-credentials-get <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allo...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The default allowlist is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. Web Authentication Level 2 Editor's draft. Definition of publickey-credentials-get directive, de...
Feature-Policy: screen-wake-lock - HTTP
Note: This API is still actively being developed and available only behind a flag on select browsers and platforms. The HTTP Feature-Policy header screen-wake-lock directive controls whether the current document is allowed to use Screen Wake Lock API to indicate that device should not dim or turn off the screen. Note: In earlier specification drafts this directive was called wake-lock. ...
...ent is allowed to use Screen Wake Lock API to indicate that device should not dim or turn off the screen. Note: In earlier specification drafts this directive was called wake-lock. Syntax Feature-Policy: screen-wake-lock <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': T...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy Default allow list for screen-wake-lock is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. Screen Wake Lock API Editor's Draft Initial definition of screen-wake-lock fea...
Feature-Policy: unsized-media - HTTP
The HTTP Feature-Policy header unsized-media directive controls whether the current document is allowed to change the size of media elements after the initial layout is complete. This restriction solves "layout instability" problem caused by providing default dimensions for images whose size is not specified in advance so that image doesn't change size after loading. Syntax Feature-Policy: unsized-media <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an ifra...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default value The default value for unsized-media is '*', that is unsized media elements are allowed for all origins by default. The page will re-flow every time an image with unknown dimensions is loaded. Specifications Specification Status Comment Feature P...
Feature-Policy: wake-lock - HTTP
Note: This API is still actively being developed and available only behind a flag on select browsers and platforms. The HTTP Feature-Policy header wake-lock directive controls whether the current document is allowed to use Wake Lock API to indicate that device should not enter power-saving mode. Note: Latest drafts of Screen Wake Lock API defines screen-wake-lock directive. Syntax Feature-Policy: wake-lock <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy Default allow list for wake-lock is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. Wake Lock API 1 Candidate Recommendation Initial definition of wake-lock feature dire...
web-share - HTTP
The HTTP Feature-Policy header web-share directive controls controls whether the current document is allowed to use the Navigator.share() of Web Share API to share text, links, images, and other content to arbitrary destiations of user's choice. Syntax Feature-Policy: web-share <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
... 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)>: The feature is allowed for specific origins (for example, https://example.com). Origins should be separated by a space. ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The default value is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. Web Share API Draft ...
Feature-Policy: xr-spatial-tracking - HTTP
The HTTP Feature-Policy header xr-spatial-tracking directive controls whether the current document is allowed to use the WebXR Device API. This policy controls whether navigator.xr.requestSession() can return XRSession that requires spatial tracking and whether user agent can indicate support for sessions supporting spatial tracking via navigator.xr.isSessionSupported() and devicechange event on navigator.xr object. ...
...l tracking and whether user agent can indicate support for sessions supporting spatial tracking via navigator.xr.isSessionSupported() and devicechange event on navigator.xr object. Syntax Feature-Policy: xr-spatial-tracking <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': T...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The default allowlist is 'self'. Specifications Specification Status Comment WebXR Device APIThe definition of 'Permissions Policy' in that specification. Working Draft ...
Sec-Fetch-Dest - HTTP
The Sec-Fetch-Dest fetch metadata header indicates the request's destination, that is how the fetched data will be used. ...
...l be used. ...
...fest Sec-Fetch-Dest: nested-document Sec-Fetch-Dest: object Sec-Fetch-Dest: paintworklet Sec-Fetch-Dest: report Sec-Fetch-Dest: script Sec-Fetch-Dest: serviceworker Sec-Fetch-Dest: sharedworker Sec-Fetch-Dest: style Sec-Fetch-Dest: track Sec-Fetch-Dest: video Sec-Fetch-Dest: worker Sec-Fetch-Dest: xslt Sec-Fetch-Dest: audioworklet Sec-Fetch-Dest: audioworklet Values audio audioworklet document embed empty font image manifest object paintworklet report script serviceworker sharedworker style track video worker xslt nested-document Examples TODO Specifications Specification Title Fetch Metadata Request Headers The Sec-Fetch-Dest HTTP Request Header ...
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. ...
...ages can see an improvement of 5% or more in the time of loading images. Configuring prefetching in the browser In general, you don't need to do anything to manage prefetching. However, the user may wish to disable prefetching. On Firefox, this can be done by setting the network.dns.disablePrefetch preference to true. ...
...etting the network.dns.disablePrefetch preference to true. Also, by default, prefetching of embedded link hostnames is not performed on documents loaded over HTTPS. On Firefox, this can be changed by setting the network.dns.disablePrefetchFromHTTPS preference to false. Examples Turning on and off prefetching You can either send the X-DNS-Prefetch-Control header server-side, or from individual documents, using the http-equiv attribute on the <meta> element, like this: <meta http-equiv="x-dns-prefetch-control" content="off"> You can reverse this setting by setting content to "on". Forcing lookup of specific hostnames You can force the lookup of specific hostnames without providing specific anchors using that hostname by using the rel attribute on the <link> element with a link type of dns-p...
HTTP resources and specifications - HTTP
This page lists relevant resources about HTTP. ...
...Modern APIs for application are defines using the RESTful pattern nowadays. Proposed Standard RFC 2324 Hyper Text Coff...
...Modern APIs for application are defines using the RESTful pattern nowadays. Proposed Standard RFC 2324 Hyper Text Coffee Pot Control Protocol (HTCPC...
Indexed collections - JavaScript
alues of an array, processing each one in some way. The simplest way to do this is as follows: let colors = ['red', 'green', 'blue'] for (let i = 0; i < colors.length; i++) { console.log(colors[i]) } If you know that none of the elements in your array evaluate to false in a boolean context--if your array consists only of DOM nodes, for example--you can use a more efficient idiom: let divs = document.getElementsByTagName('div') for (let i = 0, div; div = divs[i]; i++) { /* Process div in some way */ } This avoids the overhead of checking the length of the array, and ensures that the div variable is reassigned to the current item each time around the loop for added convenience. The forEach() method provides another way of iterating over an array: let colors = ['red', 'green', 'blue'] col...
...ult of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of RegExp.exec(), String.match(), and String.split(). For information on using arrays with regular expressions, see Regular Expressions. Working with array-like objects Some JavaScript objects, such as the NodeList returned by document.getElementsByTagName() or the arguments object made available within the body of a function, look and behave like arrays on the surface but do not share all of their methods. The arguments object provides a length attribute but does not implement the forEach() method, for example. Array methods cannot be called directly on array-like objects. function printArguments() { arguments.forEach(func...
... << PreviousNext >> ...
About the JavaScript reference - JavaScript
ript, 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. Structure of the reference In the JavaScript reference you c...
...es 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. Structure of the reference In the JavaScript reference you can find the following chapters: Standard built-in objects This chapter documents all the JavaScript standard built-in objects, along with their methods and properties. Statements and declarations JavaScript applications consist of statements with an appropriate syntax. 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. Expressions and opera...
...t standard built-in objects, along with their methods and properties. Statements and declarations JavaScript applications consist of statements with an appropriate syntax. 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. Expressions and operators This chapter documents all the JavaScript language operators, expressions and keywords. Functions Chapter about JavaScript functions. Classes Chapter about JavaScript classes introduced in ECMAScript 2015. Errors Chapter about specific errors, exceptions and warnings thrown by JavaScript. New in JavaScript Chapter about JavaScript version history. More reference pages Deprecated and obsolete features Lex...
TypeError: "x" is not a function - JavaScript
In this example, Array.prototype.map() is used, which will work with Array objects only...
...In this example, Array.prototype.map() is used, which will work with Array objects only. let obj = {a: 13, b: 37, c: 42}; obj.map(f...
...In this example, Array.prototype.map() is used, which will work with Array objects only. let obj = {a: 13, b: 37, c: 42}; obj.map(function(num) { return num * 2; }); // TypeError: obj.map is not a function Use an array instea...
Error: Permission denied to access property "x" - JavaScript
s when there was an attempt to access an object for which you have no permission. Message Error: Permission denied to access property "x" Error type Error. What went wrong? There was attempt to access an object for which you have no permission. ...
... to access an object for which you have no permission. This is likely an <iframe> element loaded from a different domain for which you violated the same-origin policy. ...
...ly an <iframe> element loaded from a different domain for which you violated the same-origin policy. ...
Promise - JavaScript
nds, at random. The Promise() constructor is used to create the promise. The fulfillment of the promise is simply logged, via a fulfill callback set using p1.then(). A few logs show how the synchronous part of the method is decoupled from the asynchronous completion of the promise. ...
...(You need a browser that supports Promise. ) By clicking the button several times in a short amount of time, you'...
...(You need a browser that supports Promise. ) By clicking the button several times in a short amount of time, you'll even see the different promises being fulfilled one after another. Loading an image with...
SharedArrayBuffer - JavaScript
a() Security requirements Shared memory and high-resolution timers were effectively disabled at the start of 2018 in light of Spectre. In 2020, a new, secure approach has been standardized to re-enable shared memory. ...
...ution timers were effectively disabled at the start of 2018 in light of Spectre. In 2020, a new, secure approach has been standardized to re-enable shared memory. With a few security measures, postMessage() will no longer throw for SharedArrayBuffer objects and shared memory across threads will be available: As a baseline requirement, your document needs to be in a secure context. ...
... beginning. Examples Creating a new SharedArrayBuffer var sab = new SharedArrayBuffer(1024); Slicing the SharedArrayBuffer sab.slice(); // SharedArrayBuffer { byteLength: 1024 } sab.slice(2); // SharedArrayBuffer { byteLength: 1022 } sab.slice(-2); // SharedArrayBuffer { byteLength: 2 } sab.slice(0, 1); // SharedArrayBuffer { byteLength: 1 } Using it in a WebGL buffer const canvas = document.querySelector('canvas'); const gl = canvas.getContext('webgl'); const buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, sab, gl.STATIC_DRAW); Specifications Specification ECMAScript (ECMA-262)The definition of 'SharedArrayBuffer' in that specification. ...
WeakRef - JavaScript
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 proposal included in its explainer document: Garbage collectors are complicated. If an application or library depends on GC cleaning up a WeakRef or calling a finalizer [cleanup callback] in a timely, predictable manner, it's likely to be disappointed: the cleanup may happen much later than expected, or not at all. Sources of variability include: One object might be garbage-collected much sooner than another object, even if they becom...
... ...
... ...
<math> - MathML
Web › MathML › Element › math
Specifications Specification Status Comment ...
... Specifications Specification Status Comment MathML 3.0The definition of 'The Top-Level math Element' in that specification. ...
... Specifications Specification Status Comment MathML 3.0The definition of 'The Top-Level math Element' in that specification. ...
OpenSearch description format
The OpenSearch description format lets a website describe a search engine for itself, so that a browser or other client application can use that search engine. OpenSearch is supported by (at least) Firefox, Edge, Internet Explorer, Safari, and Chrome. (See Reference Material for links to other browsers' documentation.) Firefox also supports additional features not in the OpenSearch standard, such as search suggestions and the <SearchForm> element. This article focuses on creating OpenSearch-compatible search plugins that support these additional Firefox features. OpenSearch description files can be advertised as described in Autodiscovery of search plugins, and can be installed programmatically as described in Adding search engines from web pages. OpenSearch description file The XML file that...
...Thus if a search box is not shown in the user's UI, they will receive no indication. In general, behavior varies among browsers. Supporting automatic updates for OpenSearch plugins OpenSearch plugins can automatically update. To support this, include an extra Url element with type="application/opensearchdescription+xml" and rel="self". The template attribute should be the URL of the OpenSearch document to automatically update to. For example: <Url type="application/opensearchdescription+xml" rel="self" template="https://example.com/mysearchdescription.xml" /> Note: At this time, addons.mozilla.org (AMO) doesn't support automatic updating of OpenSearch plugins. If you want to put your search plugin on AMO, remove the auto-updating feature before submitting it. Troubleshooting Tips...
...emotely fetched favicons must not be larger than 10KB (see bug 361923). In addition, the search plugin service provides a logging mechanism that may be useful to plugin developers. Use about:config to set the pref 'browser.search.log' to true. Then, logging information will appear in Firefox's Error Console (Tools > Error Console) when search plugins are added. Reference Material OpenSearch Documentation Safari 8.0 Release Notes: Quick Website Search Microsoft Edge Dev Guide: Search provider discovery The Chromium Projects: Tab to Search imdb.com has a working osd.xml OpenSearch Plugin Generator Ready2Search - create OpenSearch plugins. Customized Search through Ready2Search ...
Critical rendering path - Web Performance
The document object model is created as the HTML is parsed. The HTML may request JavaScript, which may, in turn, alter the DOM. The HTML includes or makes requests for styles, which in turn builds the CSS object model. ...
...The HTML may request JavaScript, which may, in turn, alter the DOM. ...
...s and building the DOM, until it gets to the end, at which point it constructs the CSS object model. With the DOM and CSSOM complete, the browser builds the render tree, computing the styles for all the visible content. After the render tree is complete, layout occurs, defining the location and size of all the render tree elements. Once complete, the page is rendered, or 'painted' on the screen. Document Object Model DOM construction is incremental. The HTML response turns into tokens which turns into nodes which turn into the DOM Tree. A single DOM node starts with a startTag token and ends with an endTag token. Nodes contain all relevant information about the HTML element. The information is described using tokens. Nodes are connected into a DOM tree based on token hierarchy. If another set of...
Populating the page: how browsers work - Web Performance
obytes. 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 tokenized input into the document, building up the document tree. The DOM tree describes the content of the document. The <html> element is the first tag and root node of the document tree. The tree reflects the relationships and hierarchies between different tags. Tags nested within other tags are child nodes. The great...
...urth step in the critical rending path is running layout on the render tree to compute the geometry of each node. Layout is the process by which the width, height, and location of all the nodes in the render tree are determined, plus the determination of the size and position of each object on the page. Reflow is any subsequent size and position determination of any part of the page or the entire document. Once the render tree is built, layout commences. The render tree identified which nodes are displayed (even if invisible) along with their computed styles, but not the dimensions or location of each node. To determine the exact size and location of each object, the browser starts at the root of the render tree and traverses it. On the web page, most everything is a box. Different devices and d...
...m, will-change, and a few others. These nodes will be painted onto their own layer, along with their descendants, unless a descendant necessitates its own layer for one (or more) of the above reasons. Layers do improve performance, but are expensive when it comes to memory management, so should not be overused as part of web performance optimization strategies. Compositing When sections of the document are drawn in different layers, overlapping each other, compositing is necessary to ensure they are drawn to the screen in the right order and the content is rendered correctly. As the page continues to load assets, reflows can happen (recall our example image that arrived late). A reflow sparks a repaint and a re-composite. Had we defined the size of our image, no reflow would have been necessa...
Structural overview of progressive web apps - Progressive web apps (PWAs)
ecked for errors, and more. In theory, streaming is a better model than the app shell model, but it's also more complex, and the Streams API isn't yet fully supported by any of the major browsers. Once it's available, however, it will be the fastest way to serve your app's content. The performance benefits will be truly spectacular. For working examples and more information, see the Streams API documentation. Structure of a sample application The js13kPWA web site's structure is quite simple. It consists of a single HTML file (index.html), with basic CSS styling provided in style.css. Also included are a few images, scripts, and fonts. The file and folder hierarchy looks like this: app.js data/ games.js img/ favicon.ico fonts/ icons/ img/ bg.png js13kgames.png ind...
... var...
...tById('content').innerHTML = content; Then it registers a service worker: if ("serviceWorker" in navigator) { navigator.serviceWorker.register("/pwa-examples/js13kpwa/sw.js"); } After that, the app adds a handler for clicks on a button whose ID is notifications; this handler requests permission to send notifications to the user, then generates and sends a random notification. ...
requiredFeatures - SVG: Scalable Vector Graphics
http://www.w3.org/TR/SVG11/feature#CoreAttribute The browser supports the id, xml:base, xml:lang and xml:s...
...otLight>, <feFuncR>, <feFuncG>, <feFuncB> and <feFuncA> elements http://www.w3.org/TR/SVG11/feature#BasicFilter The browser supports the <filter>, <feBlend>, <feColorMatrix>, <feComponentTransfer>, <feComposite>, <feFlood>, <feGaussianBlur>, <feImage>, <feMerge>, <feMergeNode>, <feOffset>, <feTile>, <feFuncR>, <feFuncG>, <feFuncB> and <feFuncA> elements http://www.w3.org/TR/SVG11/feature#DocumentEventsAttribute The browser supports the onunload, onabort, onerror, onresize, onscroll and onzoom attributes http://www.w3.org/TR/SVG11/feature#GraphicalEventsAttribute The browser supports the onfocusin, onfocusout, onactivate, onclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout and onload attributes http://www.w3.org/TR/SVG11/feature#AnimationEventsAttribute The...
...r</text> <!-- Testing : http://www.w3.org/TR/SVG11/feature#BasicFilter --> <rect class="ko" x="10" y="810" height="25" width="430" /> <rect class="ok" x="10" y="810" height="25" width="430" requiredFeatures="http://www.w3.org/TR/SVG11/feature#BasicFilter" /> <text x="20" y="827">http://www.w3.org/TR/SVG11/feature#BasicFilter</text> <!-- Testing : http://www.w3.org/TR/SVG11/feature#DocumentEventsAttribute --> <rect class="ko" x="10" y="835" height="25" width="430" /> <rect class="ok" x="10" y="835" height="25" width="430" requiredFeatures="http://www.w3.org/TR/SVG11/feature#DocumentEventsAttribute" /> <text x="20" y="852">http://www.w3.org/TR/SVG11/feature#DocumentEventsAttribute</text> <!-- Testing : http://www.w3.org/TR/SVG11/feature#GraphicalEventsAttribute --> <rec...
restart - SVG: Scalable Vector Graphics
Web › SVG › Attribute › restart
whenNotActive This value i...
... whenNotActive This value indicates that the animation can only be restarted when it is not active ...
... Animatable No always This value indicates that the animation can be restarted at any time. whenNotActive This value indicates that the animation can only be restarted when it is not active (i.e. after the active end). Attempts to restart the animation during its active duration are ignored. never This value indicates that the animation cannot be restarted for the time the document is loaded. Specifications Specification Status Comment SVG Animations Level 2The definition of 'restart' in that specification. Editor's Draft No change Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'restart' in that specification. Recommendation Initial definition ...
type - SVG: Scalable Vector Graphics
Web › SVG › Attribute › type
tion. For the <feTurbulence> element, it indicates whether the filter primitive should perform a noise or turbulence function. For the <style> and <script> elements, it defines the content type of the element. ...
...sage context For the <animateTransform> elements Categories None Value translate | scale | rotate | skewX | skewY Animatable No Normative document SVG 1.1 (2nd Edition) For the <feColorMatrix> element Categories None Value matrix | saturate | hueRotate | luminanceToAlpha Animatable Yes Normative document SVG 1.1 (2nd Edition) For the <feFuncR>, <feFuncG>, <feFuncB>, and <feFuncA> elements Categories None Value identity | table | discrete | linear | gamma Animatable Yes Normative document SVG 1.1 (2nd Edition) For the <feTurbulence> element Categories None Value fractalNoise | turbulence Animatable ...
... For the <feFuncR>, <feFuncG>, <feFuncB>, and <feFuncA> elements Categories None Value identity | table | discrete | linear | gamma Animatable Yes Normative document SVG 1.1 (2nd Edition) For the <feTurbulence> element Categories None Value fractalNoise | turbulence Animatable Yes Normative document SVG 1.1 (2nd Edition) For the <style> and <script> elements Categories None Value <content-type> Animatable No Normative document SVG 1.1 (2nd Edition) : script SVG 1.1 (2nd Edition) : style Example Elements The following elements can use the values attribute <animateTransform> <feColorMatrix> <feFuncA> <feFuncB> <feFu...
<script> - SVG: Scalable Vector Graphics
Web › SVG › Element › script
The SVG script element allows to add scripts to an SVG document. ...
... Value type: <string>; Default value: ?; Animatable: yes href The URL to the script to load. Value type: <URL> ; De...
...ype This attribute defines type of the script language to use. Value type: <string>; Default value: application/ecmascript; Animatable: no xlink:href Deprecated since SVG 2 The URL to the script to load. Value type: <URL> ; Default value: none; Animatable: no Global attributes Core Attributes Most notably: id Styling Attributes class, style Event Attributes Global event attributes, Document element event attributes Usage notes CategoriesNonePermitted contentAny elements or character data Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of '<script>' in that specification. Candidate Recommendation Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of '<script>' in that specificat...
<svg> - SVG: Scalable Vector Graphics
Web › SVG › Element › svg
The svg element is a container that defines a new coordinate system and viewport. It is used as the outermost element of SVG documents, but it can also be used to embed an SVG fragment inside an SVG or HTML document. Note: The xmlns attribute is only required on the outermost svg element of SVG documents. It is unnecessary for inner svg elements or inside HTML documents. html,body,svg { height:100% } <svg viewBox="0 0 300 100" xmlns="http://www.w3.org/2000/svg" stroke="red" fill="grey"> <circle cx="50" cy="50" r="40" /> <circle cx="150" cy="50" r="4" /> <svg viewBox="0 0 10 10" x="200" width="100"> <circle cx="5" cy="5" r="4" /> </svg> </svg> Attributes baseProfile Deprecated since SVG 2 The minimum SVG language profile that the document requires. Value type: <string...
...es Note: Starting with SVG2, x, y, width, and height are Geometry Properties, meaning these attributes can also be used as CSS properties. ...
...VG2, x, y, width, and height are Geometry Properties, meaning these attributes can also be used as CSS properties. ...
<symbol> - SVG: Scalable Vector Graphics
Web › SVG › Element › symbol
Documents that are rich in structure may be rendered graphically, as speech, or as Braille, and thus promote accessibility. ...
... The <symbol> element is used to define graphical template objects which can be instantiated by a <use> element. The use of symbol elements for graphics that are used multiple times in the same document adds structure and semantics. Documents that are rich in structure may be rendered graphically, as speech, or as Braille, and thus promote accessibility. html,body,svg { height:100% } <svg viewBox="0 0 80 20" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- Our symbol in its own coordinate system --> <symbol id="myDot" width="10" height="10" viewBox="0 0 2 2"> <circle cx="1" cy="1" r="1" /> </symbol> <!-- A grid to materialize our symbol positioning --> <path d="M0,10 h80 M10,0 v20 M25,0 v20 M40,0 v20 M55,0 v20 M70,0 v20" fill="none" st...
...x This attribute determines the x coordinate of the symbol. Value type: <length>|<percentage> ; Default value: 0; Animatable: yes y This attribute determines the y coordinate of the symbol. ...
SVG In HTML Introduction - SVG: Scalable Vector Graphics
ed to manipulate the picture in the same way you would script regular HTML. ...
...d added an attractive, interactive background The approach is backwards compatible to browsers that do not support SVG; simply, no background appears in them It's very simple and performs very well The picture dynamically sizes itself to the required size in an intelligent way We can have declarative style rules applying to both HTML and SVG The same script manipulates both HTML and SVG The document is entirely standards-based To add a linked image with DOM methods to an embedded SVG element, one has to use setAttributeNS to set href. Like in the following example: var img = document.createElementNS("http://www.w3.org/2000/svg", "image"); img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "move.png"); Details The viewBox attribute establishes a logical coordinate sys...
...o the maximum of the height or width and then cutting off any overflow. The style attribute pins the SVG element to the background of the form. Related Links Another SVG in HTML example: A swarm of motes Working example that works in both Mozilla and in Internet Explorer with Adobe's SVG Viewer installed. (For inline SVG to work in both Firefox and Internet Explorer it is necessary to serve documents with a different Content-Type to each browser. For this reason, if you're behind a proxy server that caches the page, the example wont work in the second browser you load it in because it will receive the wrong Content-Type.) ...
xml:base - XML: Extensible Markup Language
Web › XML › xml:base
xml:base is like the HTML <base> element, but can specify the base URI per element as well as the entire document. The base URL of a element can be queried from a script using Node.baseURI. The base URI of an element is: the base URI specified by an xml:base attribute on the element, if one exists, otherwise the base URI of the element's parent element within the document entity or external entity, if one exists, otherwise the base URI of the document entity or external entity containing the element. Support was removed from blink (Chrome and Opera) in 2015: Chromium bug 341854 blink-dev mailing list post And from Firefox 66 in bug 903372. ...
...t's parent element within the document entity or external entity, if one exists, otherwise the base URI of the document entity or external entity containing the element. Support was removed from blink (Chrome and Opera) in 2015: Chromium bug 341854 blink-dev mailing list post And from Firefox 66 in bug 903372. Use cases If you have an inline SVG you use as icons that needs to work in a document with a HTML BaseElement , you can reset the URI on your icon sprite by setting the xml:base. <html> <head> <base href="https://mydomain.com"> <style> .link { stroke: #999; stroke-opacity: .6; } marker#arrow { fill: black; } </style> </head> <body> <svg width="100%" height="100%" xml:base=""> <defs> <marker id="arrow" viewBox="0 -5 10 10" refX="0" refY="0" markerWidth="20"...
... Work-arounds xml:base support in old browsers https://gist.github.com/leonderijke/c5cf7c5b2e424c0061d2 Specifications Specification Status Comment XML Base (Second Edition) Recommendation ...
<xsl:stylesheet> - XSLT: Extensible Stylesheet Language Transformations
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The <xsl:stylesheet> element (or the equivalent <xsl:transform> element) is the outermost element of a stylesheet. Namespace Declaration A pseudo-attribute required to identify the document as an XSLT stylesheet. Typically this is xmlns:xsl="http://www.w3.org/1999/XSL/Transform". ...
... <xsl:stylesheet version="NUMBER" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" id="NAME" extension-element-prefixes="LIST-OF-NAMES" exclude-result-prefixes="LIST-OF-NAMES"> ENTIRE STYLESHEET </xsl:stylesheet> Required Attributes version Specifies the version of XSLT required by this stylesheet. Optional Attributes exclude-result-prefixes Specifies any namespace used in this document that should not be sent to the output document. The list is whitespace separated. extension-element-prefixes Specifies a space-separated list of any namespace prefixes for extension elements in this document. default-collation Specifies the default collation used by all XPath expressions appearing in attributes or text value templates that have the element as an ancestor, unless overridden by...
...xsl:apply-templates> elements within its scope. default-validation Defines the default value of the validation attribute of all relevant instructions appearing within its scope. expand-text Determines whether descendant text nodes of the element are treated as text value templates. id Specifies an id for this stylesheet. This is most often used when the stylesheet is embedded in another XML document. input-type-annotations Specifies whether type annotations are stripped from the element so the same results are produced whether the source documents have been validated against a schema or not. use-when Determines whether the element and all the nodes that have it as ancestor are excluded from the stylesheet. xpath-default-namespace Specifies the namespace that will be used if the element...
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
ing the XSLTProcessor in JavaScript. 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". <?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-namesp...
...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 appear in the prolog of the document, i.e. before the first element tag. All PIs in the prolog must be honored, both ones occurring before and onces occurring after any xml-stylesheet PIs. If there are multiple xml-stylesheet PIs the parameters apply to all stylesheets as a consequence of that all stylesheets are imported into a single stylesheet per the XSLT spec.reference? Note that multiple xml-stylesheet XSLT PIs are not suppor...
...space: <?xslt-param-namespace prefix="my" namespace="http://www.example.org/myNamespace"?> <?xslt-param name="books" select="//my:book"?> Supported versions Supported as of Firefox 2.0.0.1. The value attribute is supported in Firefox 2, but the select attribute crashes for some expressions in the 2.0 release. Possible future developments Should we allow any XSLT functions in the expression? document() seems useful, but it seems tricky to maintain the invariant that generate-id() should produce the same string for the same document. What about querying URL parameters in the XSLT stylesheet? E.g. Passing them to specified <xsl:param>'s. ...
XSLT: Extensible Stylesheet Language Transformations
Web › XSLT
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes Extensible Stylesheet Language Transformations (XSLT) is an XML-based language used, in conjunction with specialized processing software, for the transformation of XML documents. Although the process is referred to as "transformation," the original document is not changed; rather, a new XML document is created based on the content of an existing document. Then, the new document may be serialized (output) by the processor in standard XML syntax or in another format, such as HTML or plain text. XSLT is most often used to convert data between different XML schemas or to convert XML data into web pages or PDF documents. Documentation XSLT Element Reference Reference. Transforming XML with XSLT ...
...new document may be serialized (output) by the processor in standard XML syntax or in another format, such as HTML or plain text. XSLT is most often used to convert data between different XML schemas 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 ...
...t 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 TopXML XSLT tutorial introduces you to the basics of XSLT concepts, syntax, and programming. XSLT Tutorial This W3Schools tutorial teaches the reader how to use XSLT to transform XML documents into other formats, like XHTML. What is XSLT? This extensive introduction to XSLT and XPath assumes no prior knowledge of the technologies and guides the reader through back...
self - Archive of obsolete content
self provides: access to the options object access to the port object access to a mostly deprecated messaging API For an overview of content scripts, see the main article. Note that the self object in content scripts is completely different from the self module, which provides an API for an add-on to access its data files and ID. self Properties options Content-scripting APIs such as tab.attach(), page-mod, and page-worker let you pass read-only data to the content script as a JSON object via the contentScriptOptions option. ...
...self: // main.js const tabs = require("sdk/tabs"); tabs.open({ url: "./page.html", onReady: function(tab) { tab.attach({ contentScriptFile: "./content-script.js", contentScriptOptions: { a: "blah" } }); } }); // content-script.js alert(self.options.a); port You can use port to receive messages from, and send messages to, the main add-on code. See the documentation for port. Methods The self object has four methods, which enable the content script to send messages to, and receive messages from, the main add-on code. This is an older API than the API provided by port, and for most purposes the port API is a better choice. The exception is the context-menu module, which still uses postMessage. postMessage() Send a message from a content script to ...
Porting the Library Detector - Archive of obsolete content
ver in a tooltip: we can't do this using a widget, so instead will use a panel. ...
...n setLibraryInfo(element) { self.port.emit('setLibraryInfo', element.target.title); } var elements = document.getElementsByTagName('img'); for (var i = 0; i &lt; elements.length; i++) { elements[i].addEventListener('mouseover', setLibraryInfo, false); } one in the panel, which updates the panel's content with the library information: self.on("message", function(libraryInfo) { window.document.body.innerHTML = libraryInfo; }); Finally main.js relays the library information from the widget to the panel: widget.port.on('setLibraryInfo', function(libraryInfo) { widget.panel.postMessage(libraryInfo); }); ...
Two Types of Scripts - Archive of obsolete content
o 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 lib directory under your add-on's root directory. Minimally you'll have a single module implemented by a scrip...
...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. ? ? The console global supplied by the SDK. ? ? Globals defined by the HTML5 specification, such as window, document, and localStorage. ? ? The self global, used for communicating between content scripts and add-on code. See the guide to communicating with content scripts for more details. ? ? ...
XUL Migration Guide - Archive of obsolete content
he action button API, which is only available from Firefox 29 onwards. The window/utils module gives you direct access to chrome windows, including the browser's chrome window. ...
...ards. The window/utils module gives you direct access to chrome windows, including the browser's chrome window. Here's a really simple example add-on that modifies the browser chrome using window/utils: function removeForwardButton() { var window = require("sdk/window/utils").getMostRecentBrowserWindow(); var forward = window.document.getElementById('forward-button'); var parent = window.document.getElementById('urlbar-container'); parent.removeChild(forward); } require("sdk/ui/button/action").ActionButton({ id: "remove-forward-button", label: "Remove Forward Button", icon: "./icon-16.png", onClick: removeForwardButton }); There are more useful examples of this technique in the Jetpack Wiki's collection of third party modules. Accessing tabbrowser This example uses the act...
request - Archive of obsolete content
For more advanced usage, check out the net/xhr module, based on the browser's XMLHttpRequest object. Globals Constructors Request(options) This constructor creates a request object that can be used to make network requests. The constructor takes a single parameter options which is used to set several properties on the resulting Request. Parameters options : object Optional options: Name Type url string,url This is the url to which the request will be made. Can either be a String or an instance of the SDK's URL. ...
...ains 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 + " : " + response.headers[headerName]); } anonymous Boolean i...
ui - Archive of obsolete content
nwards, 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 a frame you need to add it to a toolbar. Toolbar The ability to add buttons to toolbars is new in Firefox 30. In Firefox 29 you can only add frames to toolbars. A toolbar gives you a hor...
...label: "play", icon: "./icons/play.png" }); var frame = ui.Frame({ url: "./frame-player.html" }); 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: ...
content/symbiont - Archive of obsolete content
options : object Optional options: Name Type frame object The host application frame in which the page is loaded. If frame is not provided hidden one will be created. contentScriptWhen string When to load the content scripts. ...
... by this property are loaded before those specified by the contentScript property. contentScript The texts of content scripts to load. Content scripts specified by this property are loaded after those specified by the contentScriptFile property. contentScriptWhen When to load the content scripts. ...
content/worker - Archive of obsolete content
estroy the worker by removing the content script from the page and removing all registered listeners. A detach event is fired just before removal. Properties port Object that allows you to: send customized messages to the worker using the port.emit function receive events from the worker using the port.on function url The URL of the content. tab If this worker is attached to a content document, returns the related tab. Events message This event allows the content worker to receive messages from its associated content scripts. Calling the self.postMessage() function from a content script will asynchronously emit the message event on the corresponding worker. Arguments value : The event listener is passed the message, which must be a JSON-serializable value. error This event allow...
...t on the corresponding worker. Arguments value : The event listener is passed the message, which must be a JSON-serializable value. error This event allows the content worker to react to an uncaught runtime script error that occurs in one of the content scripts. Arguments Error : The event listener is passed a single argument which is an Error object. detach This event is emitted when the document associated with this worker is unloaded or the worker's destroy() method is called. Note that you can't communicate with the content script in response to this event. If you try, you'll see this error: Error: Couldn't find the worker to receive this message. The script may not be initialized yet, or may already have been unloaded You can handle the detach event in the content script itself tho...
io/text-streams - Archive of obsolete content
t from a backing stream using a given text encoding. You can also create TextReader objects using io/file's open() function. Parameters inputStream : stream The backing stream, an nsIInputStream. It must already be opened. charset : string inputStream is expected to be in the character encoding named by this value. If not specified, "UTF-8" is assumed. See nsICharsetConverterManager.idl for documentation on how to determine other valid values for this. TextWriter(outputStream, charset) Creates a buffered output stream that writes text to a backing stream using a given text encoding. You can also create TextWriter objects using io/file's open() function. Parameters outputStream : stream The backing stream, an nsIOutputStream. It must already be opened. charset : string Text will be wr...
...king stream using a given text encoding. You can also create TextWriter objects using io/file's open() function. Parameters outputStream : stream The backing stream, an nsIOutputStream. It must already be opened. charset : string Text will be written to outputStream using the character encoding named by this value. If not specified, "UTF-8" is assumed. See nsICharsetConverterManager.idl for documentation on how to determine other valid values for this. TextReader Methods close() Closes both the stream and its backing stream. read(numChars) Reads and returns a string from the stream. If the stream is closed, an exception is thrown. Parameters numChars : number The number of characters to read. If not given, the remainder of the stream is read. Returns string : The string read. If t...
system/child_process - Archive of obsolete content
However, there are a few differences to be aware of: you need to require() the module using require("sdk/system/child_process") fork() is not supported gid and uid are not supported in node.js, spawn() and exec() inherit the environment variables from the parent process, by default. ...
... supported in node.js, spawn() and exec() inherit the environment variables from the parent process, by default. The SDK versions don't: so when you specify a command you must pass in a complete path to the command or use the env option to set up the child process environment. ...
system/xul-app - Archive of obsolete content
Globals Functions is(name) Checks whether the host application is the given application. Parameters name : string A host application name. Returns boolean : True if the host application is name and false otherwise. isOneOf(names) Checks whether the host application is one of the given applications. ...
... host application is name and false otherwise. isOneOf(names) Checks whether the host application is one of the given applications. Parameters names : array An array of host application names. Returns boolean : True if the host application is one of the names and false otherwise. versionInRange(version, lowInclusive, highExclusive) Compares a given version to a version range. See the MDN documentation for details on version comparisons. Parameters version : string The version to compare. lowInclusive : string The lower bound of the version range to compare. The range includes this bound. highExclusive : string The upper bound of the version range to compare. The range does not include this bound. Returns boolean : True if version falls in the given range and false otherwise. Pro...
ui/button/action - Archive of obsolete content
one icon, or multiple icons in different sizes. If you specify multiple icons, Firefox will select the best-fitting icon based on the device screen resolution and the place the icon appears. For example, in the screenshots above, Firefox uses the small icon when the button is in the toolbar and the large icon when the button is in the menu panel. Read more about specifying icons in the reference documentation for the ActionButton constructor. Responding to click events You can respond to click events by assigning a listener to the button's click event. You can do this in the button's constructor, by assigning the listener to the onClick option. You can also add, or change, the listener afterwards: var { ActionButton } = require("sdk/ui/button/action"); var button = ActionButton({ id: "my-...
... Destroying buttons When you've finished with a button, destroy it by calling its destroy() method. After that, any attempts to access any of its properties or to call any of its methods will throw exceptions. Globals Constructors ActionButton(options) Creates an action button. Parameters options : object Required options: Name Type id s...
ui/button/toggle - Archive of obsolete content
one icon, or multiple icons in different sizes. If you specify multiple icons, Firefox will select the best-fitting icon based on the device screen resolution and the place the icon appears. For example, in the screenshots above, Firefox uses the small icon when the button is in the toolbar and the large icon when the button is in the menu panel. Read more about specifying icons in the reference documentation for the ToggleButton constructor. Responding to click events You can respond to click events by assigning a listener to the button's click or change events. You can do this in the button's constructor, by assigning the listener to the onClick or onChange option. You can also add, or change, the listener afterwards: var { ToggleButton } = require("sdk/ui/button/toggle"); var button = Togg...
... Updating checked You can update a toggle button's checked property in just the same way you update its other properties, but there's one extra thing you need to keep in mind. The checked property is not only updated directly by assignment, but is also updated when the user clicks the button (or when some code calls button.click()). When that happens, the button is updated fo...
jpm - Archive of obsolete content
nt directory (or --addon-dir). Opens every file in there whose name starts with "test-". Make note of the hyphen after "test" in the filename. jpm test include a file called "test-myCode.js", but will exclude files called "test_myCode.js" or "testMyCode.js") call every function exported from that file whose name starts with "test". jpm test See the tutorial on unit testing and the reference documentation for the assert module for more details on this. jpm test accepts the following options: -b --binary BINARY Use the version of Firefox specified in BINARY. BINARY may be specified as a full path or as a path relative to the current directory. jpm test -b /path/to/Firefox/Nightly See Selecting a browser version. --binary-args CMDARGS Pass extra...
... You could even automate this workflow with a simple script. For example: jpm watchpost --post-url http://localhost:8888/ Note that the logging level defined for the console is different when you use this method, compared to the logging level used when an add-on is run using jpm run. This means that if you want to see the output from console.log() messages, you have to tweak a setting. See the documentation on logging levels for the details on this. Overloading the built-in modules The SDK modules you use to implement your add-on are built into Firefox. When you run or package an add-on using jpm run or jpm xpi, the add-on uses the versions of the modules in the version of Firefox that hosts it. As an add-on developer, this is usually what you want. But if you're developing the SDK modules t...
Creating Reusable Modules - Archive of obsolete content
te a "fingerprint" that can be used to identify a file. MD5 is a commonly used hash function: although it's no longer considered secure, it works fine outside a security context. Here we'll write an add-on that lets the user select a file on disk and calculates its hash. For both these operations we'll use XPCOM interfaces. File picker To let the user select a file we'll use nsIFilePicker. ...
... == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) { var file = fp.file; // Get the path as string. Note that you usually won't // need to work with the string paths. var path = fp.file.path; // work with returned nsILocalFile... } return path; } Hash function Firefox has built-in support for hash functions, exposed via the nsICryptoHash XPCOM interface The documentation page for that interface includes an example of calculating an MD5 hash of a file's contents, given its path. We can adapt it like this: var {Cc, Ci} = require("chrome"); // return the two-digit hexadecimal code for a byte function toHexString(charCode) { return ("0" + charCode.toString(16)).slice(-2); } function md5File(path) { var f = Cc["@mozilla.org/file/local;1"] .create...
Getting started (cfx) - Archive of obsolete content
. Summary In this tutorial we've built and packaged an add-on using three commands: cfx init to initialize an empty add-on template cfx run to run a new instance of Firefox with the add-on installed, so we can try it out cfx xpi to package the add-on into an XPI file for distribution These are the three main commands you'll use when developing SDK add-ons. There's comprehensive reference documentation covering all the commands you can use and all the options they take. The add-on code itself uses two SDK modules, action button and tabs. There's reference documentation for all the high-level and low-level APIs in the SDK. What's next? To get a feel for some of the things you can do with the SDK APIs, try working through some of the tutorials. Advanced techniques Overriding the built-i...
... simple script. For example: while true ; do cfx xpi ; wget --post-file=codesy.xpi http://localhost:8888/ ; sleep 5 ; done Note that the logging level defined for the console is different when you use this method, compared to the logging level used when an add-on is run using cfx run. This means that if you want to see output from console.log() messages, you'll have to tweak a setting. See the documentation on logging levels for the details on this. Another example using grunt and grunt-shell: module.exports = function(grunt) { 'use strict'; require('matchdep').filterDev('grunt-!(cli)').forEach(grunt.loadNpmTasks); grunt.initConfig({ shell: { xpi: { command: [ 'cd pluginpath', 'cfx xpi', 'wget --post-file=pluginname.xpi http://localhost:88...
List Open Tabs - Archive of obsolete content
nd click the button. You'll see output in the command line console that looks something like this: info: http://www.mozilla.org/about/ info: http://www.bbc.co.uk/ You don't get direct access to any content hosted in the tab. To access tab content, you need to attach a script to the tab using tab.attach(). This add-on attaches a script to all open tabs. ...
... add-on attaches a script to all open tabs. The script adds a red border to the tab's document: require("sdk/ui/button/action").ActionButton({ id: "list-tabs", label: "List Tabs", icon: "./icon-16.png", onClick: listTabs }); function listTabs() { var tabs = require("sdk/tabs"); for (let tab of tabs) runScript(tab); } function runScript(tab) { tab.attach({ contentScript: "document.body.style.border = '5px solid red';" }); } Learning More To learn more about working with tabs in the SDK, see the tabs API reference. To learn more about running scripts in tabs, see the tutorial on using tab.attach(). ...
Listen for Page Load - Archive of obsolete content
sdk/tabs").on("ready", logURL); function logURL(tab) { console.log(tab.url); } You will find this console output in the Browser Console, not the Web Console. You don't get direct access to any content hosted in the tab. To access tab content you need to attach a script to the tab using tab.attach(). This add-on attaches a script to all open tabs. ...
... the Browser Console, not the Web Console. You don't get direct access to any content hosted in the tab. To access tab content you need to attach a script to the tab using tab.attach(). This add-on attaches a script to all open tabs. The script adds a red border to the tab's document: require("sdk/tabs").on("ready", runScript); function runScript(tab) { tab.attach({ contentScript: "if (document.body) document.body.style.border = '5px solid red';" }); } (This example is only to show the idea: to implement something like this, you should instead use page-mod, and specify "*" as the match-pattern.) Learning More To learn more about working with tabs in the SDK, see the tabs API reference. You can listen for a number of other tab events, including open, close, and activate. To learn ...
Logging - Archive of obsolete content
in the command window you used to execute jpm run: info: Hello World! console in Content Scripts You can use the console in content scripts as well as in your main add-on code. The following add-on logs the HTML content of every tab the user loads, by calling console.log() inside a content script: require("sdk/tabs").on("ready", function(tab) { tab.attach({ contentScript: "console.log(document.body.innerHTML);" }); }); console Output If you are running your add-on from the command line (for example, executing jpm run or jpm test) then the console's messages appear in the command shell you used. If you've installed the add-on in Firefox then the messages appear in Firefox's Browser Console. But note that by default, calls to console.log() will not result in any output in the Erro...
...and shell you used. If you've installed the add-on in Firefox then the messages appear in Firefox's Browser Console. But note that by default, calls to console.log() will not result in any output in the Error Console for any installed add-ons: this includes add-ons installed using the Add-on Builder or using tools like the Extension Auto-installer. See "Logging Levels" in the console reference documentation for more information on this. Learning More For the complete console API, see its API reference. ...
Modifying the Page Hosted by a Tab - Archive of obsolete content
by a particular tab, load one or more content scripts into it using attach() method of tab object. The job of these scripts is to interact with web content. Here's a simple example: var button = require("sdk/ui/button/action").ActionButton({ id: "style-tab", label: "Style Tab", icon: "./icon-16.png", onClick: function() { require("sdk/tabs").activeTab.attach({ contentScript: 'document.body.style.border = "5px solid red";' }); } }); To run this example, save an icon file named "icon-16.png" in add-on's "data" directory. You could download this icon: . This add-on creates a button with Mozilla favicon as an icon. It has a click handler which fetches the active tab and loads a script into the page hosted by the active tab. The script is specified using the contentScript o...
...n the add-on script, tab.attach() returns a worker object containing the port property you use to send messages to the content script. Let's rewrite the example above to pass a message from the add-on to the content script. ...
Bookmarks - Archive of obsolete content
Firefox 2 and earlier Creating a new bookmark var win = myBrowser.contentWindow; // Get the bookmarks service const BMSVC = Components.classes["@mozilla.org/browser/bookmarks-service;1"] .getService(Components.interfaces.nsIBookmarksService); // Create the bookmark BMSVC.createBookmarkInContainer(win.document.title, // bookmark name win.location.href.toString(), // URI of the bookmark null, // shortcut win.document.title, // description win.document.characterSet, // charset null, // postData bookmarksService.getBookmarksToolbarFolder(), // bookmark folder ...
... The Places bookmarks service, provided by the nsINavBookmarksService interface, provides methods for creating, deleting, and manipulating bookmarks and bookmark folders. This article offers examples for how to perform common bookmark management tasks using the bookmarks service. ...
Downloading Files - Archive of obsolete content
esk", Ci.nsIFile); targetFile.append("file.bin"); var obj_URI = Services.io.newURI(aURLToDownload, null, null); // Obtain the privacy context of the browser window that the URL // we are downloading comes from. If, and only if, the URL is not // related to a window, null should be used instead. ...
...", nsFileInstance, privacy); The above is going to give you errors about missing nsIDownloadProgressListener methods, so you should implement that as well. For example, with empty dummy methods if you are not interested about the progress. Instead of using QI like above, you can also implement nsIInterfaceRequestor and return nsIAuthPrompt from there, like nsIWebBrowserPersist.progressListener documentation suggests. Downloading Images Sample function for fetching an image file from a URL. // This function is for fetching an image file from a URL. // Accepts a URL and returns the file. // Returns empty if the file is not found (with an 404 error for instance). // Tried with .jpg, .ico, .gif (even .html). function GetImageFromURL(url) { var ioserv = Components.classes["@mozilla.org/network...
LookupPrefix - Archive of obsolete content
Here is an implementation of lookupPrefix which should work cross-browser. Note that all Gecko-based browsers (including Firefox) support Node.lookupPrefix. This function is not necessary for Gecko-based browsers when used in XHTML. ...
...code which were corrected here) if (node.lookupPrefix && htmlMode !== 'text/html') { // Shouldn't use this in text/html for Mozilla as will return null return node.lookupPrefix(namespaceURI); } if (namespaceURI === null || namespaceURI === '') { return null; } switch (node.nodeType) { case 1: // Node.ELEMENT_NODE return _lookupNamespacePrefix(namespaceURI, node); case 9: // Node.DOCUMENT_NODE return _lookupNamespacePrefix(namespaceURI, node.documentElement); case 6: // Node.ENTITY_NODE case 12: // Node.NOTATION_NODE case 11: // Node.DOCUMENT_FRAGMENT_NODE case 10: // Node.DOCUMENT_TYPE_NODE return null; // type is unknown case 2: // Node.ATTRIBUTE_NODE if (node.ownerElement) { return _lookupNamespacePrefix(namespaceURI, node.ownerElement); } return n...
Preferences - Archive of obsolete content
This article provides examples for extension developers that wish to use the Mozilla preferences system. Information here applies to the Mozilla Suite, Firefox, Thunderbird, and possibly other Mozilla-based applications. For more details on preferences in Mozilla, see Preferences System. If you haven't yet, read other documents about Mozilla preferences on MDN (links below in Resources section). Note: This article doesn't cover all available methods for manipulating preferences; please refer to the XPCOM reference pages listed in Resources section for the complete list of methods. The interfaces dealing with preferences are fairly well documented, so using the methods not mentioned here should be straightforward. XPCOM interfaces for preferences system Mozilla exposes its preferences system t...
...ully funcitonal preferences skeleton, it uses the observer example from above. This example also uses a technique to trigger an onChange function that can be defined per preference and has the old value and along with the new value of the preference. It also uses a technique so you can just do prefs.preferenceName.setval('blah') instead of having to branch.setCharPref etc. ...
SVG General - Archive of obsolete content
On this page you will find some simple, general information on SVG markup. Hopefully, enough to get you creating some SVG images. You will also find some general purpose scripting helpers, that should make scripting SVG a little easier. SVG Template Here is a basic markup template to start building an SVG document: <svg xmlns="http://www.w3.org/2000/svg"> <!-- SVG elements go here --> </svg> Note: It is recommended that you do not use DTD's with SVG documents. The tutorial and authoring guidelines have more information. Dynamic scripting helper This little helper script can be used to simplify creation of SVG elements in script. SVG requires you to use setAttributeNS to add attributes to a newly created SVG DOM element. No properties like HTML. SVG IMAGE also requires the use of X...
...quires the use of XLINK for the href attribute, which can be tricky to remember, especially when you're mixing SVG with HTML or XUL. ...
StringView - Archive of obsolete content
ted the callback function. characterOffset Optional A number expressing (in codepoints) the location at which to begin executing the callback function. charactersLength Optional A number expressing (in codepoints) the number of invocations of the callback function. ...
...ion. charactersLength Optional A number expressing (in codepoints) the number of invocations of the callback function. Examples function myCallback (charCode, characterOffset, rawOffset /*, rawDataArray */) { this.appendChild(document.createTextNode("char #" + characterOffset + ", raw index: " + rawOffset + ", character: " + String.fromCharCode(charCode))); this.appendChild(document.createElement("br")); } (new StringView("\u4367\uD889\uDE54\u4343\u5431")).forEachChar(myCallback, document.body); Note: stringView.forEachChar() executes a complete cycle through all characters in the stringView between characterOffset and characterOffset + charactersLength. If you want to build a custom cycle through a variable-length-encoded stringView (UTF-8, UTF-16), you can use a ...
XPath - Archive of obsolete content
Notes and sample code for XPath and Ajax (The following was moved from document.evaluate) obj.evaluate(xpathExpression,contextNode,namespaceResolver,resultType,result); //obj and contextNode 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; } ...
...hina 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[i].text); } } else { var tobj = obj.evaluate("/root/field/item",obj.documentElement,null, XPathResult.ANY_TYPE, null); var tmp = tobj.iterateNext(); while(tmp) { fields.push(tmp.textContent); tmp = tobj.iterateNext(); } } alert(fields); } //here is the demo xml file for x...
getAttributeNS - Archive of obsolete content
'\\.')+'$'); // e.g., xlink:href // Find any prefixes with the local-name being searched (escape period since only character (besides colon) allowed in an XML Name which needs escaping) for (var j = 0; j < attrs.length; j++) { // thisitem's atts // e.g., abc:href, xlink:href while (((result = prefixAtt.exec(attrs[j].nodeName)) !== null) && thisitem.nodeName !== '#document' && thisitem.nodeName !== '#document-fragment') { var xmlnsPrefix = new RegExp('^xmlns:'+result[1]+'$'); // e.g., xmnls:xl, xmlns:xlink // CHECK HIGHER UP FOR XMLNS:PREFIX // Check the current node and if necessary, check for the next matching local name up in the hierarchy (until reaching the document root) while (thisitem.nodeName !== '#document' ...
...'#document-fragment') { var xmlnsPrefix = new RegExp('^xmlns:'+result[1]+'$'); // e.g., xmnls:xl, xmlns:xlink // CHECK HIGHER UP FOR XMLNS:PREFIX // Check the current node and if necessary, check for the next matching local name up in the hierarchy (until reaching the document root) while (thisitem.nodeName !== '#document' && thisitem.nodeName !== '#document-fragment') { attrs2 = thisitem.attributes; for (var i = 0; i < attrs2.length; i++) { // Search for any prefixed xmlns declaration on thisitem which match prefixes found above with desired local name if (attrs2[i].nodeName.match(xmlnsPrefix) && attrs2[i].nodeValue === ns ) { // e.g., 'xmlns:xlink' and 'http://www.w3.org/1999/xlink'...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
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). ...
...ve example, it would be placed as a subdirectory underneath that subproject (at the same level as public/ and src/). Of course, this means that you will have to build acmelib manually on all platforms before launching the Mozilla build. But at least you can then refer to include files and import libraries from your component using relative paths. Building for Multiple Platforms TODO Original Document Information Author: Matthew Gertner - July 26, 2005. Permission granted to migrate in Jan 2006, including permission to relicense under the CC:By-SA. Original Source: http://www.allpeers.com/blog/creating-complex-firefox-extensions/ ...
Extension Etiquette - Archive of obsolete content
ch extensions often must share with other consumers, be they other add-ons, web code, or the browser itself. These often include areas such as: Object prototypes, such as String.prototype, which are often extended to add methods to native objects. Global variables, such as top-level declarations on scripts loaded into shared windows or web pages. Expando properties of shared objects, such as document objects, or DOM nodes. IDs and class names in HTML and XUL documents, when extensions add elements to web pages or browser windows. chrome: or resource: packages, which are often defined in chrome.manifest files. about: page URLs. XPCOM contract IDs, which are often registered in chrome.manifest files. While these are among the most common examples of namespaces in which conflicts can occur...
...ta Naming Be creative! Don't be redundant and include "extension," "Mozilla/Firefox/Thunderbird," or the version number in the name. Be original! Descriptions Use something that is descriptive, but that would fit in the default add-on manager width. The Mozilla extensions (Inspector/Reporter/Talkback) believe starting with a verb is the best way. For example, "Does an action in the browser." Documentation Assume that the vast majority of your users don't have inner working knowledge of Mozilla. Make sure your extension's homepage states the "obvious," including the purpose of your extension. Users also appreciate when your extension is shipped with a simple how-to document. IDs Firefox/Thunderbird 1.5 or later are much more strict about the IDs of extensions than their 1.0 counterparts. Ma...
Migrating raw components to add-ons - Archive of obsolete content
pecifying the versions of Firefox with which they are compatible, leading to poor integration and instability as users upgrade their Firefox installations. The Firefox extension mechanism allows you to do everything that you could do through direct component drops, but also gives you and your users extra flexibility and more sophisticated versioning support. As we roll this new behavior out, this document will be updated with additional information addressing scenarios we see developers encountering. Simple migration If your goal is just to get your raw component working properly as an extension, you can do this in three steps: Create a new add-on using the instructions here. As you'll see, add-ons give you much more flexibility than simply loading a component, but in order to get started, all yo...
...the first time Firefox is run once your 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. 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 co...
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
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. ...
...ectory as the file that is the test target. Next, click the Edit button to set up the "2 1+" test case (Listing 2). Note that in this file, the method names serve as the test names. In JUnit and similar packages, methods containing tests that start with testhoge are recognized as tests. MozUnit uses the same kind of notation, but you can also make the string the method name, making the test self-documenting. Pretty clever. Listing 2: Content for test_calc.js (first-round test case) var TestCase = mozlab.mozunit.TestCase; var assert = mozlab.mozunit.assertions; var tc = new TestCase('Rpn Calc Testcase'); var module = new ModuleManager(); var rpncalc = module.require('package', 'calc'); tc.tests = { '2 1 +': function() { var calc = new rpncalc.RpnCalc(); calc.init(); calc.push(2); ...
Chapter 1: Introduction to Extensions - Archive of obsolete content
Emura-san is a co-author of Firefox 3 Hacks (O'Reilly Japan, 2008.) Introduction If you're reading this guide, you've probably used Firefox before. Perhaps the first time you looked at Firefox, you may have been surprised to see that it has a much simpler structure than other full-featured browsers, such as Opera or Safari. ...
... Because Firefox and its extensions are designed to support multiple languages, excellent extensions come from all over the world, and can be quickly localized by anyone interested. This lowers the threshold both to using and to developing extensions; that f...
Adding Events and Commands - Archive of obsolete content
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 overlay code. document.addEventListener( "XSHelloGreetingEvent", function(aEvent) { /* do stuff*/ }, false); Be careful when doing this! You should at least validate the URL of the page that is generating the custom event, so that you know that it's coming from the right place. You should also avoid this kind of events to trigger actions that could be destructive to the user's data, because a malicious site could t...
...n in the broadcaster. You can have as many elements as you want observing a broadcaster. With that set, all you need to do now is set or remove attributes in the broadcaster using JavaScript. All nodes observing it will automatically have those attribute values set or removed as well. You can override pre-existing values, such as the label attribute value in the example. let onlineBroadcaster = document.getElementById("xulschoolhello-online-broadcaster"); onlineBroadcaster.setAttribute("label", "Something"); You can also have finer-grained control to this behavior by adding the observes element as a child to your observer node. This allows you to choose which attributes you want it to observe. Broadcasters allow you to easily maintain consistency among numerous elements without having to add...
Session store API - Archive of obsolete content
essionStore interface. Knowing when to restore Each time Firefox is about to restore a tab, an event of type SSTabRestoring is sent. ...
...In this example, nsIConsoleService is used to display a message to the console. This event is sent just before a tab is restored. An event of type SSTabRestored fires each time a tab has finished restor...
Setting up an extension development environment - Archive of obsolete content
tidart/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 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...
...The Error Console is disabled by default starting in Gecko 2.0. You can re-enable it by changing the devtools.errorconsole.enabled preference to true and restarting the browser. With this, javascript.options.showInConsole is also set to true by default. Development extensions These extensions may help you with your development. ...
Using the Stylesheet Service - Archive of obsolete content
The stylesheet service allows extensions to manage user and UA stylesheets 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 Speci...
...ing stylesheets on startup via the category manager Stylesheets may also be registered on startup via the agent-style-sheets and user-style-sheets categories. The category names are ignored, and the values are the URIs from which to load the stylesheets. The order the sheets are applied in is undefined. Usage notes Stylesheets added using this service get applied to both chrome and content documents. Remember to declare the correct namespace if you want to apply stylesheets to XUL documents. Registered style sheets are not remembered across restarts. loadAndRegisterSheet fails if CSS contains #id. '#' must be percent-encoded, details see bug 659650. Historical information nsIStyleSheetService was introduced in Firefox 1.5. In Firefox 1.5 and 2, adding and removing such style sheets tak...
Creating a dynamic status bar extension - Archive of obsolete content
on inside refreshInformation() so that its variable scope includes the variables used by that function. Due to the way JavaScript works, if infoReceived() were outside refreshInformation(), it would not have access to the same variable scope. In fact, even the this value would not match, so we couldn't get at the same variables and functions that way. ...
...We need this so that we can make changes to the status bar panel itself. We then fetch the result returned by the web server into the variable output from the XMLHttpRequest.responseText property. The text we receive back from the server looks something like this: "GOOG",414.20,"5/1/2006","1:36pm",-3.74,417.85,419.44,412.19,4760215 We then parse the text. We use t...
DOMSubtreeModified - Archive of obsolete content
f the page. ...
...f the Mutation Observer API This event can cause infinite loops if you decide to change the DOM inside the event handler, hence it has been disabled in a number of browsers (see DOMAttrModified and DOMSubtreeModified events are no longer fired when style attribute is changed via CSSOM for example). document.body.addEventListener('DOMSubtreeModified', function () { document.title = 'DOM Changed at ' + new Date(); }, false); ...
Localizing an extension - Archive of obsolete content
he JavaScript code Now we're ready to revise the JavaScript code to load the strings from the string bundle instead of using literal strings. This involves rewriting the refreshInformation() function to load the strings, and its enclosed infoReceived() function to use the loaded, localized, strings instead of string literals. ...
...Then it fetches all the strings we need from the bundle, one by one, by calling the string bundle's getString() method, passing the appropriate key for each string. In this case, we're also appending a space to the end of each string. That's just how this particular program works, and isn't something that you have to do. Then we replace any occ...
Installing plugins to Gecko embedding browsers on Windows - Archive of obsolete content
Since the prospect of embedded Gecko browsers raises the scenario of more than one Gecko-based browser that a Netscape-style plugin can work with, it becomes important to let plugin developers know how to discover these browsers on a Windows machine. This information applies to Mozilla based browsers that pull the Mozilla codebase after the Mozilla 0.9.1 milestone release. None of the Registry keys mentioned here are written by browsers before the Mozilla 0.9.1 timeframe. ...
...l keys. ...
Monitoring WiFi access points - Archive of obsolete content
ily to allow WiFi-based location services to be used by geolocation services. Example This example simply displays a list of the available access points. ...
... function test() { } test.prototype = { onChange: function (accessPoints) { netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); var d = document.getElementById("d"); d.innerHTML = ""; for (var i=0; i<accessPoints.length; i++) { var a = accessPoints[i]; d.innerHTML += "<p>" + a.mac + " " + a.ssid + " " + a.signal + "</p>"; } var c = document.getElementById("c"); c.innerHTML = "<p>" + count++ + "</p>"; }, onError: function (value) { alert("error: " +value); }, QueryInterface: function(iid) { netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); if (iid.equals(Components.interfaces.nsIWifiListener) || iid.equals(Components.interfaces.nsISupports)) return th...
No Proxy For configuration - Archive of obsolete content
Audience Mozilla users, mozilla developers, mozilla testers. Overview As browsers rapidly grew in popularity in the mid-90's, many network administrators added proxy servers. Initially, proxy servers were used for access control and performance. Many networks had limited access to the public network via proxy servers. Because the public network was small in scope and connections were slow, a caching proxy could often improve the overall performance. This feature was originally designed as a "blacklist" of sites or domains that was within the intranet, and should not be accessed via the proxy server. ...
...et or dogwood.state.mo.us, .intra.state.mo.us, dor.intranet Note that you don't need to (read shouldn't) put a * for all hosts with that domain ending. Corollary- a no_proxies_on entry of netscape.com will be applicable to all hosts ending at netscape.com including foonetscape.com but an entry of .netscape.com will specifically be applicable to all hosts in the domain of netscape.com. Original Document Information Author(s): Benjamin Chuang Last Updated Date: November 2, 2005 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Source Navigator - Archive of obsolete content
I hope I can finish it within one day or two if I have more time. ;) --Kennykaiyinyu 19:04, 10 June 2008 (PDT) What is Source-Navigator? (quoted from the internet) Source-Navigator is a source code analysis tool which lets users to edit, browse and build their projects. With it, you can edit your source code, display relationships between classes and functions and members, and display call trees. You can also build your projects, either with your own makefile, or by using Source-Navigator's build system to automatically generate a makefile. Source-Navigator works with the Insight GUI interface for GDB. ...
...erminal window: sudo apt-get install sourcenav This should install source-navigator. One can check whether the installation is complete by executing: $ which snavigator /usr/bin/snavigator Importing the source Execute the following: snavigator. This triggers a splash screen, followed by a "Source-Navigator Projects" dialog as the following: I've already created a new project bin.proj before documenting this. If this is your first time to open source navigator, the big white box on the left of the dialog should contain no lines. Click "New Project". This shows the "Auto-Create Project" dialog: which allows you to decide your filename of the project file (which ends in .proj) and your source directory/directories that you want to import into the project. (You can always include more by pressi...
Visualizing an audio spectrum - Archive of obsolete content
me FFT analysis on an audio stream, rather than the code shown below. ...
...r the canvas before drawing spectrum ctx.clearRect(0,0, canvas.width, canvas.height); for (var i = 0; i < fft.spectrum.length; i++ ) { // multiply spectrum by a zoom value magnitude = fft.spectrum[i] * 4000; // Draw rectangle bars for each frequency bin ctx.fillRect(i * 4, canvas.height, 3, -magnitude); } } var audio = document.getElementById('audio-element'); audio.addEventListener('MozAudioAvailable', audioAvailable, false); audio.addEventListener('loadedmetadata', loadedMetadata, false); // FFT from dsp.js, see below var FFT = function(bufferSize, sampleRate) { this.bufferSize = bufferSize; this.sampleRate = sampleRate; this.spectrum = new Float32Array(bufferSi...
Autodial for Windows NT - Archive of obsolete content
A Brief History of Autodial on Windows In the consumer versions of Windows, (Windows 95, Windows 98, Windows ME) autodial for all applications is controlled from the Control Panel, in the Internet Options applet, under the tab Connections. If you turn on the autodial feature, Windows will automatically dial whenever any application tries to access a network address that can't be reached. ...
... 1.1 also includes a fix to bug 157733, which allows our interaction with the autodial service to work a little more reliably. I don't see a need to expose this pref in the UI, but perhaps it should be there. Or pehaps we should assume Mozilla users can configure the autodial service and disable the helper by default, but Netscape users need a little more help, and enable it for them. Original Document Information Author(s): Benjamin Chuang Last Updated Date: October 2, 2002 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Building TransforMiiX standalone - Archive of obsolete content
We support building a standalone version of TransforMiiX on Windows, Unix and OS X. Read the build instructions for your platform to get the requirements, which are the same as for Mozilla. You need to get the source from CVS. Add TX_EXE=1 mk_add_options BUILD_MODULES="xpcom transformiix" ac_add_options --enable-standalone-modules="xpcom transformiix" to your .mozconfig, and use client.mk to pull as usual. This will pull the necessary subtree with mozilla/client.mk mozilla/build/unix/modules.mk mozilla/build mozilla/config mozilla/expat mozilla/extensions/transformiix mozilla/include mozilla/allmakefiles.sh mozilla/client.mk mozilla/aclocal.m4 mozilla/configure mozilla/configure.in mozilla/Makefile.in plus nspr and xpcom from the cvs repository. ...
...x to your .mozconfig, too, as it stops configure from testing unneeded libs. make -f client.mk build as usual. Of course, make -f client.mk checks out and builds just TransforMiiX alright. ...
Creating a Firefox sidebar extension - Archive of obsolete content
See the references section for information on creating extension in earlier browsers. Introduction This article is a quick start for the creation of a new sidebar for Firefox. What we will do is create a sidebar and register it so it will be available in the menu. The goal is creating an empty sidebar that can be used as start for new sidebar applications. Creating a sidebar requires some GUI creation and registration in the destination application. ...
...le and the Extension installation window pops up. After a restart of Firefox, the sidebar is installed. You can download the empty sidebar project to use as a basis for your own sidebars. The EmptySidebar extension Resources Code snippets:Sidebar Building an Extension Creating Applications with Mozilla Packaging Firefox/Thunderbird Extensions Creating a Firefox 1 Sidebar Original Document Information Author: J.C. Wesdorp <jcwesdorp . at . occidopagus.nl> - May 30, 2005. Updated for Firefox 2 - Dec 12, 2006. Permission granted to migrate in Jan 2006, including permission to relicense under the CC:By-SA. Original Source: http://occidopagus.nl/firefox/emptysidebar/ ...
Creating a Mozilla Extension - Archive of obsolete content
nsion for the old versions of Mozilla Suite (currently SeaMonkey). See Building an Extension for an up-to-date tutorial (it focuses on Firefox, but is also applicable to other new applications). A Mozilla extension is an installable enhancement to the Mozilla browser that provides additional functionality (for example Linky, which adds an item to the context menu for opening multiple links in a document or selection). This tutorial walks you through the process of building a Mozilla extension that adds an icon to Mozilla's status bar showing the current status of the Mozilla source code (i.e. whether or not the latest version of the code is compiling successfully and passing tests). The extension will access Tinderbox, mozilla.org's webtool for tracking source code status, to get the status of t...
... ...
DTrace - Archive of obsolete content
opers to instrument a program with probes that have little to no effect on performance when not in use and very little when active. Probe data can be collected with scripts written in D (no, not that one). Mozilla DTrace support has been added by the Sun DTrace team and can be used on Solaris 10 and Mac OS X 10.5. DTrace has been largely supplanted by the Gecko Profiler and other tools, so this documentation has been archived. If you find that there are still use cases of consequence, you're welcome to file a documentation bug. The DTrace probes currently built into the codebase may be enabled by default in the future, but for now you'll need to create a build with --enable-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...
...e DTrace probes currently built into the codebase may be enabled by default in the future, but for now you'll need to create a build with --enable-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. ...
Using Dehydra - Archive of obsolete content
input_end() { print("Hello, world!"); } Compile using the following command: $ g++ -fplugin=~/dehydra/gcc_dehydra.so -fplugin-arg=~/dumptypes.js -o/dev/null -c dumptypes.cc Note:for g++4.5 and up use -fplugin-arg-gcc_dehydra-script= rather than -fplugin-arg It should print the following results: Type found: Foo location: test.cc:2:12 Type found: MyInt location: test.cc:1:13 Hello, world! See documentation for: process_type, input_end, print, .loc property Example: using attributes to mark a class as "final" Save the following code as final.cc: // This class should not be subclassed! class __attribute__((user("final"))) MyClass { }; // This subclass should be an error class SubClass : public MyClass { }; Save the following analysis script final.js: /** * Helper function: returns true if a ...
...let base in t.bases) if (isFinal(base.type)) error("class " + t.name + " extends final class " + base.type.name, t.loc); } Compile using the following command: $ g++ -fplugin=~/dehydra/gcc_dehydra.so -fplugin-arg=~/final.js -o/dev/null -c final.cc It should print the following results and return with an error code: final.cc:8: error: class SubClass extends final class MyClass See documentation for: process_type, error, .bases property, .attributes property ...
Developing New Mozilla Features - Archive of obsolete content
and to the Mozilla world. Develop relationships with existing developers in the area of your feature If you want to add a big new feature to mail, spend some time helping the existing mail developers. Talk to the developers about fixing some of their bugs. Fix some bugs. Have some of your QA team get involved. Once you're familiar with an area, do the completely unexpected and write a piece of documentation. Developers will be grateful, and you'll be known as someone seriously interested in contributing. Become familiar with our code review processes. Have someone on your team become Mozilla-savvy enough to obtain CVS access. Help the existing developers to understand that you are "for real" That you have a clue about Mozilla development; that your team is going to ship a product. Our develop...
...ck-in when the pain is limited to the developers and the reviewers rather than everyone in the tree. We're committed to this style of development, but recognize that vigilance is necessary to make sure newcomers and their features don't get lost. If you're having a particularly bad experience or if you've got suggestions on how to improve our process, please let mozilla.org staff know. Original Document Information Author(s): Mitchell Baker Last Updated Date: October 30, 2004 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Drag and Drop Example - Archive of obsolete content
the data from the drag session and create a new element of the appropriate type. var boardObserver = { getSupportedFlavours : function () { var flavours = new FlavourSet(); flavours.appendFlavour("text/unicode"); return flavours; }, onDragOver: function (event, flavour, session) {}, onDrop: function (event, dropdata, session) { if (dropdata.data != "") { var elem = document.createElement(dropdata.data); event.target.appendChild(elem); elem.setAttribute("left", "" + event.pageX); elem.setAttribute("top", "" + event.pageY); elem.setAttribute("label", dropdata.data); } } } The getSupportedFlavours function needs only to return a list of flavours that the stack can accept to be dropped on it. In this case, it only accepts text. We don't ne...
...ferData(); transferData.data.addDataForFlavour("text/unicode", txt); } }; var boardObserver = { getSupportedFlavours : function () { var flavours = new FlavourSet(); flavours.appendFlavour("text/unicode"); return flavours; }, onDragOver: function (event, flavour, session) {}, onDrop: function (event, dropdata, session) { if (dropdata.data != "") { var elem = document.createElement(dropdata.data); event.target.appendChild(elem); elem.setAttribute("left", "" + event.pageX); elem.setAttribute("top", "" + event.pageY); elem.setAttribute("label", dropdata.data); } } }; << Previous Original Document Information Author(s): Neil Deakin Original Document: http://xulplanet.com/tutorials/mozsdk/dragex.php Copyright Information: Cop...
Drag and Drop JavaScript Wrapper - Archive of obsolete content
s to be dragged at once and also allows alternative forms of the data to be dragged. The following table describes some of the flavours you might use. ...
...rms of the data to be dragged. The following table describes some of the flavours you might use. You can also make up your own flavours if necessary. ...
JavaScript Client API - Archive of obsolete content
The best, and most up-to-date, reference to Sync's internal APIs is the source code. ...
... register event handler or observer here ... this._enabled = true; } break; case "weave:engine:stop-tracking": if (this._enabled) { // remove event handler or observer here ... this._enabled = false; } break; }, onEvent: function onEvent() { /* Here is where you'd handle the event. See the documentation for whatever service you are observing to find out what to call this method, what arguments to expect, and how to interpret them. */ var guid = 0; /* Here is where you'd include code to figure out the GUID of the item that has changed... */ this.addChangedID(guid); // Update the score as you see fit: this.score += 10; } }; Writing an E...
HTTP Class Overview - Archive of obsolete content
It's meant as a guide to developers wishing to understand or extend the Mozilla HTTP implementation. ...
... ...
Basics - Archive of obsolete content
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! Class Console Writes some information to the Error Console. You can find the console in the Extra Menu of Firefox. The namespace for this API is console. Methods info()This method does stuff. log(stringstring)This method writes a notification message to the console. stringThe message to add to the consolestring console.log("hello world!"); arn()This method does stuff. error()This method does stuff. exception()This method does stuff. logFromCaller()This method does stuff. ...
...onFocus()changing the focus of a tab. Methods open(urlstring)Opens a new tab in your browser with a defined url. urlURL to be openedstring jetpack.tabs.open("http://www.example.com/"); ...
Page modifications - Archive of obsolete content
Please see the page modifications API proposal for now. ...
... Please see the page modifications API proposal for now. ...
Twitter - Archive of obsolete content
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! Jetpack's Twitter library, jetpack.lib.twitter, is a very simple, lightweight layer on top of Twitter's REST API. In fact it's hardly more than syntactic sugar for doing XMLHttpRequests. To use this library, you therefore need to be familiar with Twitter's own API. (It's easy!) Methods Each method in Twitter's API maps to a method here. For example, the Twitter method for tweeting, statuses/update, maps to jetpack.lib.twitter.statuses.update(). To call trends/current, use jetpack.lib.twitter.trends.current(). ...
...ed above. Or you can simply rely on Firefox. When you call a method that requires authentication -- such as jetpack.lib.twitter.statuses.update() -- without providing a username or password, Firefox will prompt the user for them if she is not already authenticated with Twitter. Both methods use HTTP basic authentication. In the future, the library may support OAuth. See Twitter's authentication documentation for related information. FAQ See Twitter's API FAQ. Since Jetpack's Twitter library is a very thin wrapper around Twitter's API, most everything there applies here, and not much applies here that doesn't apply there. Example usage Tweeting jetpack.lib.twitter.statuses.update({ status: "O frabjous day!" }); Firefox will prompt for a username and password if the user is not already authent...
Jetpack Snippets - Archive of obsolete content
Note: This page documents the Jetpack Prototype, which is no 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! Bits of code that may come in handy. Feel free to add your own! Using firebug lite in a slidebar jetpack.future.import("slideBar");jetpack.slideBar.append({ html: <html><head></head><body> <p>some slidbar you want to debug</p> <a href="javascript:console.log('hello!')">test</a> <script><![CDATA[ //firebug lite bookmarklet code: var firebug=document.createElement('script'); firebug.setAttribute('src','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'); do...
....slide(800, true); }}); Calling into a slidebar from the global jetpack scope jetpack.slideBar.append({ onReady: function (slide) { // call out to a global function, passing the slidebar object exInitSlidebar(slide); }, ...});function exInitSlidebar(aSlidebar) { // This variable will now be global slider = aSlidebar;} // then, accessing the slidebar HTMLvar tl = slider.contentDocument.getElementById("thumbList"); // or calling slidebar API methods or accessing propertiesslider.notify(); ...
System information - Archive of obsolete content
Please see the system information API proposal for now. ...
... Please see the system information API proposal for now. ...
Tabs - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Tabs
Note: This page documents the Jetpack Prototype, which is no 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! In this class you can find information about the tabs in your Firefox window. The namespace for this class is jetpack.tabs. blah(lengthstringfocusedstringtoStringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengthThe number of open tabsstring focusedthe current tab in your browserstring toStringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onReady()when the inherited document is fully loaded. onFocus()changing the...
...onFocus()changing the focus of a tab. ...
UI - Archive of obsolete content
Note: This page documents the Jetpack Prototype, which is no longer under active development. ...
...ing menus in the browser Slidebar UI mechanism for displaying jetpack content in a slide-out animated vertical column Toolbar Including entries and access elements into the toolbar Panel A movable, expandable, and custom styled content element to display jetpack content Tabs Adding events and interacting with browser tabs and their contained documents Statusbar Low-level functions and basic calls Notifications A system for alerting users via provided UI mechanisms Selection Interacting with user-selected content Window Mitigates and eases interactions between different browser windows ...
Jetpack - Archive of obsolete content
Jetpack Jetpack is a project to make it easy to build Firefox add-ons using common web technologies. ...
... Jetpack Jetpack is a project to make it easy to build Firefox add-ons using common web technologies. ...
Microsummary topics - Archive of obsolete content
For example, the following code snippet installs the microsummary generator from the Creating a Microsummary tutorial: var generatorText = ' \ <?xml version="1.0" encoding="UTF-8"?> \ <generator xmlns="http://www.mozilla.org/microsummaries/0.1" \ name="Firefox Download Count" \ uri="urn:{835daeb3-6760-47fa-8f4f-8e4fdea1fb16}"> \ <templat...
...d specify a unique identifier for the generator in the uri attribute of the <generator> element. The value of the attribute must be a valid URI, but you can specify an arbitrary identifier using a URN, for example: urn:{835daeb3-6760-47fa-8f4f-8e4fdea1fb16} To guarantee uniqueness, use URNs containing UUIDs generated by the nsUUIDGenerator component. See Generating a UUID in the nsIUUIDGenerator documentation. You may also use another form appropriate to your extension. Note: When web sites install generators via window.sidebar.addMicrosummaryGenerator(), Firefox sets their uri attribute to urn:source:sourceURL, where sourceURL is the URL from which the generator was downloaded. In the future, Firefox may access source URLs to download updated versions of generators, so unless you are installing ...
Modularization techniques - Archive of obsolete content
The mechanism we're using is based on the principles laid down by COM, so pretty much anything you know about COM can be applied here, and any reference on COM can provide you with more interesting and complex examples than the ones provided here. The Basics Interfaces The basic building blocks of modules are C++ pure virtual interfaces. ...
... can be licensed from Microsoft, but for obvious reasons we are not going to be doing that. In house equivalents to the important elements of this technology will be developed as needed. ...
Overview of how downloads work - Archive of obsolete content
Click on the images to display them "stand-alone" in the browser, which may resize them to fit the browser window. ...
...he browser, which may resize them to fit the browser window. ...
Prism - Archive of obsolete content
efox extension, code-named "Refractor", can be used to spin out new Prism apps from inside the web browser. Refractor adds a new menu item to call up the shortcut creation dialog for inside Firefox. Web apps can also point to a complete web app bundle or some elements of a web app (like higher resolution icons). Refractor automatically takes this information into account. Documentation Frequently Asked Questions Bundles A web application bundle is a zip archive that holds a configuration file, icons and an optional webapp JS script. Bundles can be installed locally, or directly from a website using the Prism for Firefox extension. Configuration ...
... Installing Prism. View All... ...
PyDOM - Archive of obsolete content
This allows you to use Python code (almost) anywhere you can use JavaScript. 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. For example, when a top-level window has something like: <window ... script="foo = 1" ... ...
...le, when a top-level window has something like: <window ... script="foo = 1" ... An event handler like: <button onclick="print foo"/> Should be able to reference 'foo' via globals as shown. Note that you can stick arbitrary values on any DOM object - this is what JS calls 'expandos'. ...
Same origin policy for XBL - Archive of obsolete content
The same origin policy used for XBL documents is different from the policy used for other content. This article provides a description of how the same origin policy for XBL works. When Mozilla needs to decide whether or not XBL is allowed to be loaded, it looks at the nsIPrincipal originating the load and the nsIURI to be loaded. Determining the originating principal The principal originating the load is determined using the following steps: For external stylesheets (<link>, <?xml-stylesheet?>, user sheets, and UA sheets), it depends on where the sheet is loaded from, just like it would for an HTML document loaded from a similar source. For inline stylesheets (<style> and style attributes), the principal of the element node involved (meaning the <style> element or the element whose style attribu...
... For external stylesheets (<link>, <?xml-stylesheet?>, user sheets, and UA sheets), it depends on where the sheet is loaded from, just like it would for an HTML document loaded from a similar source. For inline stylesheets (<style> and style attributes), the principal of the element node involved (meaning the <style> element or the element whose style attribute is being looked at). For the nsIDOMDocumentXBL interface's nsIDOMDocumentXBL.addBinding() and nsIDOMDocumentXBL.loadBindingDocument() methods, the originating principal is the one of the script making the call, or the principal of the document the call is made on if there isn't a script. Checks performed Once the originating principal is determined, checks are done to make sure the load should be allowed. The checks performed are: If the...
Space Manager High Level Design - Archive of obsolete content
Should be private (compiles fine) nsBlockFrame::Paint is mucking with nsBlockBandData in and #if 0 block - remove that and the include (compiles fine) nsSpaceManger has no way of clearing the float damage interval set ...
...e (compiles fine) nsSpaceManager data members are declared protected, but there are no subclasses. ...
Supporting per-window private browsing - Archive of obsolete content
import resource://gre/modules/PrivateBrowsingUtils.jsm and use PrivateBrowsingUtils.getPrivacyContextFromWindow(win), passing a Window object that is related to the content in question. As an example, if an add-on adds a context menu item that accesses an API that requires an nsILoadContext, the most relevant window is the one that owns the element being targeted by the context menu (element.ownerDocument.defaultView). If some action triggered by a chrome element (such as a button) requires an API that takes a privacy context, the most relevant window is the one that contains the chrome element. In some cases, there is no logical window object to use (such as when data or an action originate from some other source than web content). In these cases, it is permissable to pass null as the argument in...
...However, sometimes you need to adjust the privacy status on a channel manually, for example, if you have created the channel directly yourself. You can use the nsIPrivateBrowsingChannel interface for this purpose. The example below creates a channel to load a URL, and forces it to be in private mode. var channel = Service...
Table Cellmap - Archive of obsolete content
Further it contains info whether this entry is a row- or colspan. ...
...ines seem to be hot spots performance wise: nsCellMap::ColHasSpanningCells nsCellMap::RowHasSpanningCells nsCellMap::RowIsSpannedInto Users of nsCellmap::GetDataAt outside nsCellMap.cpp The border collapse code relies on the cellmap. The collapsing of rows and columns uses the cellmap. and finally the line iterator methods which are used for arrow navigation through a table. Original Document Information Author(s): Bernd Mielke Last Updated Date: September 27, 2003 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
URIs and URLs - Archive of obsolete content
s of resource identifiers without interfering with the way that existing identifiers are used; and, it allows the identifiers to be reused in many different contexts, thus permitting new applications or protocols to leverage a pre-existing, large, and widely-used set of resource identifiers. Resource A resource can be anything that has identity. Familiar examples include an electronic document, an image, a service (e.g., "today's weather report for Los Angeles"), and a collection of other resources. Not all resources are network "retrievable"; e.g., human beings, corporations, and bound books in a library can also be considered resources. The resource is the conceptual mapping to an entity or set of entities, not necessarily the entity which corresponds to that mapping at any particula...
...authority. This authority component is typically defined by an Internet-based server or a scheme-specific registry of naming authorities. ... The structure of a registry-based naming authority is specific to the URI scheme, but constrained to the allowed characters for an authority component. are not supported. References Main reference for URIs, URLs and URL-parsing is RFC 2396. Original Document Information Author(s): Andreas Otte Last Updated Date: January 2, 2002 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Venkman - Archive of obsolete content
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. 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...
...illa forums... Mailing list Newsgroup RSS feed IRC: #venkman on irc.mozilla.org Report a bug in Venkman If you find a problem with Venkman, please follow directives mentioned at Venkman FAQ section 5.4 and then you may report a bug on JavaScript Debugger component. Related Topics JavaScript, Web Development, Developing Mozilla Original Document Information Author(s): Robert Ginda Other contributors: Doctor Unclear Last Updated Date: July 13, 2007 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
XBL - Archive of obsolete content
97874 and Are We XBL Still?. Removal of the XBL implementation is being tracked in bug 1566221. See also: XBL Removal Design Review Packet, Problems with XBL and the XBL and Web Components comparison. XML Binding Language (XBL, sometimes also called Extensible Bindings Language) is a language for describing bindings that can be attached to elements in other documents. The element that the binding is attached to, called the bound element, acquires the new behavior specified by the binding. Bindings can contain event handlers that are registered on the bound element, an implementation of new methods and properties that become accessible from the bound element, and anonymous content that is inserted underneath the bound e...
...L widgets are at least partially implemented using XBL. You can build your own reusable widgets from existing XUL, HTML, SVG, and other primitives using XBL. Specifications XBL 1.0 is specified in XBL 1.0 Reference. Unfortunately, the actual implementation in Mozilla is different from the specification, and there's no known document available describing the differences. Hopefully, the Reference will be updated to describe those differences. XBL 1.0 is a Mozilla-specific technology, and not a W3C standard. At least two standards spawned from it have died: sXBL and XBL 2.0. Warning: sXBL and XBL 2.0 have died. W3C sXBL (curre...
Creating XPI Installer Modules - Archive of obsolete content
/bin/chrome/ directory, and the XPI itself can be redistributed for installation on other machines. Notes Note: zip There exist a lot of ZIP archivers/unarchivers. For Unix, you can either use the preinstalled zip tool, or e.g. ...
...or installation on other machines. Notes Note: zip There exist a lot of ZIP archivers/unarchivers. For Unix, you can either use the preinstalled zip tool, or e.g. 7-Zip (free software). For Windows, you can e.g. ...
Install Wizards (aka: Stub Installers) - Archive of obsolete content
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. ...
... XPInstall engine and requisite components to prepare for use by the stub installer. The stub installer hands off one-by-one a series of xpis to install. ...
Using XPInstall to Install Plugins - Archive of obsolete content
hat can do this. A complete template of an XPI Package is also presented in this section. Not all the work needs to be done in JavaScript -- if you have a native installer (EXE) that recognizes Netscape Gecko browsers, and you merely wish to wrap the EXE installer in an XPI Package for a streamlined delivery to the client, you can easily do so. This section refers extensively to the XPInstall API Documentation. Initializing Installation with Plugin Identifier All XPInstall installations are initiated with the initInstall method of the Install Object. Since the Install Object is available to the install script, it need not be mentioned in the install script (e.g. there is no need to invoke Install.initInstall; simply invoking initInstall will suffice). The initInstall method is polymorphic, but ...
...ll is a legitimate concern, it might be wise to write a native code (EXE) uninstaller to remove the software. XPInstall can therefore be the "agent of delivery" to streamline the download of the EXE software, but ultimately, the logic of installation and uninstallation will be handled by EXE, which can then create files and registry entries and also clean up after itself upon removal. Original Document Information Author(s): Arun K. Ranganathan, Netscape Communications Last Updated Date: 05 Aug 2002 Copyright Information: Copyright (C) 2001-2003 Netscape. All rights reserved. Link: http://devedge-temp.mozilla.org/view.../index_en.html Triggering an XPInstall Download from HTML In a manner analogous to how SmartUpdate downloads were initiated by the pluginurl attribute of the embed tag,...
getFolder - Archive of obsolete content
so work in other versions): "Chrome" "Components" "Current User" "Defaults" "file:///" "OS Drive" "Plugins" "Preferences" "Profile" "Program" "Temporary" "Mac Apple Menu" "Mac Control Panel" "Mac Desktop" "Mac Documents" "Mac Extension" "Mac Fonts" "Mac Shutdown" "Mac Startup" "Mac System" "Mac Trash" "Mac Preferences" "MacOSX Default Download" "MacOSX Home" "MacOSX Internet Sites" "MacOSX Local Applications" "MacOSX Local Desktop" "MacOSX Local Documents" ...
... "Mac Trash" "Mac Preferences" "MacOSX Default Download" "MacOSX Home" "MacOSX Internet Sites" "MacOSX Local Applications" "MacOSX Local Desktop" "MacOSX Local Documents" "MacOSX Local Frameworks" "MacOSX Local Internet PlugIn" "MacOSX Local Preferences" "MacOSX Movie Documents" "MacOSX Music Documents" "MacOSX Picture Documents" "MacOSX User Applications" "MacOSX User Desktop" "MacOSX User Documents" "MacOSX User Frameworks" "MacOSX User Internet PlugIn" "MacOSX User Preferences" "Unix Lib" "Unix Local" "Windows" ...
Learn XPI Installer Scripting by Example - Archive of obsolete content
eate new directories, to install files in system folders and other areas. Overview of the Install Script XPI install scripts are written in JavaScript using XPInstall Engine syntax defined in the XPInstall API Reference. ...
...ndler on a regular web page, will point to the remotely-hosted XPI (called here 'cdrip.xpi') and trigger its installation: function putIt() { xpi={'CD_Ripper':'cdrip.xpi'}; InstallTrigger.install(xpi); } ... <a href="#" onclick="putIt();">install the CD Ripper Now!</a> See the InstallTrigger object in the XPInstall API Reference for more information on triggering installations. Original Document Information Author(s): Ian Oeschger Last Updated Date: 01/26/2006 Copyright Information: Copyright (C) Ian Oeschger ...
XPJS Components Proposal - Archive of obsolete content
Draft 1.0 What are XPJS Components? XPJS Components is a (cheesy) name for a system to support xpcom components written in JavaScript. Now, you might ask: "Isn't that what XPConnect does?" And I would answer that XPConnect is necessary, but not sufficient to the task. ...
...actory calls into the module will force the XPJSManager to load up a new instance of the .js file and start over. ...
datasources - Archive of obsolete content
have a template element as a child. For RDF templates, the specified datasources are combined into a single composite datasource which holds the data from all of the datasources. This composite datasource is accesssible via a script through the database property. For XML datasources, only one source is used, either the URL of an XML file or an anchor reference to another element within the same document. ...
...nchor reference to another element within the same document. For instance, the reference '#data' refers to an element with the id 'data'. If you plan on adding a datasource to an element but don't want one to be added right away, set this attribute to 'rdf:null'. This will make the element so that its contents can be generated from a datasource. Otherwise, you cannot add one later. When the XUL document is contained on a remote web site, the datasources may only be loaded from the same domain as the document. ...
id - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › id
<< XUL Reference home id Type: unique id A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById() and other DOM functions and to reference the element in style sheets. ...
...o" label="Click Me" oncommand="doSomething()"/> <script> function doSomething(){ var myButton = document.getElementById('foo'); myButton.setAttribute('label','The button was pressed'); } </script> A more abstract version of the above would be a <button id="foo" label="Click Me" oncommand="setWidgetLabel(this, 'I was pressed')"/> <script> function setWidgetLabel(idName, newCaption){ document.getElementById( idName.id ).setAttribute('label',newCaption) } </script> Not specifying the id attribute for a window or a prefwindow fills the console with the following warning message: Warning: Empty string passed to getElementById() See also name ...
Deprecated and defunct markup - Archive of obsolete content
as deprecated, this page needs review} The following XUL tags and attribute should be considered deprecated, if not defunct. The list below may include a few elements which are actually in use, but at a deeper level in the code. Even some of the information on the tags below may be out of date, but is provided here for historical reference and to help anyone who comes across them in old code or documentation. Elements <actions> (listed here by mistake or was it a container tag?) Typo for <action> --Neil 03 March 2011 <autorepeatbutton> (action occurs repeatedly on mouse hover--used to construct other elements; used in <arrowscrollbox> and large drop-down menus) So, not deprecated? --Neil 03 March 2011 <bulletinboard> (made to support left/top styles, but <stack> can now do as well) ...
...--Neil 03 March 2011 <sidebarheader> Not true, still in use --Neil 03 March 2011 <slider> (clickable tray in <scrollbar> which holds <thumb>; do not use alone) Also used as part of <scale> --Neil 03 March 2011 <spinner> (spinbox; <spinbuttons> with a...
openPopup - Archive of obsolete content
gerEvent ) Return type: no return value Opens the popup relative to a specified node at a specific location. anchor The popup may be either anchored to another node or opened freely. To anchor a popup to a node, supply an anchor node and set the position to a string indicating the manner in which the popup should be anchored. The anchor node does not need to be in the same document as the popup. Unanchored popups may be created by supplying null as the anchor node. The direction in which the popup is oriented depends on the direction of the anchor. position Possible values for position are: before_start, before_end, after_start, after_end, start_before, start_after, end_before, end_after, overlap, and after_pointer. Check Positioning of the Popup Guide for a p...
...d_after, overlap, and after_pointer. Check Positioning of the Popup Guide for a precise description of the effect of the different values. x, y For an anchored popup, the x and y arguments may be used to offset the popup from its anchored position by some number, measured in CSS pixels. An unanchored popup appears at the position specified by x and y, relative to the viewport of the document containing the popup node. In this case, the position and attributesOverride arguments are ignored. isContextMenu The isContextMenu argument should be true for context menus and false for all other types of popups. It affects menu item highlighting; that is, while a context menu is open, menus opened earlier do not highlight or execute their items. attributesOverride I...
removeItemAt - Archive of obsolete content
<< XUL Reference home removeItemAt( index ) Return type: element Removes the child item in the element at the specified index. The method returns the removed item. ...
...ent at the specified index. The method returns the removed item. ...
Methods - Archive of obsolete content
r appendGroup appendItem appendNotification blur cancel cancelDialog centerWindowOnScreen checkAdjacentElement clearResults clearSelection click close collapseToolbar contains decrease decreasePage doCommand ensureElementIsVisible ensureIndexIsVisible ensureSelectedElementIsVisible expandToolbar extra1 extra2 focus getBrowserAtIndex getBrowserForDocument getBrowserForTab getBrowserIndexForDocument getButton getDefaultSession getEditor getElementsByAttribute getElementsByAttributeNS getFormattedString getHTMLEditor getIndexOfFirstVisibleRow getIndexOfItem getItemAtIndex getNextItem getNotificationBox getNotificationWithValue getNumberOfVisibleRows getPageById getPreviousItem getResultAt getResultCount getR...
... reset rewind scrollByIndex scrollByPixels scrollToIndex select selectAll selectItem selectItemRange selectTabAtIndex setSelectionRange showPane showPopup sizeTo startEditing stop stopEditing swapDocShells syncSessions timedSelect toggleItemSelection Related DOM element methods DOM:element.addEventListener DOM:element.appendChild DOM:element.compareDocumentPosition DOM:element.dispatchEvent DOM:element.getAttribute DOM:element.getAttributeNode DOM:element.getAttributeNodeNS DOM:element.getAttributeNS DOM:element.getElementsByTagName DOM:element.getElementsByTagNameNS DOM:element.getFeature FIXME: brokenLink DOM:element.getUserData DOM:element.hasAttribute DOM:element.hasAttributeNS DOM:element.hasAttributes DOM:element.hasC...
Node - Archive of obsolete content
Archive › Mozilla › XUL › Node
It represents a single node in the document tree. ...
... Summary This is a scriptable interface corresponding to the nsIDOMNode XPCOM interface. Constants The nsIDOMNode interface is the primary datatype for the entire Document Object Model. It represents a single node in the document tree. For more information on this interface please see DOM-Level-2-Core short ELEMENT_NODE 1 short ATTRIBUTE_NODE 2 short TEXT_NODE 3 short CDATA_SECTION_NODE 4 short ENTITY_REFERENCE_NODE 5 short ENTITY_NODE 6 short PROCESSING_INSTRUCTION_NODE 7 short COMMENT_NODE 8 short DOCUMENT_NODE 9 short DOCUMENT_TYPE_NODE 10 short DOCUMENT_FRAGMENT_NODE 11 short NOTATION_NODE 12 Methods Node appendChild ( Node newChild ) Node cloneNode ( boolean deep ) boolean hasAttributes ( ) boolean hasChildNodes ( ) Node insertBefore ( Node newChild , Node...
Menus - Archive of obsolete content
h a menu item is to use a command element. The example below has the same effect as the previous example, however it uses a command element instead of listening to the command event directly. <command id="cmd_open" oncommand="alert('Open a File!');"/> ... <menuitem label="Open" accesskey="O" command="cmd_open"/> The command attribute should be set to the id of a command element within the same document, in this case 'cmd_open'. The command event will be fired on the command element instead of the menuitem. This is useful when you wish to have several elements performing the same action, for example a menuitem on a menubar, a context menu, and a toolbar button, because you can place the code to execute only once on the command and hook each element up to the command. Menuitems also support disp...
...in each window with a single line: <menu id="menu-tools"/> The overlay should have a menu with the same id 'menu-tools' containing the complete definition of the menu. If you wish to have slight differences between each window, one possibility is to show or hide menu items in a load event listener. For example, to have an item initially hidden in a window: function initMenus() { var item = document.getElementById("menu-file-open"); item.hidden = true; } The hidden property is set to true to hide the menu with the id 'menu-fileOpen'. This function may be called from within an onload attribute on the window. Accessing and Setting the Active Item In a menu, there will usually be an item that is considered "active". This item will be highlighted, and will do certain functions depending ...
PopupKeys - Archive of obsolete content
he menu are selected. If an access key is a pressed that does not correspond to an item within the menu, items that don't have access keys can be selected if the key pressed corresponds to the first letter of the label. Other keys are ignored by the menu key listener, however, the event does not propagate to the main window. This is because the key listener is a capturing listener attached to the document. ...
...u key listener, however, the event does not propagate to the main window. This is because the key listener is a capturing listener attached to the document. For a panel, the only key that is handled by default is the escape key to close the panel. The other keys do not apply. Focus in Popups A menu does not take the keyboard focus. The menu key listener described above captures key events on the document. Thus, a key listener added to a <menupopup> will not receive any key events. Instead, you must add a capturing key listener to the document or window if you want to listen for keys pressed within a menu. Note that the last argument here is true to listen for events during the capturing phase of event propagation: window.addEventListener("keypress", someAction, true); However, the default liste...
controllers - Archive of obsolete content
<< XUL Reference controllers Type: nsIControllers A controllers list attached to the element. The controllers are used to respond to commands. The document's command dispatcher will locate controllers to handle a command by using the focused element's list. ...
... attached to the element. The controllers are used to respond to commands. The document's command dispatcher will locate controllers to handle a command by using the focused element's list. ...
Building Hierarchical Trees - Archive of obsolete content
column the primary column for these to appear. To be able to do this, the tree builder must know that an item is a container. With an RDF datasource, this would usually be an RDF container such as a Seq and the tree would display its children. For an XML datasource, the tree might display a node's children as the children in the tree, making the tree display a hierarchy similar to that in the XML document. Or, with more complex XPath expressions, a template could display a tree where the hierarchy wasn't directly like the XML document. If a node is a container, the tree item becomes a container, and the user may open the row by double-clicking it. Note that this test is done on the member value not the reference value. For instance, in the photo example, we have a container 'http://www.xulplanet.c...
... is a Seq, so it will become a container. The houses are not containers, so they will not have children in the tree. <rdf:Bag rdf:about="http://www.xulplanet.com/rdf/myneighbourhood"> <rdf:li> <rdf:Seq rdf:about="http://www.xulplanet.com/rdf/marion" dc:title="Marion Street"> The result is a two level tree with two columns. For an XML source, a container is a node in the XML document that has children. In this example, the two group elements are displayed at the first level. The individual people are displayed at the next level of the tree as the builder recurses. In this example, we only need to use one rule. <tree datasources="people2.xml" ref="*" querytype="xml" rows="10" flags="dont-build-content"> <treecols> <treecol id="name" primary="true" label="Name" fle...
Accesskey display rules - Archive of obsolete content
XUL elements don't display any accesskeys on Mac XUL elements don't display any accesskeys on Mac. Because MacOS X doesn't have the conception of accesskey function on its native widgets/applications. Basic accesskey display rules On non-Mac platforms, a character which is same as its accesskey is underlined. ...
...arentheses. E.g., when an accesskey of "Open" is 'A', the generated label will be "Open (A)". However, if the last character of the label is an ellipsis or a colon, the accesskey text is inserted before them. I.e., when an accesskey of "Open..." is 'A', the generated label will be "Open (A)...". And also when an accesskey of "Your Name:" is 'B', the generated label will be "Your Name (B):". This document calls the appended text "accesskey text". Always appends accesskey text The basic rules are enough for Western locales. However, in some locales, e.g., Japanese localized build, its most UI labels don't have alphabets but alphabets are used to accesskey. For coherence of the labels on such localized builds, the accesskey text is always appended even if the labels have their accesskey characters. ...
Adding Properties to XBL-defined Elements - Archive of obsolete content
<< PreviousNext >> Next, we'll find out how to add custom properties to XBL-defined elements. The XBL Interface JavaScript and the DOM provide access to get and set the properties of elements. 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. Properties can also be used to hold a value but may have code execute when an attempt is made to retrieve or modify the value. Methods are functions which may be executed. All three are defined within an ...
... get and set the value. The example below creates a button which generates and stores a random number. You can retrieve this same number multiple times by getting the number property from the button. Most of the work here is done in the oncommand handlers. Later, we'll find out how to move this to XBL. XUL: <box id="random-box" class="randomizer"/> <button label="Generate" oncommand="document.getElementById('random-box').number=Math.random();"/> <button label="Show" oncommand="alert(document.getElementById('random-box').number)"/> XBL: <binding id="randomizer"> <implementation> <field name="number"/> </implementation> </binding> A number field has been defined in the binding, which stores the random number. The two extra buttons set and get the value of this fiel...
Broadcasters and Observers - Archive of obsolete content
er the observer notices a change to the attributes of the broadcaster that it is watching. An example is shown below. Example 3 : Source View <broadcasterset> <broadcaster id="colorChanger" style="color: black"/> </broadcasterset> <button label="Test"> <observes element="colorChanger" attribute="style" onbroadcast="alert('Color changed');"/> </button> <button label="Observer" oncommand="document.getElementById('colorChanger').setAttribute('style','color: red');" /> Two buttons have been created, one labeled Test and the other labeled Observer. If you click on the Test button, nothing special happens. However, if you click on the Observer button, two things happen. First, the button changes to have red text and, second, an alert box appears with the message 'Color changed'. What happen...
...ent are changed. Changing the style of the buttons directly will not cause the broadcast to occur so the alert box will not appear. If you tried duplicating the code for the first button several times, you would end up with a series of alert boxes appearing, one for each button. This is because each button is an observer and will be notified when the style changes. Next, we'll look at using the Document Object Model with XUL elements. << PreviousNext >> ...
Custom Tree Views - Archive of obsolete content
e id of the first treecol in the example above. This example is very simple of course -- in reality you would have more complex data in each cell. The final step is to associate the view object with the tree. The tree has a property view, which can be assigned to the view object declared above. We can assign a value to this property at any time to set or change the view. function setView(){ document.getElementById('my-tree').view = treeView; } The following presents the example together. An inline script has been used here to simplify the example. Normally, you would put the script in an external script file. Example custom tree Source <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window title="Tree Example" id="tree-window" xmlns="http://w...
...The setView() function has been called in the onload() ...
More Wizards - Archive of obsolete content
ttribute. It is also called whenever a key is pressed in the textbox, to determine whether the Next button should be enabled again. ...
...ed in the textbox, to determine whether the Next button should be enabled again. ...
Property Files - Archive of obsolete content
ome://myplugin/locale/strings.properties"/> </stringbundleset> Like other non-displayed elements, you should declare all your stringbundles inside a stringbundleset element so that they are all kept together. Getting a String from the Bundle This stringbundle element has a number of properties. The first is getString which can be used in a script to read a string from the bundle. var strbundle = document.getElementById("strings"); var nofilesfound=strbundle.getString("notFoundAlert"); alert(nofilesfound); This example first gets a reference to the bundle using its id Then, it looks up the string 'notFoundAlert' in the property file. The function getString() returns the value of the string or null if the string does not exist. Finally, the string is displayed in an alert box. Text Formattin...
...ring() returns the value of the string or null if the string does not exist. Finally, the string is displayed in an alert box. Text Formatting The next method is getFormattedString(). This method also gets a string with the given key name from the bundle. In addition, each occurrence of formatting code (e.g. %S) is replaced by each successive element in the supplied array. var dir = "/usr/local/document"; var count = 10; var strbundle = document.getElementById("strings"); var result = strbundle.getFormattedString("resultMessage", [ dir, count ]); alert(result); This example will display following message in an alert box. 10 files found in the /usr/local/document directory. You will notice the formatting codes %1$S and %2$S is used, and replaced different order in the array. Formatting code %...
Tree View Details - Archive of obsolete content
<treecol id="element" label="Element" primary="true" flex="1"/> </treecols> <treechildren/> </tree> </window> We use a simple tree here with no data in the treechildren. The 'init' function is called when the window is loaded to initialize the tree. It simply sets the custom view by retrieving the tree and setting its 'view' property. We will define 'treeView' next. function init() { document.getElementById("elementList").view = treeView; } The custom tree view will need to implement a number of methods, of which the important ones will be examined individually. First we'll define two structures to hold the data for the tree, the first will hold a map between parents and the children they contain, and the second will hold an array of the visible items. Remember that a custom view mu...
... << PreviousNext >> ...
XUL Tutorial - Archive of obsolete content
xes Adding More Elements More Layout Elements Stacks and Decks Stack Positioning Tabboxes Grids Content Panels Splitters Toolbars and Menus Toolbars Simple Menu Bars More Menu Features Popup Menus Scrolling Menus Events and Scripts Adding Event Handlers More Event Handlers Keyboard Shortcuts Focus and Selection Commands Updating Commands Broadcasters and Observers Document Object Model Document Object Model Modifying a XUL Interface Manipulating Lists Box Objects XPCOM Interfaces XPCOM Examples Trees Trees More Tree Features Tree Selection Custom Tree Views Tree View Details Tree Box Objects RDF and Templates Introduction to RDF Templates Trees and Templates RDF Datasources Advanced Rules Persistent Data Skins and Locales Adding Sty...
...L XBL Example Specialized Window Types Features of a Window Creating Dialogs Open and Save Dialogs Creating a Wizard More Wizards Overlays Cross Package Overlays Installation Creating an Installer Install Scripts Additional Install Features This XUL tutorial was originally created by Neil Deakin. He has graciously given us permission to use it as part of the MDN. Original Document Information Author: Neil Deakin Copyright Information: (C) 1999-2005 XULPlanet.com ...
Using multiple DTDs - Archive of obsolete content
But there are situations where you want to use multiple DTDs, for example to localize common widgets used in all your XUL files, additionally to the ones specific to the file. Single DTD To make strings in your XUL file localizable, you normally add a DTD declaration at the beginning of the file like this: <!DOCTYPE window SYSTEM "chrome://myextension/locale/mainwindow.dtd"> where "window" is the local name of the document (root) element. ...
...s where you want to use multiple DTDs, for example to localize common widgets used in all your XUL files, additionally to the ones specific to the file. Single DTD To make strings in your XUL file localizable, you normally add a DTD declaration at the beginning of the file like this: <!DOCTYPE window SYSTEM "chrome://myextension/locale/mainwindow.dtd"> where "window" is the local name of the document (root) element. Assuming you have an entity called someButton.label defined in mainwindow.dtd, you can access the entity like this: <button id="somebutton" label="&someButton.label"> Multiple DTDs If you want to use multiple DTDs with your XUL file, you can simply list all of the DTDs inside your DTD declaration: <!DOCTYPE window [ <!ENTITY % commonDTD SYSTEM "chrome://myextensions/locale...
XUL and RDF - Archive of obsolete content
This section makes a technical argument both for having XUL in the first place and for using RDF as the underlying implementation of XUL's content model. ...
...This section makes a technical argument both for having XUL in the first place and for using RDF as the underlying implementation of XUL's content model. ...
XML - Archive of obsolete content
y will with it. This is what XML is: a meta-language for defining languages appropriate to the tasks at hand; It's structured in a way that makes it accessible as "information" to both humans and machines. HTML -- which is a derived language like our MemoML (see the Appendix notes for information on the geneology of markup languages) -- has been created for the purposes of representing hypertext documents and the basic relationships between them. Humans read raw HTML often when they edit HTML documents, though this is changing as regular HTML editors are replaced by WYSIWYG HTML editors, and so do HTML parsers, which use the markup to format the document in its presentational form in web browsers. Like HTML and MemoML, XUL is an XML-based language. Where in HTML the elements are used to describe...
...ngredients rather than the chef. This arrangement creates new possibilities for truly cross-platform web applications, application serving, web appliances and embedded systems, and all sort of other things. Like all really good technologies, XUL and its XP cousins are already being used in ways not imagined by their creators and growing propitiously out of control. Author: Ian T. Oeschger Other Documents: XML in Mozilla Original Document Information Author(s): Ian T. Oeschger Last Updated Date: November 13, 2001 Copyright Information: Copyright (C) Ian T. Oeschger ...
colorpicker - Archive of obsolete content
ed in different ways for different XUL Input Elements as listed below: onchange Type: script code TextBox When Enter key is pressed Radio/Check Box When the state is changed Select List When the selected item is changed What is accessible The script context at this point can only access the following things: Global Values/Functions i.e. ...
...n Type: boolean Returns true if the popup for a button-type colorpicker is open. Set this property to true to open the popup or false to close the popup. tabIndex Type: integer Gets and sets the value of the tabindex attribute. ...
description - Archive of obsolete content
ap when displayed <description> This is a long section of text that will word wrap when displayed. </description> This is a long section of text that will not word wrap <description value="This is a long section of text that will not word wrap"> </description> This is a long section of dynamically controlled text that will word wrap <description id="desc" style="width: 300px"></description> document.getElementById('desc').textContent = "This is a long section of dynamic message text that will word wrap"; Attributes crop Type: one of the values below If the label of the element is too big to fit in its given space, the text will be cropped on the side specified by the crop attribute. An ellipsis will be used in place of the cropped text. If the box direction is rev...
...r Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
key - Archive of obsolete content
Archive › Mozilla › XUL › key
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
...ey/> <!-- These elements don't handle any key events --> <key key="" modifiers="control"/> <key keycode="" modifiers="control"/> Modifying attributes In case you want to change one of the <key>'s attributes, such as the modifiers attribute, the keyset element has to be re-added to its parent node; otherwise the new attributes won't be applied. For example: // modify some attributes let key = document.getElementById(KEY_ID); key.setAttribute("modifiers", "alt shift"); // apply the changes let keyset = document.getElementById(KEYSET_ID); keyset.parentNode.appendChild(keyset); ...
listcell - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
...l-iconic Use this class to have an image appear on the listcell. Specify the image using the image attribute. Note that both an image and a label are added when this style is set. The label will take up extra space even when no label text is set. ...
notificationbox - Archive of obsolete content
ll notifications. This property is read-only. notificationsHidden Type: boolean Indicating whether the notification area should be hidden. Events AlertActive Type: Event Fired when a notification element is shown. AlertClose Type: Event Fired when a notification element is closed. ...
...setUserData appendNotification( label , value , image , priority , buttons, eventCallback ) Return type: element Create a new notification and display it. If another notification is already present with a higher priority, the new notification will be added behind it. label - label to appear on the notification. This should be either a string, or, from Gecko 37 onwards, you can pass a DocumentFragment with rich content as well. Keep in mind that this is all XUL so using HTML elements for 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. but...
preferences - Archive of obsolete content
so executes code specified in onchanged attribute of the element. See also the description of change event of <preference>. void observe(in nsISupports aSubject, in string aTopic, in wstring aData); nsIObserver method used internally to react to changes to preferences listed as children of this element. ...
...sertBefore(), isDefaultNamespace(), isEqualNode, isSameNode, isSupported(), lookupNamespaceURI, lookupPrefix, normalize(), querySelector(), querySelectorAll(), removeAttribute(), removeAttributeNode(), removeAttributeNS(), removeChild(), removeEventListener(), replaceChild(), setAttribute(), setAttributeNode(), setAttributeNodeNS(), setAttributeNS(), setUserData Related Preferences System documentation: Introduction: Getting Started | Examples | Troubleshooting Reference: prefwindow | prefpane | preferences | preference | XUL attributes ...
prefpane - Archive of obsolete content
(1) an example of a widget that has state changes tracked for it includes the checkbox element, whose state is tracked automatically when the "command" event fires. void writePreferences(in boolean flushToDisk); Writes all changes in this pane to preferences, optionally flushes to disk. ...
...tion/javascript" src="chrome://myext/content/script0.js"> <script type="application/javascript" src="chrome://myext/content/script1.js"> </prefwindow> When opening a dialog with multiple panes you must include the toolbar feature in the call to openDialog, for example: window.openDialog("chrome://example/content/prefwin.xul", "", "chrome,toolbar"); Related prefwindow Preferences System documentation: Introduction: Getting Started | Examples | Troubleshooting Reference: prefwindow | prefpane | preferences | preference | XUL attributes ...
progressmeter - Archive of obsolete content
The default value if not specified is 100 such that the value may be used as a percentage. mode Type: one of the values below A determinedprogressmeter is used in cases where you know how long an operation will...
...ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
tabbox - Archive of obsolete content
t specified, events are listened to from the tabbox. Thus, if this attribute is not used, the tabbox or an element inside it must have the focus for the keyboard navigation to apply. parent Keyboard navigation is captured at the parent of the tabbox. window Keyboard navigation is captured at the window level. Tab navigation will occur as long as any element in the window is focused. document Keyboard navigation is captured at the document level. Tab navigation will occur as long as any element in the document is focused. handleCtrlTab Type: boolean If set to true or omitted, the tabbox will switch to the next tab when the Control and Tab keys are pressed. If the Shift key is also held down, the previous tab will be displayed. If this attribute is set to false, these...
...will always be one of the tab elements in the tabs element. Assign a value to this property to modify the currently selected tab. tabs Type: tabs element The tabs element contained within the tabbox. tabpanels Type: tabpanels element The tabpanels element contained within the tabbox. ...
textbox - Archive of obsolete content
es a character. If the user types another character, the timer resets. type Type: one of the values below You can set the type attribute to one of the values below for a more specialized type of textbox. Don't set the type if you wish to use a regular textbox. autocomplete A textbox that supports autocomplete. For more information about autocomplete textboxes, see the autocomplete documentation (XPFE [Thunderbird/SeaMonkey]) (Firefox) number A textbox that only allows the user to enter numbers. In addition, arrow buttons appear next to the textbox to let the user step through values. There are several attributes that allow the number textbox to be configured, including decimalplaces, min, max, increment, wraparound, hidespinbuttons, and textbox.value. password A textbox th...
...n value Sets the selected portion of the textbox, where the start argument is the index of the first character to select and the end argument is the index of the character after the selection. Set both arguments to the same value to move the cursor to the corresponding position without selecting text. ...
wizard - Archive of obsolete content
ge, pageCount, pageIndex, pageStep, title, wizardPages Methods advance, cancel, extra1, extra2, getButton, getPageById, goTo, rewind Examples <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <wizard id="theWizard" title="Secret Code Wizard" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function checkCode(){ document.getElementById('theWizard').canAdvance = (document.getElementById('secretCode').value == "cabbage"); } </script> <wizardpage onpageshow="checkCode();"> <label value="Enter the secret code:"/> <textbox id="secretCode" onkeyup="checkCode();"/> </wizardpage> <wizardpage> <label value="That is the correct secret code."/> </wizardpage> </wizard> Attributes activetitl...
...order. title Type: string The title that appears at the top of the wizard. This is overridden by the label attribute on the individual pages. wizardPages Type: DOM NodeList of wizardpage elements This property holds the list of wizardpage elements in the wizard. ...
Building XULRunner with Python - Archive of obsolete content
on to the usual Java Script. This gives access to Python features and modules and builds on Mark Hammond's pyXPCOM work from Active State. XPCOM components can also be created in Python. Currently (Mar 07) Python is not enabled by default so a custom build of Mozilla is needed. This page provides instructions in the hope of eliminating much trial and error. You should also read the the developer documentation on source code and building as wells as PyXPCOM XULRunner with Python promises to be a good platform for accessibility projects and both Jambu Alternative Input and the IAccessible2 test tool are using it. Of particular interested is access to MSAA and IAccessible2 via the Python comtypes package. Development Machine Setup First a word of warning that ZoneAlarm has exhibited memory leak...
...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") btnTest.addEventListener('command', onTest, False) def onTest(): window.alert('Button activated') window.addEventListener('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 d...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
d. You'll get a warm fuzzy feeling from mastering the complex but very powerful Mozilla build system. And all that furniture you smash in the meantime makes great kindling to get you through those cold winter nights. Let's face it, it was probably time for you to get some new furniture anyway. Everything you ever wanted to know about building Mozilla (and thus XULRunner) can be found in the Build Documentation. Follow the instructions for meeting build requirements and getting the source, then come back here since the build process itself will be slightly different. Got source? Now you need to set up a special .mozconfig file to tell Mozilla to build both XULRunner and your application. Here's a sample .mozconfig for building XULRunner and McCoy: # Options for client.mk. mk_add_options MOZ_BUILD_P...
... ...
XULRunner tips - Archive of obsolete content
Note: I use this method of installing extensions into all of my Mozilla applications. This way I have one directory where I keep all my Mozilla extensions, and each applicati...
... Note: I use this method of installing extensions into all of my Mozilla applications. This way I have one directory where I keep all my Mozilla extensions, and each application (Firef...
XULRunner - Archive of obsolete content
Firefox (from version 3) ships with a private XULRunner package, which can run any compatible XULRunner application using the -app switch: firefox -app application.ini is equivalent to xulrunner -app application.ini Older builds are also available. Overview Development Plan What XULRunner Provides XULRunner FAQ Nightly builds: unstable-trunk Documentation Getting Started with XULRunner Short tutorial on building desktop applications with XULRunner. XUL Tutorial Once you have a working XULRunner application, use the XUL tutorial to expand it into a fantastic XUL application. XULRunner tips A collection of tips for working with XULRunner. Deploying XULRunner An introduction on how to package your ap...
...L Tutorial Once you have a working XULRunner application, use the XUL tutorial to expand it into a fantastic XUL application. XULRunner tips A collection of tips for working with XULRunner. Deploying XULRunner An introduction on how to package your application with XULRunner. XULRunner Hall of Fame Tracks all available applications based on XULRunner. Build Documentation Learn how to get the source and build it. Debug Documentation Steps to configure Venkman to debug your App XULRunner Guide A fairly complete, but outdated, introduction and tutorial for XULRunner which collates much of the documentation found here. View all... Community View Mozilla forums... Mailing list Newsgroup RSS feed ...
Mozprocess - Archive of obsolete content
For more information about mozprocess as part of the mozbase project, please see the mozbase project page. mozprocess provides python process management via an operating system and platform transparent interface to Mozilla platforms of interest. Mozprocess aims to provide the ability to robustly terminate a process (by timeout or otherwise), along with any child processes, on Windows, OS X, and Linux. Mozprocess utilizes and extends subprocess.Popen to these ends. API mozprocess.processhandler:ProcessHandler is the central exposed API for mozprocess. ProcessHandler utilizes a contained subclass of subprocess.Popen, Process, which does the brunt of the process management. ...
...lts to os.environ ) exit_code = process.waitForFinish(timeout=60) # seconds See an example in https://github.com/mozilla/mozbase/b...profilepath.py ProcessHandler may be subclassed to handle process timeouts (by overriding the onTimeout() method), process completion (by overriding onFinish()), and to process the command output (by overriding processOutputLine()). TODO Document improvements over subprocess.Popen.kill ...
2006-09-29 - Archive of obsolete content
Meetings None for this week. ...
...hold The author of the Thunderjudge extension is currently putting the development of the extension on hold due to several issues (more details available at the website). He is also asking if there are developers out there who know the TB core and are willing to help him out. Discussions Developer documentation issues for Thunderbird 2 Eric Shepherd has requested feedback for any developer documentation issues that might need dealing with for Thunderbird 2. Meetings None for this week. ...
2006-10-13 - Archive of obsolete content
Discussions Shared training.dat & message filters Jon-Mikel is looking for suggestions on sharing spam filter data and message filters between machines easily. ...
... Discussions Shared training.dat & message filters Jon-Mikel is looking for suggestions on sharing spam filter data and message filters between machines easily. ...
2006-11-24 - Archive of obsolete content
...
... ...
NPN_GetURL - Archive of obsolete content
rowser instance. _self or _current: Load the link into the same window the plug-in instance occupies. Not recommended; if target refers to the window or frame containing the instance, the instance is destroyed and the plug-in may be unloaded. Use with NPN_GetURL() only if you want to terminate the plug-in. _parent: Load the link into the immediate <frameset> parent of the plug-in instance's document. If the plug-in instance's document has no parent, the default is _self. _top: Load the link into the plug-in instance window. The default is _self, if the plug-in instance's document is already at the top. Use for breaking out of a deep frame nesting. If the target is null, the browser creates a new stream and delivers the data to the current instance regardless of the MIME type of the ...
...owser, it works here, except for the _self target. Returns If successful, the function returns NPERR_NO_ERROR. If unsuccessful, the plug-in is not loaded and the function returns an error code. For possible values, see Error codes. Description NPN_GetURL() is used to load a URL into the current window or another target or stream. Plug-ins can use this capability to provide hyperlinks to other documents or to retrieve data from anywhere on the network. This is especially useful for enabling an existing application to operate on the web. For HTTP URLs, the browser resolves this method as the HTTP server method GET, which requests URL objects. Use NPN_GetURLNotify() instead of NPN_GetURL() in these cases: To request a stream and receive notification of the result. If the buffer contains header...
Security Controls - Archive of obsolete content
uding a network-based firewall, a host-based firewall, and OS patching. The motivation for having multiple layers is that if one layer fails or otherwise cannot counteract a certain threat, other layers might prevent the threat from successfully breaching the system. A combination of network-based and host-based controls is generally most effective at providing consistent protection. ...
...m. A combination of network-based and host-based controls is generally most effective at providing consistent protection. Original Document Information Author(s): U.S. Department of Commerce Title: Federal Information Processing Standard Publication 200, Minimum Security Requirements for Federal Information and Information Systems Last Updated Date: March 2006 Copyright Information: This document is not subject to copyright. Original Document Information Author(s): Karen Scarfone, Wayne Jansen, and Miles Tracy Title: NIST Special Publication 800-123, Guide to General Server Security Last Updated Date: July 2008 Copyright Information: This document is not subject to copyright. ...
Digital Signatures - Archive of obsolete content
But encryption and decryption, by themselves, do not address another problem: tampering. This section describes how public-key cryptography addresses the problem of tampering. Tamper detection and related authentication techniques rely on a mathematical function called a one-way hash (also called a message digest). A one-way hash is a number of fixed length with the following characteristics: The value of the hash is unique for the hashed data. ...
...t is difficult to deny doing so later, assuming that the private key has not been compromised or out of the owner's control. This quality of digital signatures provides a high degree of nonrepudiation; that is, digital signatures make it difficult for the signer to deny having signed the data. In some situations, a digital signature may be as legally binding as a handwritten signature. Original Document Information Author(s): Ella Deon Lackey Last Updated Date: 2012 Copyright Information: (C) 2012 Red Hat, Inc. Link: Red Hat Certificate System Common Criteria Certification 8.1: Deployment, Planning, and Installation ...
Security - Archive of obsolete content
But encryption and decryption, by themselves, do not address another problem: tampering.Encryption and DecryptionEncryption is the process of transforming information so it is unintelligible to anyone but the intended recipient. ...
...intelligible to anyone but the intended recipient. Decryption is the process of transforming encrypted information so that it is intelligible again.Introduction to Public-Key CryptographyPublic-key cryptography and related standards and techniques underlie the security features of many products such as signed and encrypted email, single sign-on, and Secure Sockets Layer (SSL) communications. This document introduces the basic concepts of public-key cryptography. For an overview of SSL, see "Introduction to SSL." For an overview of encryption and decryption, see "Encryption and Decryption." Information on digital signatures is available from "Digital Signatures." Introduction to SSLThis document introduces the Secure Sockets Layer (SSL) protocol. SSL has been universally accepted on the World W...
Table Reflow Internals - Archive of obsolete content
The initial chunk of an xml doc is loaded. The initial chunk of an html doc (or a subsequent chunk of an xml doc) is loaded. The container posts a dirty reflow command with itself as the target. Content is inserted, appended, or deleted through the DOM. The container posts a dirty reflow command with itself as the target. ...
...ete because its block is incomplete. ...
Building a Theme - Archive of obsolete content
start up with an empty theme, Firefox will be unusable, as the button elements will be drawn as plain text. This is why we copied the default styles in the setup step. When writing a theme, the easiest way to determine what CSS selectors you need to write is to use the DOM Inspector which you should have installed in the setup step. ...
... step. You can use this to inspect any element in a web page or an XUL document, which makes it invaluable for themes. Updating the toolbar's Styling Note In Firefox 4.0 and up, the highlight feature of DOM Inspector is broken. To workaround this, disable Hardware Acceleration in Firefox' Options. Open up the DOM Inspector now (located under the "Tools" menu), and go to "File->Inspect Chrome Document". This will be a menu containing all the XUL documents currently open in Firefox. Pick the first document with a web page title, like "Firefox Start Page" and select it. For this tutorial, we're going to update the background color of the toolbars. Select the node finding tool (the arrow-plus-box in the top-left corner of the DOM Inspector), and click on any unused space on a toolbar. This shou...
Scratchpad - Archive of obsolete content
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 icon next to each suggestion indicates the type, and the currently highlighted suggestion gets a popup with more information. ? and ? cycle through the suggestions and Enter or Tab select the highlighted choice. Inline documentation To show the inline documentation popup, press Ctrl + Shift + Space when the cursor is on an identifier. For example, if you type document.addEventListener, then press Ctrl + Shift + Space, you'll see a popup that shows a summary of the function's syntax and a short description: The "[docs]" link takes you to the MDN documentation for the symbol. Executing Once you've written your code, s...
... In the Editor Preferences section of the developer tools settings, you can choose to use Vim, Emacs, or Sublime Text key bindings instead. To select these, visit about:config, select the setting devtools.editor.keymap, and ass...
Summary of Changes - Archive of obsolete content
elements deprecated bgcolor CSS1 background-color: ; non-standard EMBED HTML 4.01 OBJECT deprecated APPLET HTML 4.01 OBJECT non-standard MARQUEE HTML 4.01 DIV plus scripting non-standard BGSOUND HTML 4.01 OBJECT Proprietary or Deprecated Feature W3C Feature or Recommended Replacement IE5+ id_attribute_value document.all.id_attribute_value document.all[id_attribute_value] DOM level 2: document.getElementById(id_attribute_value) IE5+ FormName.InputName.value DOM level 1: document.forms["FormName"].InputName.value IE5+ InputName.value DOM level 1: document.forms["FormName"].InputName.value IE5+ FormCtrlName DOM level 1: document.forms["FormName"...
...ent.all[id_attribute_value] DOM level 2: document.getElementById(id_attribute_value) IE5+ FormName.InputName.value DOM level 1: document.forms["FormName"].InputName.value IE5+ InputName.value DOM level 1: document.forms["FormName"].InputName.value IE5+ FormCtrlName DOM level 1: document.forms["FormName"].FormCtrlName IE5+ document.forms(0) DOM level 1: document.forms[0] IE ElemRef.innerText DOM Level 1 (Core) interface We could introduce DOM 3 Core textContent attribute here which is supported by Mozilla 1.5+ and is a perfect equivalent to innerText. http://www.w3.org/TR/2004/REC-DOM-Le...e3-textContent IE5+ ElemRef.style.pixelTop DOM level 2: parseInt(ElemRef.style.top, 10) ...
:-moz-full-screen-ancestor - Archive of obsolete content
However, those elements' ancestors have this pseudo-class applied to them. This pseudo-class was removed in Firefox 50. ...
...However, those elements' ancestors have this pseudo-class applied to them. This pseudo-class was removed in Firefox 50. ...
Accessing XML children - Archive of obsolete content
operator or [] notation to set properties. var a = {}; a.foo = 1; a["bar"] = 2; In E4X, the . and [] operators provide access to the child nodes of an E4X element. var element1 = <foo> <bar/> </foo>; var element2 = <baz/>; element1.bar.appendChild(element2); element1["bar"].appendChild(<quux/>); adds a child to the "bar" child node of element1. This gives an XML document of <foo> <bar> <baz/> <quux/> </bar> </foo> Note, however, that assigning a non-XML value to a child element that doesn't exist will create that element. var element1 = <foo/> element1.bar = 1; produces <foo> <bar>1</bar> </foo> If the child node already exists, the . operator allows you to change its value. var elem = <foo> <bar>1</bar> </foo> elem.bar = ...
... <bar baz="1">red</bar> <bar baz="2">blue</bar> </foo>; var list = element.bar; list.length(); // returns 2 list[0]; // the first bar element list[1]; // the second bar element Notice further that this list is "live" in the sense that changes made to the list are reflected back in the element that the list originally came from. list[1] = "green"; changes the XML document to read <foo> <bar baz="1">red</bar> <bar baz="2">green</bar> </foo> Special types of nodes XML objects have methods for accessing XML lists of certain common types of nodes as well. var a = <foo> Some text <bar>not text</bar> More text </foo>; var list = a.text(); list.length(); // returns 2 list[0]; // returns " Some text " list[1]; // returns " More text " You can similarly access commen...
Error.number - Archive of obsolete content
word is the facility code, and the lower word is the error code. To determine the error code, use the & (bitwise And) operator to combine the number property with the hexadecimal number 0xFFFF. Example The following example causes an exception to be thrown and displays the error code that is derived from the error number. try { // Cause an error. var x = y; } catch(e) { document.write ("Error Code: "); document.write (e.number & 0xFFFF) document.write ("<br />"); document.write ("Facility Code: ") document.write(e.number>>16 & 0x1FFF) document.write ("<br />"); document.write ("Error Message: ") document.write (e.message) } Example The output of this code is as follows. Error Code: 5009 Facility Code: 10 Error Message: 'y' is undefin...
...Also supported in Store apps (Windows 8 and Windows Phone 8.1). ...
GetObject - Archive of obsolete content
mitted, GetObject returns a currently active object of the specified type. If no object of the specified type exists, an error occurs. Some applications allow you to activate part of a file. To do so, add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file you want to activate. For information on how to create this string, see the documentation for the application that created the object. For example, in a drawing application you might have multiple layers to a drawing stored in a file. You could use the following code to activate a layer within a drawing called SCHEMA.CAD: var LayerObject = GetObject("C:\\CAD\\SCHEMA.CAD!Layer3"); If you do not specify the object's class, Automation determines which application to start and wh...
... object. If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times ActiveXObject is executed. With a single-instance object, GetObject always returns the same instance when called with the zero-length string ("") syntax, and it causes an error if the pathname argument is omitted. Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, and Internet Explorer 8 standards. ...
VBArray.dimensions - Archive of obsolete content
Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
...Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
VBArray.lbound - Archive of obsolete content
Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
...Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
VBArray.ubound - Archive of obsolete content
Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
...Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
@cc_on - Archive of obsolete content
nditional compilation 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. ...
...ou 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. /*@cc_on @*/ /*@ document.write("JavaScript version: " + @_jscript_version + "."); document.write("<br />"); @if (@_win32) document.write("Running on the 32-bit version of Windows."); @elif (@_win16) document.write("Running on the 16-bit version of Windows."); @else document.write("Running on a different operating system."); @end @*/ Requirements Supported in all versions of Internet Explorer, but not in Windows 8.x Store apps. ...
@if - Archive of obsolete content
nd-line programs. 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. ...
...n 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. /*@cc_on @*/ /*@ document.write("JavaScript version: " + @_jscript_version + "."); document.write("<br />"); @if (@_win32) document.write("Running on a 32-bit version of Windows."); @elif (@_win16) document.write("Running on a 16-bit version of Windows."); @else document.write("Running on a different operating system."); @end @*/ Requirements Supported in all versions of Internet Explorer, but not in Windows 8.x Store apps. ...
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
rounding errors force the two floats to total more than 100% the width of the parent, as could happen if the floats' element boxes were made to total 50%. Unfortunately, a few browsers don't get this right, and end up flowing the cards as a single vertical column instead of putting the fish side by side. After a bit of fiddling to try to fix this, I decided that trying to overcome this error in document flow wasn't worth the effort. The layout wasn't bad if the fish weren't laid out next to each other, so I moved on. Floating Fish With the cards set up to float, the next step was to place the images appropriately. This involved floating the image inside the floated div. It just seemed like a Fish Cam page should have a lot of floating for some reason. I also added a border to the image, so tha...
...the idea of using simple markup and CSS to create interesting effects, if you weren't already. With just the few elements I had available in this example, there were any number of possibilities for design effects, and I think you'll find the same to be true for your own designs if you just give this sort of approach a try. - FIN. - Related Links The Amazing Netscape Fish Cam Page Original Document Information Author(s): Eric Meyer, Standards Evangelist, Netscape Communications Last Updated Date: Published 25 Apr 2003 Copyright Information: Copyright (C) 2001-2003 Netscape. All rights reserved. Note: This reprinted article was originally part of the DevEdge site. ...
Requests For Enhancement - Archive of obsolete content
Archive › Web › XForms › RFE
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. But a form author is not restricted to only those XML languages that Gecko knows. A lot of the XForms capabilities are reachable by using our Custom Controls interfaces. Our Custom Control interfaces allows for the exchange of data between any XML element and and an XForms model. This means that an author can write powerful Mozilla-based applications by using XForms. If previously you was force...
...custom control due to limitations in our interfaces or the functionality of our controls, then this is the right place to pass along your requirements. Custom Controls If you have a custom control that you believe will help fulfill the needs of form authors or other custom controls authors, please file it here. This section could be of particular interest to people using custom controls in XUL documents for the following reasons: XUL, in many cases, is much better suited for application development than XHTML. Therefore the control set may need to be more extensive to address the wider spectrum of requirements that a XUL application will have on its controls. XUL is a feature of Mozilla only and custom control authors should be aware their controls won't work on other browser platforms. En...
XForms Alert Element - Archive of obsolete content
Introduction This message will be shown when the form control cannot properly bind to instance data or when the instance data value is invalid or out of the specified range of selectable values (see the spec). The message of the alert element can exist in instance data, in a remote document, or as inline text. If more than one source of message is specified in this element, the order of precedence is: single node binding attributes, linking attributes, inline text. Attributes Single-Node Binding Linking src - URL of a document whose contents will be retrieved by the alert element and used to provide the alert message for the containing form control. Type restrictions The alert element can be bound to any simple content. Representations Can be represented in two ways: modeless win...
... used to provide the alert message for the containing form control. Type restrictions The alert element can be bound to any simple content. Representations Can be represented in two ways: modeless window that contains the alert element's message (default representation). the alert element's message can also be displayed immediately after the containing form control element in the XForms document's layout. This representation is used if the alert element has an inline display style. Examples <xforms:model> <xforms:instance> <data xmlns=""> <x>10</x> </data> </xforms:instance> <xforms:bind id="x" nodeset="x" type="xsd:integer"/> </xforms:model> <style> @namespace xforms url("http://www.w3.org/2002/xforms"); xforms|input:invalid xforms|alert.inline { display: inline; ...
XForms Label Element - Archive of obsolete content
Introduction Specifies the label (short description) for the XForms control (see the spec). Every form control other than the output and choices elements must contain a label element. It is valid for a form control to have an empty label element. The label text can be specified in instance data, in a remote document, or as inline text. If more than one source of label text is specified for this element, the order of precedence is: single node binding attributes, linking attributes, inline text. UI behavior accesskey support - if the accesskey attribute is specified on labeled XForms controls or on the label element itself then the label text for the control will contain an indicator as to what the access key is in a standard way. Usually by underlining the accesskey character in the label t...
...is in a standard way. Usually by underlining the accesskey character in the label text. focus behavior - when a label element is clicked or its accesskey is activated then the form control that contains the label will be given the focus. Attributes UI Common accesskey - used to specify the keyboard shortcut for focusing the parent form control. Single-Node Binding Linking src - URL of a document whose contents will be retrieved by the label element and used to provide label text for the containing form control. Type restrictions The label element can be bound to any simple content. Representations The XForms label element is represented by the text retrieved from instance data, a document or the label element's own inline content. ...
Mozilla XForms User Interface - Archive of obsolete content
Currently XForms can be hosted by XHTML and XUL in Seamonkey and Firefox. Later we have plans to support XForms hosted by SVG. The XForms specs define two kinds of XForms UI elements, called 'Form Controls' and 'XForms User Interface'. Elements from the "Form Controls" group allows users to interact with instance data. ...
...ggle elements (see the spec). The switch element contains case elements which in turn contain markup. Only the contents of a single case may be displayed at one time. The toggle element is used (as an event handler) to make a case visible and thereby hiding all other case elements contained by the same switch. repeat A repeat element contains markup and is itself bound to a nodeset in an instance document (see the spec). For each node in the nodeset, the contents of the repeat element will be displayed in the form. That node will serve as the context node for any relative xpath expressions in that set of repeated markup. For example, if a repeat is bound to a nodeset that contains 5 nodes and the repeat contains an output element that echoes the current node, then the user will see 5 outputs in th...
Using XForms and PHP - Archive of obsolete content
tips on using XForms and PHP together. Returning XML data To either serve a page (with XForms in it) or to generate data used as instance data for XForms, the page needs to be served as XML, for example application/xhtml+xml. To do that, you need to use the header() PHP function: <?php header("Content-Type: application/xhtml+xml; charset=UTF-8"); ... ?> But remember this (quote from PHP documentation): Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file. Parsin...
...ile access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file. Parsing Submitted Data Depending on the submission type, you might get different data formats on the server side. To really use the power of XForms (/XML) you would probably submit XML. There is some help in getting to the raw XML on the PHP Documentation site. How to actually parse and use the XML data depends heavily on what you want to achieve and on the PHP version. To get a DOM Document on PHP 4 I usually do something like this: $data = $HTTP_RAW_POST_DATA; $dom = domxml_open_mem($data); $root = $dom->document_element(); ... $newnode = $dom->create_element("boo"); $root->append_child($newnode); ... ...
XForms - Archive of obsolete content
Mozilla XForms extension. This extension, while supporting a significant subset of the XForms 1.0 and 1.1 candidate recommendations, is not actively maintained any more since about 2010. The last official release has been done for Firefox 3.6 and is available for download on addons.mozilla.org. For more details about the future of the Mozilla XForms extension see this blog post. Documentation Implementation status Implementation status of the Mozilla XForms extension Building Get started with building your own XForms extensions from source. Troubleshooting tips for XForms A small collection of tips for troubleshooting common problems with XForms forms. Mozilla XForms specials Explains where, and how, Mozilla XForms deviates...
...and how, Mozilla XForms deviates or extends the XForms 1.0 specification. XForms custom controls Custom controls lets the form author "skin" each XForms control through XBL, and create f.x. an SVG input control. XForms user preferences A description of the about:config variables that XForms uses. XForms API reference XForms interfaces documentation. XForms UI Elements reference XForms user interface elements documentation. View All... Community View Mozilla forums... Mailing list Newsgroup RSS feed #xforms channel on irc.mozilla.org W3C Forms mailing list Other community links... Tools XForms validator XForms Buddy ...
Displaying a graphic with audio samples - Archive of obsolete content
<!DOCTYPE html> <html> <head> <title>JavaScript Spectrum Example</title> </head> <body> <audio id="audio-element" src="revolve.ogg" controls="true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <img id="mozlogo" style="display:none" src="mozilla2.png"></img> <script> var canvas = document.getElementById('fft'), ctx = canvas.getContext('2d'), channels, rate, frameBufferLength, fft; function loadedMetadata() { channels = audio.mozChannels; rate = audio.mozSampleRate; frameBufferLength = audio.mozFrameBufferLength; fft = new FFT(frameBufferLength / channels, rate); ...
... ctx.fillRect (0,0, canvas.width, canvas.height); ctx.fillStyle = "rgb(255,255,255)"; for (var i = 0; i < signal.length; i++ ) { // multiply spectrum by a zoom value magnitude = signal[i] * 1000; // Draw rectangle bars for each frequency bin ctx.fillRect(i * 4, canvas.height, 3, -magnitude); } ctx.drawImage(document.getElementById('mozlogo'),0,0, canvas.width, canvas.height); } var audio = document.getElementById('audio-element'); audio.addEventListener('MozAudioAvailable', audioAvailable, false); audio.addEventListener('loadedmetadata', loadedMetadata, false); </script> </body> </html> ...
Fixing Incorrectly Sized List Item Markers - Archive of obsolete content
n ordered lists, where the number that precedes each list item may be obviously different than the content that follows it. In fact, the markers were set to be a uniform size that did not change to match the content of the list items, so in rare cases the marker might actually appear to be smaller. See bug 110360, which explains the problem and shows when the fix was applied. In addition, when a document is displayed in "quirks" mode in Mozilla 0.9.4 and later, the markers of lists will not use the font size of the list item text, but will instead stay the same as the user's default font size. See bug 97351 for more details. The Solution Fortunately, there are Mozilla-specific CSS-like rules that can be used to correct both problems. The following rule is derived from Mozilla's html.css file: ...
..., *:-moz-list-number {font-size: 1em;} Recommendations If it is important to make list item markers match the font size of the content, use one of the suggested rules. In situations where validation is a priority, segregate the rule into a separate stylesheet so that the rule will not confuse CSS validators run against the main stylesheet. Related Links bug 110360 bug 97351 Original Document Information Author(s): Eric A. Meyer, Netscape Communications Last Updated Date: Published 04 Oct 2002; Revised 07 Mar 2003 Copyright Information: Copyright (C) 2001-2003 Netscape. All rights reserved. Note: This reprinted article was originally part of the DevEdge site. ...
Web Standards - Archive of obsolete content
Designing and building with these standards simplifies and lowers the cost of production, while delivering sites that are accessible to more people and more types of Internet devices. Sites developed along these lines will continue to function correctly as traditional desktop browsers evolve, and as new Internet devices come to market. ...
...lity of any document published on the Web. Designing and building with these standards simplifies and lowers the cost of production, while delivering sites that are accessible to more people and more types of Internet devices. Sites developed along these lines will continue to function correctly as traditional desktop browsers evolve, and as new Internet devices come to market. [1] Documentation Migrate apps from Internet Explorer to Mozilla Ever have trouble getting your Internet Explorer-specific Web applications to work with Mozilla? This article covers common issues associated with migrating applications to the open source Mozilla-based browser. Using Web Standards in your Web Pages This article provides an overview of the process for upgrading the cont...
Building up a basic demo with Babylon.js - Game development
ilar concepts: camera, light and objects. Environment setup To start developing with Babylon.js, you don't need much. You should start off by: Making sure you are using a modern browser with good WebGL support, such as the latest Firefox or Chrome. Creating a directory to store your experiments in. Saving a copy of the latest Babylon.js engine inside your directory. Opening the Babylon.js documentation in a separate tab -- it is useful to refer to. HTML structure Here's the HTML structure we will use: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>MDN Games: Babylon.js demo</title> <style> html,body,canvas { margin: 0; padding: 0; width: 100%; height: 100%; font-size: 0; } </style> </head> <body> <script src="babylon.js"></script> <canvas id="rende...
...er to. HTML structure Here's the HTML structure we will use: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>MDN Games: Babylon.js demo</title> <style> html,body,canvas { margin: 0; padding: 0; width: 100%; height: 100%; font-size: 0; } </style> </head> <body> <script src="babylon.js"></script> <canvas id="render-canvas"></canvas> <script> var canvas = document.getElementById("render-canvas"); /* 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 (which Babylon.js will use to render the content on) to fill the entire available viewport space. The first <script> element includes the Babylon.js library in the pag...
Building up a basic demo with the PlayCanvas engine - Game development
ilar concepts: camera, light and objects. Environment setup To start developing with PlayCanvas, you don't need much. You should start off by: Making sure you are using a modern browser with good WebGL support, such as the latest Firefox or Chrome. Creating a directory to store your experiments in. Saving a copy of the latest PlayCanvas engine inside your directory. Opening the PlayCanvas documentation in a separate tab -- it is useful to refer to. HTML structure Here's the HTML structure we will use. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>MDN Games: PlayCanvas demo</title> <style> body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <body> <script src="playcanvas-latest.js"></script> <canvas id="app...
... HTML structure Here's the HTML structure we will use. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>MDN Games: PlayCanvas demo</title> <style> body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <body> <script src="playcanvas-latest.js"></script> <canvas id="application-canvas"></canvas> <script> var canvas = document.getElementById("application-canvas"); /* 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 PlayCanvas will use to 100% so that it will fill the entire available viewport space. The first <script> element includes the PlayCanvas library in the page;...
WebRTC data channels - Game development
ation. Data channels come in two flavors. Reliable channels guarantee that messages you send arrive at the other peer and in the same order in which they're sent. This is analogous to a TCP socket. Unreliable channels make no such guarantees; messages aren't guaranteed to arrive in any particular order and, in fact, aren't guaranteed to arrive at all. This is analogous to a UDP socket. We have documentation for using WebRTC. This article, however, will take advantage of some libraries that can help trivialize the work, and will demonstrate ways to use abstraction to work around implementation differences between browsers. Hopefully, of course, those differences will fade away in time. Using the p2p library One library you can use is the p2p library. This library provides a simple API for crea...
...g the p2p library One library you can use is the p2p library. This library provides a simple API for creating peer connections and setting up streams and data channels. ...
Finishing up - Game development
= "16px Arial"; ctx.fillStyle = "#0095DD"; ctx.fillText("Lives: "+lives, canvas.width-65, 20); } Instead of ending the game immediately, we will decrease the number of lives until they are no longer available. We can also reset the ball and the paddle positions when the player begins with their next life. ...
...ble. We can also reset the ball and the paddle positions when the player begins with their next life. So, in the draw() function replace the following three lines: alert("GAME OVER"); document.location.reload(); clearInterval(interval); // Needed for Chrome to end game With this, we can add slightly more complex logic to it as given below: lives--; if(!lives) { alert("GAME OVER"); document.location.reload(); clearInterval(interval); // Needed for Chrome to end game } else { x = canvas.width/2; y = canvas.height-30; dx = 2; dy = -2; paddleX = (canvas.width-paddleWidth)/2; } Now, when the ball hits the bottom edge of the screen, we're subtracting one life from the lives variable. If there are no lives left, the game is lost; if there are still some lives left...
Game over - Game development
ll keep it simple, showing an alert message and restarting the game by reloading the page. First, replace where you initially called setInterval() setInterval(draw, 10); with: var interval = setInterval(draw, 10); Then replace the second if statement with the following: if(y + dy < ballRadius) { dy = -dy; } else if(y + dy > canvas.height-ballRadius) { alert("GAME OVER"); document.location.reload(); clearInterval(interval); // Needed for Chrome to end game } Letting the paddle hit the ball The last thing to do in this lesson is to create some kind of collision detection between the ball and the paddle, so it can bounce off it and get back into the play area. The easiest thing to do is to check whether the center of the ball is between the left and right edges of the...
...area. The easiest thing to do is to check whether the center of the ball is between the left and right edges of the paddle. Update the last bit of code you modified again, to the following: if(y + dy < ballRadius) { dy = -dy; } else if(y + dy > canvas.height-ballRadius) { if(x > paddleX && x < paddleX + paddleWidth) { dy = -dy; } else { alert("GAME OVER"); document.location.reload(); clearInterval(interval); } } If the ball hits the bottom edge of the Canvas we need to check whether it hits the paddle . if yes, then it bounces off just like you'd expect; if not then the game is over as before. Compare your code Here's the working code for you to compare yours against: Exercise: make the ball move faster when it hits the paddle. Next ste...
CSS - MDN Web Docs Glossary: Definitions of Web-related terms
bpage 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. */ color: yellow; /* The "background-color" property defines the background color, in this case black. */ background-color: black } "Cascading" refers to the rules that govern how selectors are prioritized to change a page's appearance. This is a very important feature, since a comp...
...background-color" property defines the background color, in this case black. ...
HTML - MDN Web Docs Glossary: Definitions of Web-related terms
he HTML 3.2 recommendation a year later. HTML 4.0 was released in 1999 and became an ISO standard in 2000. At that time, the W3C nearly abandoned HTML in favor of XHTML, prompting the founding of an independent group called WHATWG in 2004. Thanks to WHATWG, work on HTML5 continued: the two organizations released the first draft in 2008 and the final standard in 2014. Concept and syntax An HTML document is a plaintext document structured with elements. Elements are surrounded by matching opening and closing tags. Each tag begins and ends with angle brackets (<>). There are a few empty or void tags that cannot enclose any text, for instance <img>. You can extend HTML tags with attributes, which provide additional information affecting how the browser interprets the element: An HTML file is no...
...L tags with attributes, which provide additional information affecting how the browser interprets the element: An HTML file is normally saved with an .htm or .html extension, served by a web server, and can be rendered by any Web browser. Learn more General knowledge HTML on Wikipedia Learning HTML Our HTML tutorial The web course on codecademy.com Technical reference The HTML documentation on MDN The HTML specification ...
HTTP - MDN Web Docs Glossary: Definitions of Web-related terms
The current version of the HTTP specification is called HTTP/2. As part of a URI, the "http" within "http://example.com/" is called a "scheme". Resources using the "http" schema are typically transported over unencrypted connections using the HTTP protocol. The "https" scheme (as in "https://developer.mozilla.org") indicates that a resource is transported using the HTTP protocol, but over a secure TLS channel. ...
... transported over unencrypted connections using the HTTP protocol. The "https" scheme (as in "https://developer.mozilla.org") indicates that a resource is transported using the HTTP protocol, but over a secure TLS channel. HTTP is textual (all communication is done in plain text) and stateless (no communication is aware of previous communications). This property makes it ideal for humans to read documents (web sites) on the world wide web. However, HTTP can also be used as a basis for REST web services from server to server or AJAX requests within web sites to make them more dynamic. Learn more HTTP on MDN HTTP on Wikipedia ...
PDF - MDN Web Docs Glossary: Definitions of Web-related terms
PDF provides a digital image of a printed document, and keeps the same appearance when printed. ...
... PDF (Portable Document Format) is a file format used to share documentation without depending on any particular software implementation, hardware platform, or operating system. PDF provides a digital image of a printed document, and keeps the same appearance when printed. Learn more General Knowledge PDF on Wikipedia ...
Pseudo-class - MDN Web Docs Glossary: Definitions of Web-related terms
In CSS, a pseudo-class selector targets elements depending on their state rather than on information from the document tree. ...
... In CSS, a pseudo-class selector targets elements depending on their state rather than on information from the document tree. ...
REST - MDN Web Docs Glossary: Definitions of Web-related terms
REST(Representational State Transfer) refers to a group of software architecture design constraints that bring about efficient, reliable and scalable distributed systems. A system is called RESTful when it adhere to those constraints. The basic idea of REST is that a resource, e.g. ...
... architecture design constraints that bring about efficient, reliable and scalable distributed systems. A system is called RESTful when it adhere to those constraints. The basic idea of REST is that a resource, e.g. a document, is transferred with its state and relationships via well-defined, standarized operations and formats or services call themselves RESTful when they directly modify type of document as opposed to triggering actions somewhere. Because HTTP, the standard protocol hehind the "World Wide Web", "Web" also transfers documents and hypertext links, simple HTTP APIs are sometimes colloguially referred to as RESTful APIs, RESTful services, or simply REST services, although they don't necessarily adhere to all REST constraints. Beginners can assume a REST API means an HTTP service tha...
Rendering engine - MDN Web Docs Glossary: Definitions of Web-related terms
A rendering engine is software that draws text and images on the screen. The engine draws structured text from a document (often HTML), and formats it properly based on the given style declarations (often given in CSS). Examples of layout engines: Blink, Gecko, EdgeHTML, WebKit. ...
... A rendering engine is software that draws text and images on the screen. The engine draws structured text from a document (often HTML), and formats it properly based on the given style declarations (often given in CSS). Examples of layout engines: Blink, Gecko, EdgeHTML, WebKit. ...
SVG - MDN Web Docs Glossary: Definitions of Web-related terms
Scalable Vector Graphics (SVG) is a 2D vector image format based on an XML syntax. The W3C began work on SVG in the late 1990s, but SVG only became popular when Internet Explorer 9 came out with SVG support. All major browsers now support SVG. Based on an XML syntax, SVG can be styled with CSS and made interactive using JavaScript. HTML5 now allows direct embedding of SVG tags in an HTML document. As a vector image format, SVG graphics can scale infinitely, making them invaluable in responsive design, since you can create interface elements and graphics that scale to any screen size. SVG also provides a useful set of tools, such as clipping, masking, filters, and animations. Learn more General knowledge SVG on Wikipedia Learning SVG W3.org's SVG Primer Technical information ...
...a vector image format, SVG graphics can scale infinitely, making them invaluable in responsive design, since you can create interface elements and graphics that scale to any screen size. SVG also provides a useful set of tools, such as clipping, masking, filters, and animations. Learn more General knowledge SVG on Wikipedia Learning SVG W3.org's SVG Primer Technical information SVG documentation on MDN Latest SVG specification ...
WebDAV - MDN Web Docs Glossary: Definitions of Web-related terms
g) is an HTTP Extension that lets web developers update their content remotely from a client. WebDAV is rarely used alone, but two extensions are very common: CalDAV (remote-access calendar) and CardDAV (remote-access address book). ...
...otely from a client. WebDAV is rarely used alone, but two extensions are very common: CalDAV (remote-access calendar) and CardDAV (remote-access address book). WebDAV allows clients to add, delete, and retrieve webpage metadata (e.g. ...
XLink - MDN Web Docs Glossary: Definitions of Web-related terms
For those who may have found XLink 1.0 cumbersome for regular links, XLink 1.1 drops the need to specify xlink:type="simple" for simple links. XLink is used in SVG, MathML, and other important standards. ...
... For those who may have found XLink 1.0 cumbersome for regular links, XLink 1.1 drops the need to specify xlink:type="simple" for simple links. XLink is used in SVG, MathML, and other important standards. ...
XPath - MDN Web Docs Glossary: Definitions of Web-related terms
XPath is a query language that can access sections and content in an XML document. ...
... XPath is a query language that can access sections and content in an XML document. ...
XSLT - MDN Web Docs Glossary: Definitions of Web-related terms
eXtensible Stylesheet Language Transformations (XSLT) is a declarative language used to convert XML documents into other XML documents, HTML, PDF, plain text, and so on. XSLT has its own processor that accepts XML input, or any format convertible to an XQuery and XPath Data Model. The XSLT processor produces a new document based on the XML document and an XSLT stylesheet, making no changes to the original files in the process. ...
...ert XML documents into other XML documents, HTML, PDF, plain text, and so on. XSLT has its own processor that accepts XML input, or any format convertible to an XQuery and XPath Data Model. The XSLT processor produces a new document based on the XML document and an XSLT stylesheet, making no changes to the original files in the process. ...
Viewport - MDN Web Docs Glossary: Definitions of Web-related terms
Content outside the viewport is not visible onscreen until scrolled into view. The portion of the viewport that is currently visible is called the visual viewport. This can be smaller than the layout viewport, such as when the user has pinched-zoomed. ...
...Content outside the viewport is not visible onscreen until scrolled into view. The portion of the viewport that is currently visible is called the visual viewport. This can be smaller than the layout viewport, such as when the user has pinched-zoomed. ...
MDN Web Docs Glossary: Definitions of Web-related terms
This glossary provides definitions of words and abbreviations you need to know to successfully understand and build for the web. ...
...SS Object Model (CSSOM) CSS pixel CSS preprocessor D Data structure Decryption Delta Denial of Service Descriptor (CSS) Deserialization Developer Tools DHTML Digest Digital certificate Distributed Denial of Service DMZ DNS Doctype Document directive document environment DOM (Document Object Model) Domain Domain name Domain sharding Dominator DoS attack DTLS (Datagram Transport Layer Security) DTMF (Dual-Tone Multi-Frequency signaling) Dynamic programming language Dynamic typing E ECMA ECMAScript ...
Mobile accessibility - Learn web development
nt menu. Swipe right until you find the "Headings and Landmarks" option. Double-tap to select it. Now you'll be able to swipe left and right to move between headings and ARIA landmarks. To go back to the default mode, enter the local context menu again by swiping up and right, select "Default", and then double-tap to activate. Note: See Get started on Android with TalkBack for more complete documentation. iOS VoiceOver A mobile version of VoiceOver is built into the iOS operating system. To turn it on, go to Your Settings app and select Accessibility > VoiceOver. Press the VoiceOver slider to enable it (you'll also see a number of other options related to VoiceOver on this page). Note: Some older iOS devices have the VoiceOver menu at Settings app > General > Accessibility > VoiceOver.
...down and mouseup create problems -- their event handlers cannot be invoked using non-mouse controls. If you try to control our simple-box-drag.html (see example live) example with a keyboard or touch, you'll see the problem. ...
Backgrounds and borders - Learn web development
left-to-right or right-to-left text, or top-to-bottom). We'll be exploring these in the next lesson, which covers handling different text directions. There are a variety of styles that you can use for borders. In the example below we have used a different border style for the four sides of my box. Play with the border style, width, and color to see how borders work. Rounded corners Ro...
...ary We have covered quite a lot here, and you can see that there is quite a lot to adding a background or a border to a box. Do explore the different property pages if you want to find out more about any of the features we have discussed. Each page on MDN has more examples of usage for you to play with and enhance your knowledge. In the next lesson, we will find out how the Writing Mode of your document interacts with your CSS. What happens when the text does not flow from left to right? Previous Overview: Building blocks Next In this module Cascade and inheritance CSS selectors Type, class, and ID selectors Attribute selectors Pseudo-classes and pseudo-elements Combinators The box model Backgrounds and borders Handling different text directions Overflowing ...
CSS selectors - Learn web development
a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them. The element or elements which are selected by the selector are referred to as the subject of the selector. In earlier articles you met some different selectors, and learned that there are selectors that target the document in different ways -- for example by selecting an element such as h1, or a class such as .special. In CSS, selectors are defined in the CSS Selectors specification; like any other part of CSS they need to have support in browsers for them to work. The majority of selectors that you will come across are defined in the Level 3 Selectors specification, which is a mature specification, therefore you ...
...ments, which select a certain part of an element rather than the element itself. For example, ::first-line always selects the first line of text inside an element (a <p> in the below case), acting as if a <span> was wrapped around the first formatted line and then selected. p::first-line { } Combinators The final group of selectors combine other selectors in order to target elements within our documents. The following for example selects paragraphs that are direct children of <article> elements using the child combinator (>): article > p { } Next steps You can take a look at the reference table of selectors below for direct links to the various types of selectors in this Learn section or on MDN in general, or continue on to start your journey by finding out about type, class, and ID selector...
Floats - Learn web development
Any content that comes below the floated element in the normal layout flow will now wrap around it, filling up the space to the right-hand side of it as far up as the top of the floated element. There, it will stop. Floating the content to the right has exactly the same effect, but in reverse -- the floated element w...
...erty accepts the following values: left: Clear items floated to the left. right: Clear items floated to the right. both: Clear any floated items, left or right. Clearing boxes wrapped around a float You now know how to clear something following a floated element, but let's see what happens if you have a tall float and a short paragraph, with a box wrapped around both elements. Change your document so that the first paragraph and our floated box are wrapped with a <div> with a class of wrapper. <div class="wrapper"> <div class="box">Float</div> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate.</p> </div> In your CSS, add the following rule for the .wrapper class and then reload the page: .wrapper { backgro...
Practical positioning examples - Learn web development
top: 0; left: 0; height: 352px; padding: 10px; color: white; background-color: #a60000; } .info-box .active-panel { z-index: 1; } Adding our JavaScript The final step to getting this feature working is to add some JavaScript. ...
...lor: white; background-color: #a60000; } .info-box .active-panel { z-index: 1; } Adding our JavaScript The final step to getting this feature working is to add some JavaScript. ...
Supporting older browsers - Learn web development
that it will look great on modern browsers, but will still be usable at a basic level for users of older browsers. A basic level of support comes from structuring your content well so that the normal flow of your page makes sense. A user with a very limited feature phone might not get much of your CSS, but the content will flow in a way that makes reading easy. Therefore, a well-structured HTML document should always be your starting point. If you remove your stylesheet, does your content make sense? One option is to leave this plain view of the site as the fallback for people using very old or limited browsers. If you have a tiny number of people coming to the site in these browsers it may not make commercial sense to pour time into trying to give them a similar experience to people on modern ...
...helps you check what you are looking at and can also help if you need flex support in very old browsers. The IE10 and 11 prefixed version of Grid The CSS Grid specification was initially prototyped In Internet Explorer 10; this means that while IE10 and IE11 do not have modern grid support, they do have a version of Grid layout that is very usable, although different to the modern specification documented on this site. The IE10 and 11 implementations is -ms- prefixed, which means you can use it for these browsers and it will be ignored by non-Microsoft browsers. Edge does still understand the old syntax, however, so take care that everything is safely overwritten in your modern grid CSS. The guide to Progressive Enhancement in Grid Layout can help you understand the IE version of the grid, and...
CSS first steps - Learn web development
the basic theory of CSS, and provide opportunities for you to test out some skills. What is CSS? CSS (Cascading Style Sheets) allows you to create great-looking web pages, but how does it work under the hood? This article explains what CSS is, with a simple syntax example, and also covers some key terms about the language. Getting started with CSS In this article we will take a simple HTML document and apply CSS to it, learning some practical things about the language along the way. How CSS is structured Now that you have an idea about what CSS is and the basics of using it, it is time to look a little deeper into the structure of the language itself. We have already met many of the concepts discussed here; you can return to this one to recap if you find any later concepts confusing. How...
...to this one to recap if you find any later concepts confusing. How CSS works We have learned the basics of CSS, what it is for and how to write simple stylesheets. In this lesson we will take a look at how a browser takes CSS and HTML and turns that into a webpage. Using your new knowledge With the things you have learned in the last few lessons you should find that you can format simple text documents using CSS, to add your own style to them. This article gives you a chance to do that. ...
CSS FAQ - Learn web development
Learn › CSS › Howto › CSS FAQ
Using a correct and modern DOCTYPE declaration at the start of your HTML will improve browser standards compliance. ...
... with Web standards or with old browser bugs. Using a correct and modern DOCTYPE declaration at the start of your HTML will improve browser standards compliance. Modern browsers have two main rendering modes: Quirks Mode: also called backwards-compatibility mode, allows legacy webpages to be rendered as their authors intended, following the non-standard rendering rules used by older browsers. Documents with an incomplete, incorrect, or missing DOCTYPE declaration or a known DOCTYPE declaration in common use before 2001 will be rendered in Quirks Mode. Standards Mode: the browser attempts to follow the W3C standards strictly. New HTML pages are expected to be designed for standards-compliant browsers, and as a result, pages with a modern DOCTYPE declaration will be rendered with Standards Mode...
What are browser developer tools? - Learn web development
ng Ctrl + Shift + K or using the menu command: Menu ? Web Developer ? Web Console, or Tools ? Web Developer ? Web Console. On other browser, open the developer tools and then click the Console tab. This will give you a window like the following: To see what happens, try entering the following snippets of code into the console one by one (and then pressing Enter): alert('hello!'); document.querySelector('html').style.backgroundColor = 'purple'; const myWordmark = document.createElement('img'); myWordmark.setAttribute('src','https://blog.mozilla.org/press/wp-content/themes/OneMozilla/img/mozilla-wordmark.png'); document.querySelector('h1').appendChild(myWordmark); Now try entering the following incorrect versions of the code and see what you get. alert('hello!); ...
...uerySelector('html').style.backgroundColor = 'purple'; const myWordmark = document.createElement('img'); myWordmark.setAttribute('src','https://blog.mozilla.org/press/wp-content/themes/OneMozilla/img/mozilla-wordmark.png'); document.querySelector('h1').appendChild(myWordmark); Now try entering the following incorrect versions of the code and see what you get. alert('hello!); document.cheeseSelector('html').style.backgroundColor = 'purple'; const myWordmark = document.createElement('img'); myBanana.setAttribute('src','https://blog.mozilla.org/press/wp-content/themes/OneMozilla/img/mozilla-wordmark.png'); document.querySelector('h1').appendChild(myWordmark); You'll start to see the kind of errors that the browser returns. Often these errors are fairly cryptic, but it ...
Basic native form controls - Learn web development
is a set of attributes common to all form elements. You've met some of these already, but below is a list of those common attributes, for your reference: Attribute name Default value Description autofocus false This Boolean attribute lets you specify that the element should automatically have input focus when the page loads. Only one form-associated element in a document can have this attribute specified. disabled false This Boolean attribute indicates that the user cannot interact with the element. If this attribute is not specified, the element inherits its setting from the containing element, for example, <fieldset>; if there is no containing element with the disabled attribute set, then the element is enabled. form The <form> el...
...ot specified, the element inherits its setting from the containing element, for example, <fieldset>; if there is no containing element with the disabled attribute set, then the element is enabled. form The <form> element that the widget is associated with, used if it is not nested within that form. The value of the attribute must be the id attribute of a <form> element in the same document. This lets you associate a form control with a form it is outside of, even if it is inside a different form element. name The name of the element; this is submitted with the form data. value The element's initial value. Test your skills! You've reached the end of this article, but can you remember the most important information? You can find some further te...
Example 4 - Learn web development
ctorAll('.option'); nativeWidget.selectedIndex = index; value.innerHTML = optionList[index].innerHTML; highlightOption(select, optionList[index]); }; function getIndex(select) { var nativeWidget = select.previousElementSibling; return nativeWidget.selectedIndex; }; // ------------- // // Event binding // // ------------- // window.addEventListener("load", function () { var form = document.querySelector('form'); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener('load', function () { var selectList = document.querySelectorAll('.select'); selectList.forEach(function (select) { var optionList = select.querySelectorAll('.option'); optionList.forEach(function (option) { option.addEventListener('mouseover', function ()...
..., option); }); }); select.addEventListener('click', function (event) { toggleOptList(select); }); select.addEventListener('focus', function (event) { activeSelect(select, selectList); }); select.addEventListener('blur', function (event) { deactivateSelect(select); }); }); }); window.addEventListener('load', function () { var selectList = document.querySelectorAll('.select'); selectList.forEach(function (select) { var optionList = select.querySelectorAll('.option'), selectedIndex = getIndex(select); select.tabIndex = 0; select.previousElementSibling.tabIndex = -1; updateValue(select, selectedIndex); optionList.forEach(function (option, index) { option.addEventListener('click', function (event) { ...
The web and web standards - Learn web development
nization 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 Docs), but instead are intended to be used by software engineers to implement these technologies (usually in web browsers). For example, the HTML Living Standard describes exactly how HTML (...
...he paint, wallpaper, carpets and paintings you'd use to make the house look nice. JavaScript is the programming language we use to add interactivity to web sites, from dynamic style switching, to fetching updates from the server, right through to complex 3D graphics. ...
HTML Cheatsheet - Learn web development
However, in many cases we just need some quick hints as we go. That's the whole purpose of the cheatsheet, to give you some quick accurate ready to use code snippets for common usages. Remember that HTML tags must be used for their semantic, not their appearance. ...
... Highlight some text <mark>Notice me</mark> Notice me Draw a line through irrelevant text <s>I'm irrelevant</s> I'm irrelevant Underline a non-textual annotation This is <u>mispelled</u> This is mispelled Text displayed lower than normal text H<sub>2</sub>O H2O Small text Used to represent the <small>small print </small>of a document Used to represent the small print of a document Used for an address <address>Main street 67</address> Main street 67 Used for a textual cite <cite>Lorem ipsum</cite> lorem ipsum Text displayed higher than normal text x<sup>2</sup> x2 A short inline quotation <q>The q element indicates a short inline quotation.</q> The q element indica...
Tips for authoring fast-loading HTML pages - Learn web development
This will cause the JavaScript to be loaded after the page contents, which will improve the overall appearance of the page load. Reduce the number of inline scripts Inline scripts can be expensive for page loading since the parser must assume that an inline script could modify the page structure while parsing is in progress. Reducing the use of inline scripts in general, and reducing the use of document.write() to output content in particular, can improve overall page loading. Use modern AJAX methods to manipulate page content for modern browsers, rather than the older approaches based on document.write(). Use modern CSS and valid markup Use of modern CSS reduces the amount of markup, can reduce the need for (spacer) images, in terms of layout, and can very often replace images of stylized tex...
...d for images, whenever possible. Tables should use the CSS selector: property combination: table-layout: fixed; and should specify widths of columns using the <col> and the <colgroup> elements. Use lazy loading for images By default, imags are loaded eagerly; that is, the image is fetched and rendered as soon as it's processed in the HTML. All eagerly loaded images are rendered before the document's load event is sent. Switching to lazy loading of images tells the browser to hold off on loading images until they're about to be needed to draw the visual viewport. To mark an image for lazy loading, specify its loading attribute with a value of lazy. With this set, the image will only be loaded when it's needed. <img href="./images/footerlogo.jpg" loading="lazy"> Note that lazily-loaded im...
Define terms with HTML - Learn web development
Objective: Learn how to introduce new keywords and how to build description lists. When you need a term defined, you probably go straight to a dictionary or glossary. ...
.... Special case: Abbreviations It's best to mark abbreviations specially with <abbr>, so that screen readers read them appropriately and so that you can operate on all abbreviations uniformly. Just as with any new keyword, you should define your abbreviations the first time they occur. <p> <dfn><abbr>HTML</abbr> (hypertext markup language)</dfn> is a description language used to structure documents on the web. </p> The HTML spec does indeed set aside the title attribute for expanding the abbreviation. However, this is not an acceptable alternative for providing an inline expansion. The contents of title are completely hidden from your users, unless they're using a mouse and they happen to hover over the abbreviation. The spec duly acknowledges this as well. Improve accessibility <dfn>...
Use HTML to solve common problems - Learn web development
Learn › HTML › Howto
The following links point to solutions to common everyday problems you'll need to solve with HTML. Basic structure The most basic application of HTML is document structure. If you're new to HTML you should start with this. How to create a basic HTML document How to divide a webpage into logical sections How to set up a proper structure of headings and paragraphs Basic text-level semantics HTML specializes in providing semantic information for a document, so HTML answers many questions you might have about how to get your message across best in your document. How to create a list of items with HTML How to stress or emphasize content How to indicate that text is important How to display computer code with HTML How to annotate images and graphics How to mark abbreviations and mak...
...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 co...
Structuring a page of content - Learn web development
ady for laying it out using CSS is a very important skill to master, so in this assessment you'll be tested on your ability to think about how a page might end up looking, and choose appropriate structural semantics to build a layout on top of. Prerequisites: Before attempting this assessment you should have already worked through the rest of the course, with a particular emphasis on Document and website structure. Objective: To test knowledge of web page structures, and how to represent a prospective layout design in markup. Starting point To get this assessment started, you should go and grab the zip file containing all the starting assets. The zip file contains: The HTML you need to add structural markup to. CSS to style your markup. Images that are used...
... get into -- it's very hard to help someone with a coding problem if you can't see their code. ...
Images in HTML - Learn web development
00px; width: 95%"> <img> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; sol...
...ght: 100px; width: 95%"> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; sol...
Client-side web APIs - Learn web development
out (most of) the code examples in an online coding program such as JSBin or Glitch. Guides Introduction to web APIs First up, we'll start by looking at APIs from a high level -- what are they, how do they work, how do you 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. Manipulating documents When writing web pages and apps, one of the most common things you'll want to do is manipulate web documents in some way. This is usually 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...
... Drawing graphics 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 the Canvas API, and further resources to allow you to learn more. Video and audio APIs 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. Client-side storage Modern web browsers feature a number of different technologies that allow you to store data related to web sites and retrieve it when necessary allowing you to persist data long term...
Basic math in JavaScript — numbers and operators - Learn web development
or a victory message if the game has been won Display the correct seasonal greeting depending what holiday season it is Zoom a map in or out depending on what zoom level is selected We'll look at how to code such logic when we look at conditional statements in a future article. ...
... Display the correct seasonal greeting depending what holiday season it is Zoom a map in or out depending on what zoom level is selected We'll look at how to code such logic when we look at conditional statements in a future article. ...
What went wrong? Troubleshooting JavaScript - Learn web development
code: lowOrHi.textContent = 'Last guess was too high!'; This line is trying to set the textContent property of the lowOrHi constant to a text string, but it's not working because lowOrHi does not contain what it's supposed to. Let's see why this is -- try searching for other instances of lowOrHi in the code. The earliest instance you'll find in the JavaScript is on line 48: const lowOrHi = document.querySelector('lowOrHi'); At this point we are trying to make the variable contain a reference to an element in the document's HTML. Let's check whether the value is null after this line has been run. Add the following code on line 49: console.log(lowOrHi); Note: console.log() is a really useful debugging function that prints a value to the console. So it will print the value of lowOrH...
...g function that prints a value to the console. So it will print the value of lowOrHi to the console as soon as we have tried to set it in line 48. Save and refesh, and you should now see the console.log() result in your console. Sure enough, lowOrHi's value is null at this point, so there is definitely a problem with line 48. Let's think about what the problem could be. Line 48 is using a document.querySelector() method to get a reference to an element by selecting it with a CSS selector. Looking further up our file, we can find the paragraph in question: <p class="lowOrHi"></p> So we need a class selector here, which begins with a dot (.), but the selector being passed into the querySelector() method in line 48 has no dot. This could be the problem! Try changing lowOrHi to .lowOrHi i...
Object building practice - Learn web development
n exploring them more. Along the way we'll make use of some nifty objects, and show you a couple of nice techniques 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 tha...
... 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('canvas'); const ctx = canvas.getContext('2d'); const width = canvas.width = window.innerWidth; const height = canvas.height = window.innerHeight; This script gets a reference to the <canvas> element, then calls the getContext() method on it to give us a context on which we can start to draw. The resulting constant (ctx) is the object that directly represents the drawing area of ...
Getting started with Ember - Learn web development
et payloads due to compiling the templates into a "byte code" that can be parsed faster than JavaScript. The Glimmer VM enables extremely fast DOM change tracking without the need to manage and diff a cached virtual representation (which is a common approach to mitigating the slow I/O of DOM changes). For more information on the technical aspects of The Glimmer VM, the github repository has some documentation -- specifically, References and Validators may be of interest. Everything else in Ember is just JavaScript. In particular, JavaScript classes. This is where most of the "framework" parts come into play, as there are superclasses, where each type of thing has a different purpose and different expected location within your project. Here is a demonstration the impact Ember has on the JavaScri...
...run ember --help for a full list of commands and their options). To create a brand new application, type the following in your terminal. This creates a new directory inside the current directory you are in called todomvc, containing the scaffolding for a new Ember app. Make sure you navigate to somewhere appropriate in the terminal before you run it. (Good suggestions are your "desktop" or "documents" directories, so that it is easy to find): ember new todomvc Or, on Windows: npx ember-cli new todomvc This generates a production-ready application development environment that includes the following features by default: Development server with live reload. Plugin-architecture that allows for third-party packages to richly enhance your application. The latest JavaScript via...
Ember resources and troubleshooting - Learn web development
uages, 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, ask for help, and help others! General troubleshooting, gotchas, and misconceptions This is nowhere near an extensive list, but it is a list of things that came up around the time of writing (latest update, May 2020). How do I debug what's going on in the framework? For framework-specific things, the...
...to handle common events resulting from configuring the model: loading -- what to do when the model hook is loading. error -- what to do when an error is thrown from model. Both loading and error can render default templates as well as customized templates defined elsewhere in the application, unifying loading/error states. More information on everything a Route can do is found in the API documentation. Previous Overview: Client-side JavaScript frameworks Next In this module Introduction to client-side frameworks Framework main features React Getting started with React Beginning our React todo list Componentizing our React app React interactivity: Events and state React interactivity: Editing, filtering, conditional rendering Accessibility in React Re...
Componentizing our React app - Learn web development
d your browser should update 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" /> ...
... make a new const beneath the final import, but above ReactDOM.render(): const DATA = [ { id: "todo-0", name: "Eat", completed: true }, { id: "todo-1", name: "Sleep", completed: false }, { id: "todo-2", name: "Repeat", completed: false } ]; Next, we'll pass DATA to <App /> as a prop, called tasks. The final line of src/index.js should read like this: ReactDOM.render(<App tasks={DATA} />, document.getElementById("root")); This array is now available to the App component as props.tasks. You can console.log() it to check, if you'd like. Note: ALL_CAPS constant names have no special meaning in JavaScript; they're a convention that tells other developers "this data will never change after being defined here". Rendering with iteration To render our array of objects, we have to turn each o...
Getting started with Svelte - Learn web development
lications. They are written into .svelte files using a superset of HTML. All three sections -- <script>, <styles>, and markup -- are optional, and can appear in any order you like. <script> // logic goes here </script> <style> /* styles go here */ </style> <!-- markup (zero or more HTML elements) goes here --> Note: For more information on the component format, have a look at the svelte documentation. With this in mind, let's have a look at the src/App.svelte file that came with the starter template. You should see something like the following: <script> export let name; </script> <main> <h1>Hello {name}!</h1> <p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p> </main> <style> main { text-align: center; padding...
...other complex reconciliation mechanism. Note the use of : in on:click. That's Svelte's syntax for listening to DOM events. Inspecting main.js: the entry point of our app Let's open src/main.js, which is where the App component is being imported and used. This file is the entry point for our app, and it initially looks like this: import App from './App.svelte'; const app = new App({ target: document.body, props: { name: 'world' } }); export default app; main.js starts by importing the Svelte component that we are going to use. Then in line 3 it instantiates it, passing an option object with the following properties: target: The DOM element inside which we want the component to be rendered, in this case the <body> element. props: the values to assign to each prop of the App comp...
Getting started with Vue - Learn web development
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 existing site, you can drop one of the following <script> elements onto a page. This allows you to start using Vue on existing s...
... - Network: <http://192.168.1.9:8080/> Note that the development build is not optimized. To create a production build, run npm run build. If you navigate to the "local" address in a new browser tab (this should be something like http://localhost:8080 as stated above, but may vary based on your setup), you should see your app. Right now, it should contain a welcome message, a link to the Vue documentation, links to the plugins you added when you initialized the app with your CLI, and some other useful links to the Vue community and ecosystem. Making a couple of changes Let's make our first change to the app -- we'll delete the Vue logo. Open the App.vue file, and delete the <img> element from the template section: <img alt="Vue logo" src="./assets/logo.png"> If your server is still runn...
Vue resources - Learn web development
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 where to go to find further information on Vue, to continue your learning. Further resources Here's where you should go to learn more about Vue: Vue Docs -- The main Vue site. Contains comprehensive documentation, including examples, cookbooks, and reference material. This is the best place to start learning Vue in depth. Vue Github Repo -- The Vue code itself. This is where you can report issues and/or contribute directly to the Vue codebase. Studying the Vue source code can help you better understand how the framework works, and write better code. Vue Forum -- The official forum for getting help ...
...cookbooks, and reference material. This is the best place to start learning Vue in depth. Vue Github Repo -- The Vue code itself. This is where you can report issues and/or contribute directly to the Vue codebase. Studying the Vue source code can help you better understand how the framework works, and write better code. Vue Forum -- The official forum for getting help with Vue. Vue CLI Docs -- Documentation for the Vue CLI. This contains information on customizing and extending the output you are generating via the CLI. NuxtJS -- NuxtJS is a Server-Side Vue Framework, with some architectural opinions that can be useful to creating maintainable applications, even if you don't use any of the Server Side Rendering features it provides. This site provides detailed documentation on using NuxtJS. V...
Command line crash course - Learn web development
the git for Windows toolset) However, the best option for Windows in the modern day is the Windows Subsystem for Linux (WSL) -- a compatibility layer for running Linux operating systems directly from inside Windows 10, allowing you to run a "true terminal" directly on Windows, without needing a virtual machine. This can be installed directly from the Windows store for free. You can find all the documentation you need in the Windows Subsystem for Linux Documentation. In terms of what option to choose on Windows, we'd strongly recommend trying to install the WSL. You could stick with the default command prompt (cmd), and many tools will work OK, but you'll find everything easier if you have better parity with Unix tools. Side note: what's the difference between a command line and a terminal? ...
... safe place to try them is over at Glitch.com. Along with being a great place to try out web development code, the projects also give you access to a terminal, so you can run all these commands directly in that terminal, safe in the knowledge that you won't break your own machine. A great resource for getting a quick overview of specific terminal commands is tldr.sh. This is a community-driven documentation service, similar to MDN, but specific to terminal commands. In the next section let's step it up a notch (or several notches in fact) and see how we can connect tools together on the command line to really see how the terminal can be advantageous over the regular desktop user interface. Connecting commands together with pipes The terminal really comes into its own when you start to chain ...
Introducing a complete toolchain - Learn web development
guration files. Again, once you've repeated this process a few times, you'll get a feel for what your default setup should be. Of course, this is just one possible configuration. Initial setup OK, let's get the initial project setup out the way. Start off by opening your terminal, and navigating to a place that you'll be able to find and get to easily. The Desktop perhaps, or your home or documents folder? Next, run the following commands to create a folder to keep your project in, and go inside the folder: mkdir will-it-miss cd will-it-miss Now we will create a new directory for all of our web site's development code to live in. Run the following now: mkdir src Code organization tends to be quite subjective from team to team. For this project, the source code will liv...
... configure prettier, give .prettierrc.json the following contents: { "singleQuote": true, "trailingComma": "es5" } With these settings, when prettier formats JavaScript for you it will use single quotes for all your quoted values, and it won't use trailing commas (a newer feature of ECMAScript that will cause errors in older browsers). You can find more about configuring Prettier in its documentation. Next up, we'll configure eslint -- create another file in the root of your will-it-miss directory called .eslintrc.json, and give it the following contents: { "env": { "es6": true, "browser": true }, "extends": "eslint:recommended", "parserOptions": { "ecmaVersion": 6, "sourceType": "module" }, "rules": { "no-console": 0 } } The above eslint con...
Client-side tooling overview - Learn web development
e of tool you are looking for, for example try searching for "date" if you want a date formating utility, or "formatter" if you are searching for a general code formatter. Pay attention to the popularity, quality, and maintenance scores, and how recently the package was last updated. Also click through to the tool pages to find out how many monthly downloads a package has, and whether it has good documentation that you can use to figure out whether it does what you need it to do. Based on these criteria, the date-fns library looks like a good date formatting tool to use. You'll see this tool in action and learn more about package managers in general in Chapter 3 of this module. If you are looking for a plugin to integrate tool functionality into your code editor, look at the code editor's plugi...
... look at information such as how many stars or downloads the extension has, as an indicator of its quality. Development-related forums to ask questions on about what tools to use, for example MDN Learn Discourse, or Stack Overflow. When you've chosen a tool to use, the first port of call should be the tool project homepage. This could be a full blown website or it might be a single readme document in a code repository. The date-fns docs for example are pretty good, complete, and easy to follow. Some documentation however can be rather technical and academic and not a good fit for your learning needs. Instead, you might want to find some dedicated tutorials on getting started with particular types of tools. Great starting places is to search web sites like CSS Tricks, Dev, freeCodeCamp, an...
Package management basics - Learn web development
Now for some page content. Let's say we want to show human-readable relative dates, such as "2 hours ago", "4 days ago" and so on. The date-fns package's formatDistanceToNow() method is useful for this (there's other packages that do the same thing too). In the index.js file, add the following code and save it: import { formatDistanceToNow } from 'date-fns' const date = '1996-09-13 10:00:00'; document.body.textContent = formatDistanceToNow(new Date(date)) + ' ago'; Go back to http://localhost:1234 and you'll see how long ago it is since the author turned 18. What's particularly special about the code above is that it is using the formatDistanceToNow() function from the date-fns package, which we didn't install! Parcel has spotted that you need the module, searched for it in the npmjs.com pac...
...e is an update available, within the range that's specified in the package. The range is specified in the version of the dependency in your package.json, such as date-fns@^2.0.1 -- in this case the caret character ^ means all minor and patch releases after and including 2.0.1, up to but excluding 3.0.0. This is determined using a system called semver, which might look a bit complicated from the documentation but can be simplified by considering only the summary information and that a version is represented by MAJOR.MINOR.PATCH, such as 2.0.1 being major version 2 with patch version 1. An excellent way to try out semver values is to use the semver calculator. It's important to remember that npm update will not upgrade the dependencies to beyond the range defined in the package.json -- to do this...
Accessibility Information for Core Gecko Developers
HTML Accessibility 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 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. Mozilla Accessibility Architecture This document explains how we implement the cross-platform accessibility layer in Mozilla. It contains a class hierararchy and an explanat...
...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. Mozilla Accessibility Architecture This document explains how we implement the cross-platform accessibility layer in Mozilla. It contains a class hierararchy and an explanation of the accessibility cache. Unix Accessibility Project This document describes the SUN accessibility project. Join the Mozilla Accessibility Community Live Chat Both end users and developers are invited for discussion on the live IRC channel at irc.mozilla.org/#accessibility. Since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night. Newsgroup and Mailing List We have two discussion lists, which can be...
Information for Assistive Technology Vendors
Information for Assistive Technology Vendors Accessibility Features in Mozilla & Call for Testers! Mozilla now has enough accessibility support that we're reading for early adopters and testers to start giving it a try. Please read this page if you're interested in an alternative accessible browser. Keyboard documentation This lists Mozilla's keyboard docs in a single long document. Gecko Info for Windows Accessibility Vendors Mozilla supports MSAA (Microsoft Active Accessibility) in HTML and in our user interface (based on XUL technology). This makes it possible for the vendors of Windows accessibility software, such as screen readers, voice dictation packages and screen magnifiers to provide support for Mozilla. In addition, we provide some simple interfaces via which we ...
...ccessibility Vendors Mozilla supports MSAA (Microsoft Active Accessibility) in HTML and in our user interface (based on XUL technology). This makes it possible for the vendors of Windows accessibility software, such as screen readers, voice dictation packages and screen magnifiers to provide support for Mozilla. In addition, we provide some simple interfaces via which we expose a read-only DOM (document object model). Mozilla Support for Linux/UNIX Assistive Technology Developers Mozilla supports the AT-SPI (Assistive Technology Service Provider Interface) in HTML and in our user interface (based on XUL technology). This makes it possible for the developers of Linux and UNIX accessibility software, such as screen readers, voice dictation packages and screen magnifiers to provide support for...
Mozilla's Section 508 Compliance
llows users to select arbitrary content with the keyboard and move through content as if inside a readonly editor. Incomplete. Inadequate attention paid to Mac keyboard bugs. Needs more investigation. (b) Applications shall not disrupt or disable activated features of other products that are identified as accessibility features, where those features are developed and documented according to industry standards. Applications also shall not disrupt or disable activated features of any operating system that are identified as accessibility features where the application programming interface for those accessibility features has been documented by the manufacturer of the operating system and is available to the product developer. Complete. (c) ...
...ode of operation and information retrieval that does not require visual acuity greater than 20/70 shall be provided in audio and enlarged print output working together or independently, or support for assistive technology used by people who are visually impaired shall be provided. Complete. Built-in text zoom limited only to the size of the window. Works ZoomText version 8.11. Caveat, the document reading and app readings modes don't support columnized text. The focus is not always correctly echoed via text to speech. However, it is functional and very possible to use ZoomText with Mozilla in this mode. Have contacted AI Squared to work on reamining issues. Complete, but needs testing. Works with gnome-mag No magnifier support on Mac OS X c) At least o...
Multiprocess on Windows
Overview A high-level overview of the ideas behind the a11y+e10s design is available on the wiki. Prerequisite reading Since so much of this design resolves around Microsoft COM and its concept of the apartment, readers of this document should have a solid understanding of what apartments are. Unfortunately this topic is often poorly explained. One of the better pieces of documentation is a two-part series written by Jeff Prosise: Understanding COM Apartments, Part I Understanding COM Apartments, Part II For the purposes of this document, "COM" will refer to Microsoft COM (as opposed to XPCOM). Gecko and apartments Most code that runs on Gecko's main thread is not thread safe. Since Gecko's main thread uses COM, and COM requires threads to declare their threading model, the main...
...iquePtr, because MainThreadHandoff::WrapInterface requires one in its input. Integrating interceptors into the a11y tree Now that we have solved the apartment problem, and know how to wrap a COM interface with an interceptor, we need to discuss how these things fit into the a11y tree. In general, the only COM objects which should need to be explicitly wrapped are the IAccessibles for top-level documents in the content process. As mentioned previously, the interceptor will automatically wrap outparams. When a wrapped COM object is queried for its children, those children are provided as outparams, and will themselves be wrapped. ...
Accessibility and Mozilla
These articles provide Mozilla-specific details about accessibility. Accessibility API cross-referenceThis cross-reference helps us see the difference between today's accessibility API's. ...
....Mozilla accessibility architectureThis page is maintained by Aaron Leventhal and by the Mozilla Accessibility Community. Feedback and constructive suggestions are encouraged.Mozilla Plugin AccessibilityPlugins in Gecko-based browsers have a lot of accessibility issues. Here is a rundown of problems and the planned solutions:Mozilla's Section 508 ComplianceMozilla's UAAG evaluation reportThe UAAG document contains a very rich set of accessibility guidelines, that broadly define how accessibility should be implemented by any user agent, i.e. software that renders web content. The UAAG is not the basis for any government accessibility regulations at this time.Multiprocess on WindowsA high-level overview of the ideas behind the a11y+e10s design is available on the wiki.Software accessibility: Where a...
Debugging JavaScript
It should give pointers to tools, aids and tricks which make debugging your code easier. Web Console This is the first place to go when you're debugging a web page; open the Web console using the Web Console option in the Web Developer menu. This shows any JavaScript errors in your app, as well as any logging calls from the console API. Browser Console The Browser Console lets you see all JavaScript errors and logging in the browser, including from Firefox code. ...
... ...
Debugging on Mac OS X
If you want to debug from the terminal see Debugging Mozilla with lldb. For specific information on a way to debug hangs, see Debugging a hang on OS X. Creating a debuggable build First, you need to build the application you're going to debug using --disable-optimize--enable-debug-symbols in your .mozconfig (also add --enable-debug if you want assertions etc. compiled in). See Building Firefox for macOS if you need help creating your own build. Debugging Firefox on macOS 10.14+ macOS 10.14 introduced Notarization and Hardened Runtime features for improved application security. ...
... by default and eliminate this discrepancy. To obtain a Hardened Runtime build without using try infrastructure, a developer can manually codesign builds using the macOS codesign(1) command with the developer.entitlements.xml file from the tree. This requires creating a codesigning identity. Disabling System Integrity Protection (SIP) If debugging a production build is required, follow Apple's documented steps for disabling System Integrity Protection (SIP). Note that disabling SIP bypasses Hardened Runtime restrictions which can mask some bugs that only occur with Hardened Runtime so it is recommended to test fixes with SIP enabled. Disabling SIP has system security implications that should be understood before taking this step. Creating an Xcode project If you try to create a new Xcode pro...
The Firefox codebase: CSS Guidelines
Basics Here are some basic tips that can optimize reviews if you are changing CSS: Avoid !important but if you have to use it, make sure it's obvious why you're using it (ideally with a comment). 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. ...
...g to be aware of if you create a focus ring or a border using the box-shadow property: consider using a border or an outline if you want the border/focus ring to stay visible in high-contrast mode. An example of such bug is bug 1516767. Another adjustment to be aware of is that Gecko removes all the background-image when high contrast mode is enabled. Consider using an actual <img> tag (for HTML documents) or list-style-image (for XUL documents) if rendering the image is important. If you are not using Windows, one way to test against those adjustments on other platforms is: Going to about:preferences Clicking on the "Colors..." button in the "Fonts & Colors" sub-section of the "Language and Appearance" section Under "Override the colors specified by the page with your selections above", se...
Interface development guide
IDL interface rules Design guidelines and rules when creating and changing XPCOM interfaces. ...
.... The articles linked from this page offer guidelines for developing and using these interfaces. Documentation XPIDL The XPCOM Interface Description Language is used to specify XPCOM interface classes. IDL interface rules Design guidelines and rules when creating and changing XPCOM interfaces. If you're going to be changing an interface, be sure to read these first! Commenting IDL for better documentation A guide explaining how to properly comment your interface's IDL in order to ensure that not only can others understand your interface, but to ensure that the documentation here on MDC is as accurate as possible. Community View Mozilla embedding forums... Mailing list Newsgroup RSS feed Related Topics JavaScript, XPCOM, Developing Mozilla ...
Reviewer Checklist
ld be logged at the appropriate level, bearing in mind personally identifiable information, but also considering the expense of computing and recording log output. [Fennec: Checking for log levels is expensive unless you're using Logger.] Style Follow the style guide for the language and module in question. Follow local style for the surrounding code, even if that local style isn't formally documented. New files have license declarations and modelines. New JS files should use strict mode. Trailing whitespace (git diff and splinter view both highlight this, as does hg with the color extension enabled). Whitespace can be fixed easily in Mercurial using the CheckFiles extension. In git, you can use git rebase --whitespace=fix. Security issues There should be no writing to arbitrary file...
...d-time flags. Which one you choose depends on how the feature is implemented: a pure Java service can't easily check Gecko prefs, for example.] Strings There should be no string changes in patches that will be uplifted (including string removals). Rev entity names for string changes. When making UI changes, be aware of the fact that strings will be different lengths in different locales. Documentation The commit message should describe what the patch is changing (not be a copy of the bug summary). The first line should be a short description (since only the first line is shown in the log), and additional description, if needed, should be present, properly wrapped, in later lines. Adequately document any potentially confusing pieces of code. Flag a bug with dev-doc-needed if any addon...
SVG Guidelines
When used as an image format, it is sometimes less obvious whether it would be best to use SVG or a raster image format for any given image. The vector format SVG and raster formats like PNG both have their place. When choosing whether or not to use SVG it is best to understand the advantages and disadvantages of both. File size Whether SVG or a raster format will produce a smaller file for a given image depends very much on the image. For example, consider an image of a path with a gradient fill. The size of an SVG of this image will be the same regardless of the dimensions of the image. ...
...CSS/SVG transforms, apply directly the transform on the path/shape definition. Tools Tools can help to clean SVG files. Note, however that some of the rules stated above can be hard to detect with automated tools since they require too much context-awareness. To this date, there doesn't seem to be a tool that handles all of the above. ...
Experimental features in Firefox
nd video tracks, the most common use cases for these properties don't work, so they're both disabled by default. See bug 1057233 for more details. Release channel Version added Enabled by default? Nightly 33 No Developer Edition 33 No Beta 33 No Release 33 No Preference name media.track.enabled DOM Document property: autoplayPolicy The document property autoplayPolicy returns a string indicating how the browser handles requests to automatically play media (either using the autoplay property on a media element or by attempting to trigger playback from JavaScript code. The spec for this API is still being written. The value changes over time depending on what the user is doing, their preferences, and...
...It also supports events to monitor changes to this information. See bug 1550390 for more details. There currently is no real plan to ship this on desktop, but you can track the state of that just in case it changes in bug 1551302. Release channel Version added Enabled by default? Nightly 63 No Developer Edition ...
Index
Found 172 pages: # Page Tags and summary 1 Firefox Firefox, Landing, Mozilla Here you can learn about how to contribute to the Firefox project and you will also find links to information about the construction of Firefox add-ons, using the developer tools in Firefox, and other topics. 3 Building Firefox with Rust code Build documentation, Gecko, build, rust In May 2015 the Rust programming language reached its 1.0 stability milestone, and various experiments with writing parts of Gecko in Rust began. Rust code first shipped in August 2016 with the release of Firefox 48. It became a requirement for building Gecko in February 2017 with Firefox 54. 8 Experimental features in Firefox Experimental, Firefox, Preferences, features ...
...erformance This guide will help Firefox developers working on front-end code produce code which is as performant as possible--not just on its own, but in terms of its impact on other parts of Firefox. Always keep in mind the side effects your changes may have, from blocking other tasks to interfering with other user interface elements. 169 Privacy Privacy, Security This document lists privacy-related documentation. 170 Storage access policy: Block cookies from trackers Privacy, storage access policy, tracking protection Firefox includes a new storage access policy that blocks cookies and other site data from third-party tracking resources. This new policy is designed as an alternative to the current policies, which have been available in Firefox for ...
Security best practices for Firefox front-end engineers
This article will help Firefox developers understand the security controls in place and avoid common pitfalls when developing front-end code for Firefox. Existing Security Controls Sanitizing all strings that enter the DOM through APIs such as innerHTML When running system-privileged chrome code, we sanitize all HTML fragments that are created for chrome-privileged documents. This policy includes all DOM APIs that take a string and parse it into a DOM tree. We use our built-in sanitizer with the following flags: SanitizerAllowStyle SanitizerAllowComments SanitizerDropForms SanitizerLogRemovals The sanitizer removes all scripts (script tags, event handlers) and form elements (form, input, keygen, option, optgroup, select, button, datalist). The canonical truth for the list of whitelisted ele...
...opers are able to avoid tripping the rule by using escaping functions in combination with template strings, for example: bar.innerHTML = escapeHTML`<a href='${url}'>About</a>`; In system-privileged chrome code, any kind of remaining scripts will still be removed by our sanitizer. Appendix List of disallowed DOM APIs innerHTML outerHTML insertAdjacentHTML() createContextualFragment() document.write() document.writeln() Please take a look at the repository for an updated list ...
Firefox
y our huge community of volunteers. Here you can learn about how to contribute to the Firefox project and you will also find links to information about the construction of Firefox add-ons, using the developer tools in Firefox, and other topics. Learn how to create add-ons for Firefox, how to develop and build Firefox itself, and how the internals of Firefox and its subprojects work. Project documentation Get detailed information about the internals of Firefox and its build system, so you can find your way around in the code. Developer guide Our developer guide provides details on how to get and compile the Firefox source code, how to find your way around, and how to contribute to the project. Contents Experimental features in FirefoxThis page lists features that are in Night...
...te.Performance best practices for Firefox front-end engineersThis guide will help Firefox developers working on front-end code produce code which is as performant as possible--not just on its own, but in terms of its impact on other parts of Firefox. Always keep in mind the side effects your changes may have, from blocking other tasks, to interfering with other user interface elements.PrivacyThis document lists privacy-related documentation.Security best practices for Firefox front-end engineersThis article will help Firefox developers understand the security controls in place and avoid common pitfalls when developing front-end code for Firefox.Site Identity ButtonThe Site Identity Button is a feature in Firefox that gives users more information about the sites they visit. Firefox profiles ...
HTMLIFrameElement.getContentDimensions()
Warning: Removed in Firefox 65. The getContentDimensions() method of the HTMLIFrameElement interface retrieves the X and Y dimensions of the content window. Note: The values returned are equivalent to document.body.scrollWidth and document.body.scrollHeight. Syntax var instanceOfDOMRequest = instanceOfHTMLIframeElement.getContentDimensions(); Returns A DOMRequest for handling the dimensions request. Its request.onsuccess handler handles the success case, and its request.onerror handler handles the failure case. ...
...stanceOfDOMRequest = instanceOfHTMLIframeElement.getContentDimensions(); Returns A DOMRequest for handling the dimensions request. Its request.onsuccess handler handles the success case, and its request.onerror handler handles the failure case. The X and Y dimensions are available in the request.result.x and request.result.y properties, respectively. Parameters None. Examples var browser = document.querySelector('iframe'); var request = browser.getContentDimensions(); request.onsuccess = function() { console.log("page size:", request.result.width + "x" + request.result.height); } request.onerror = function() { console.log("Download error"); } Specification Not part of any specification. ...
HTMLIFrameElement.getMuted()
er to handle the success case, and an onerror handler to handle the failure case. The muted value is available in the request.result property, and is a Boolean value -- true means muted, and false means unmuted. Promise version: A Promise that resolves with the muted value -- a Boolean where true means muted, and false means unmuted. Parameters None. ...
...muted value -- a Boolean where true means muted, and false means unmuted. Parameters None. Example Callback version: var browser = document.querySelector('iframe'); var request = browser.getMuted(); request.onsuccess = function() { if(request.result) { console.log('The browser is muted.'); } else { console.log('The browser is unmuted.'); } } Promise version: var browser = document.querySelector('iframe'); browser.getMuted().then(function(muted) { if(muted) { console.log('The browser is muted.'); } else { console.log('The browser is unmuted.'); } }); Specification Not part of any specification. ...
mozbrowsercontextmenu
ject, below) representing a custom menu defined via <menu> / <menuitem> elements and pointed to via a contextmenu attribute on the DOM element clicked on, which contains the menu's id. contextmenuItemSelected An anonymous function that fires when a menu item is selected. The MenuSystem object An object defining a standard context menu that will be displayed. Its properties are as follows: documentURI A DOMString representing the URL of the document the menu is associated with. uri A DOMString. In the case of an image or video context menu, this is the src of the image or video clicked on to get the context menu. In the case of an link context menu, it is the link's href. text A DOMString representing the text of the link clicked on, in the case of a link context menu. hasVideo A Boo...
... icon, if the context menu being accessed is a menu item. id The menu item's id, if the context menu being accessed is a menu item. This is passed to the contextmenuItemSelected() function, to indicate which item has been selected. items An array of further Menu objects, which indicate the menu options available in a menu, if the context menu being accessed is a menu. ...
HTMLIFrameElement.purgeHistory()
st = instanceOfHTMLIframeElement.purgeHistory(); instanceOfHTMLIframeElement.purgeHistory().then(function() { ... }); Returns Either A DOMRequest object that returns an onsuccess handler if the history is deleted, or an onerror handler if not. A Promise that resolves, with no parameters, if the history is deleted, or rejects if not. Parameters None. ...
...dler if not. A Promise that resolves, with no parameters, if the history is deleted, or rejects if not. Parameters None. Examples DOMRequest: var browser = document.querySelector('iframe'); var request = browser.purgeHistory(); request.onsuccess = function() { console.log('History deleted!'); } request.onerror = function() { console.error(this.error.name); } Promise: var browser = document.querySelector('iframe'); browser.purgeHistory().then(function() { console.log('History deleted!'); }, function(error) { console.error(this.error.name); }); Specification Not part of any specification. ...
Browser API
browser <iframe> content. mozbrowsercaretstatechanged Sent when the text selected inside the browser <iframe> content changes. mozbrowserclose Sent when window.close() is called within a browser <iframe>. mozbrowsercontextmenu Sent when a browser <iframe> tries to open a context menu. This allows handling of the <menuitem> element available within the browser <iframe>'s content. mozbrowserdocumentfirstpaint Sent when a new paint occurs on any document in the browser <iframe>. mozbrowsererror Sent when an error occurs while trying to load content within a browser <iframe>. mozbrowserfindchange Sent when a search operation is performed on the browser <iframe> content (see HTMLIFrameElement search methods.) mozbrowserfirstpaint Sent when the <iframe> paints content for the first time (...
...en the SSL state changes within a browser <iframe>. mozbrowserselectionstatechanged Sent when the text selected inside the browser <iframe> content changes. Note that this is obsolete, and newer implementations use mozbrowsercaretstatechanged instead. mozbrowsershowmodalprompt Sent when alert(), confirm(), or prompt() are called within a browser <iframe>. mozbrowsertitlechange Sent when the document title changes within a browser <iframe>. mozbrowserusernameandpasswordrequired Sent when an HTTP authentification is requested. mozbrowseropensearch Sent when a link to a search engine is found. mozbrowservisibilitychange Sent when the visibility state of the current browser iframe <iframe> changes, for example due to a call to setVisible(). Specifications This API isn't part of any offi...
overflow-clip-box-block
...
... ...
overflow-clip-box-inline
...
... ...
overflow-clip-box
...
... ...
smartcard-insert
The smartcard-insert event is fired when the insertion of a smart card has been detected Specification Mozilla specific Interface Event Bubbles No Cancelable No Target document Default Action None Properties Property Type Description targetRead only EventTarget The event target (the topmost target in the DOM tree). typeRead only DOMString The type of event. ...
...Properties Property Type Description targetRead only EventTarget The event target (the topmost target in the DOM tree). typeRead only DOMString The type of event. bubblesRead only Boolean Whether the event normally bubbles or not. cancelableRead only Boolean Whether the event is cancellable or not. Example document.addEventListener("smartcard-insert", smartcardChangeHandler ); Related Events smartcard-remove ...
smartcard-remove
The smartcard-remove event is fired when the removal of a smart card has been detected. Specification Mozilla specific Interface Event Bubbles No Cancelable No Target document Default Action None Properties Property Type Description targetRead only EventTarget The event target (the topmost target in the DOM tree). typeRead only DOMString The type of event. ...
...Properties Property Type Description targetRead only EventTarget The event target (the topmost target in the DOM tree). typeRead only DOMString The type of event. bubblesRead only Boolean Whether the event normally bubbles or not. cancelableRead only Boolean Whether the event is cancellable or not. Example document.addEventListener("smartcard-remove", smartcardChangeHandler ); Related Events smartcard-insert ...
HTTP Cache
The cache API is completely thread-safe and non-blocking. There is no IPC support. It's only accessible on the default chrome process. When there is no profile the new HTTP cache works, but everything is stored only in memory not obeying any particular limits. It is strongly encoraged to NOT USE the OLD cache API any more - nsICacheService et al. It will soon be completely obsoleted and removed (bug 913828). nsICacheStorageService The HTTP cache entry-point. ...
... supports several priority levels. Dispatching to a level with a lower number is executed sooner then dispatching to higher number layers; also any loop on lower levels yields to higher levels so that scheduled deletion of 1000 files will not block opening cache entries. ...
Implementing QueryInterface
A reference implementation of QueryInterface NS_IMETHODIMP nsMyImplementation::QueryInterface( REFNSIID aIID, void** aInstancePtr ) { NS_ASSERTION(aInstancePtr, "QueryInterface requires a non-NULL destination!"); // It's a logic error, not a runtime error, to call me without any place to put my answer! // ...but that won't matter when someone calls me wrongly in a non-debug build. ...
..._CAST(nsIX*, this); else if ( aIID.Equals(NS_GET_IID(nsIY)) ) foundInterface = NS_STATIC_CAST(nsIY*, this); // ...as many cases as needed... else if ( aIID.Equals(NS_GET_IID(nsISupports)) ) // ... Thanks Special thanks to Heikki Toivonen, Chris Waterson, and John Bandhauer for valuable feedback that significantly improved the implementations presented here. Original Document Information Author(s): Scott Collins Last Updated Date: May 8, 2003 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Implementing Download Resuming
The interfaces in question exist in the form they are described here since Gecko 1.8a4 (Firefox 1.5, SeaMonkey 1.0, XULRunner 1.8.0.1). Introduction Various protocols support getting partial files. This means that if a download was interrupted, it can be resumed from that point on, rather than regetting the whole file. The Necko implementations of HTTP 1.1 (RFC 2616) as well as FTP support this feature. Not only is the ability to specify a start position important, but it's also important to have some assurance that the file did not change since the initial download attempt. ...
...for later use. The entity ID is what ensures that the file remains unchanged. This can also be used to check whether the download is resumable: if it is not (e.g. the server is not using HTTP 1.1), then accessing this attribute will throw an NS_ERROR_NOT_RESUMABLE exception. If the download gets interrupted, Necko will call the stream listener's onStopRequest method with a failure status. (TODO: document what webbrowserpersist/exthandler do). The front-end code can then notify the user of this, and offer to resume the download. Resuming a download In order to resume a download, you should create a channel as usual (using nsIIOService). Then, you can check if it implements nsIResumableChannel. If it does not, the protocol does not support resuming. Otherwise, call resumeAt with the desired star...
JavaScript Tips
ethod parameters as are used in the interface definition. DOM elements DOM elements are just XPCOM objects with some of the interfaces precached. Don't call getAttribute to see if an attribute exists, call hasAttribute instead. Prefer to loop through childNodes rather than using first/lastChild with next/previousSibling. But prefer hasChildNodes() to childNodes.length > 0. Similarly prefer document.getElementsByTagName(aTag).item(0) != null to document.getElementsByTagName(aTag).length > 0. Prefer to use localName rather than tagName. XUL elements have many of the attributes mapped to properties. This was done for a reason, so use them! The properties are: align allowEvents contextMenu datasources dir flex height id left maxHeight maxWidth minHeigh...
...s, but note that these are boolean properties whereas the above list are all string properties. XUL also maps other useful properties and methods using XBL bindings; these vary from element to element. For best performance give ids to all important elements. However in addition to locating elements by tag name XUL also allows you to locate an element by attribute, starting at any element in the document. References This was started as a reprint of Neil's guide Some more current info on this blog post How to remove duplicate objects from an array JavaScript ...
OS.File for the main thread
I/O from the main thread. For other uses of OS.File, please see the corresponding page. Using OS.File from a JSM To import OS.File into your chrome code, add the following line at the start of your script: Components.utils.import("resource://gre/modules/osfile.jsm") Promises Before using OS.File from the main thread, you need some understanding of the Promise library. See the Promise object documentation for details. Also, OS.File plays very nicely with Task.jsm. Example: Read the contents of a file as text The following snippet opens a file "file.txt" and read its contents as a string, using the default encoding (utf-8). The content is read asynchronously. The result is a Promise. let decoder = new TextDecoder(); // This decoder can be reused for several reads let promise = OS.F...
...Image to load an image from a path (note: if your path is a file on disk you must use local file; this is accomplished with OS.Path.toFileURI, which accepts a string). After image loads it then draws it to canvas, makes it a blob, and uses FileReader to turn it into ArrayBuffer(View), then uses OS.File.writeAtomic to save to disk. ...
Bootstrapping a new locale
In Mozilla, we use the the Mercurial version control system (Hg) to help manage our localizations. When a localization team is registered and your Hg repository is set up for a locale, you can then clone the existing Mozilla release branch (i.e. where active development of the upcoming release of Firefox occurs) and then begin the necessary work for translation. ...
... Mozilla release branch (i.e. where active development of the upcoming release of Firefox occurs) and then begin the necessary work for translation. Hg allows localizers to work locally on their machines and then "push" changes to their official Mozilla repository. Installing Mercurial Depending on your operating system, you will need to install the correct version of Hg on your machine. This document will give you the basic information on how to do that. Install the compare-locales utility The next step is to install compare-locales. $ sudo easy_install compare-locales This will download and install the utility. Clone the source code The next step is to download a copy of the source code to your local system, using Mercurial. You will need to "hg clone" the existing release branch for...
Localization and Plurals
# #1 number of files # example: 111 files - Downloads downloadsTitleFiles=#1 file - Downloads;#1 files - Downloads # LOCALIZATION NOTE (timePair): #1 time number; #2 time unit # example: 1 second; 11 seconds timePair=#1 #2 seconds=second;seconds minutes=minute;minutes hours=hour;hours downloads.js: Components.utils.import("resource://gre/modules/PluralForm.jsm"); let getStr = function(string) document.getElementById("strings").getString(string); // Get the correct plural form for the title let numDownloads = 3; let title = PluralForm.get(numDownloads, getStr("downloadsTitleFiles")); // Put in the correct number of downloads print(title.replace("#1", numDownloads)); // Get the correct plural form of seconds let timeLeft = 55; let seconds = PluralForm.get(timeLeft, getStr("seconds")); // Print...
... ...
Localizing with Koala
oose "koala" in the Categories list. Choose "koala" in the Templates list. Choose a name for your project (e.g. l10n.kpf). Choose the directory in which the project will live in (e.g. C:\mozilla\l10n on Windows, /home/user/mozilla/l10n on Linux or /Users/user/mozilla/l10n on Mac OS X). Due to a bug in Koala (bug 21930), it is recommended that you don't choose a path that contains spaces (like C:\Documents and Settings\user\...). Click "Open" to create the project. Koala will check for Mercurial. Make sure that your Mercurial installation is in your system's $PATH. Setup wizard will open. Configure the Application Choose "Firefox" as the application. Version: 3.6. Appname: browser. Included locale: en-US (this is the original locale you're translating from). Leave Location empty for now. Ch...
...w > Tabs & Sidebars > Projects from the menu. Switch to "Koala file view" in the sidebar (choose it from the list that appears when you click on the arrow pointing down situated next to the sidebar's [x] button). You should now see the results of the comparison in the "Koala file view" sidebar. Translating files Let's translate the searchbar-related strings mentioned in the beginning of 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 cod...
Localizing with Mercurial
ozilla, we use the the Mercurial version control system (Hg) to manage our source code and localizations. Mercurial allows localizers to work locally (on their machines) and then push (an Hg term) changes to a remote repository, which usually is hosted on the Mozilla servers (hg.mozilla.org). Localizing current versions of Firefox, Thunderbird and SeaMonkey includes working with Mercurial. If the documentation is incomplete or you have questions, please drop by the #l10n or #hg channels on irc.mozilla.org. The Mercurial FAQ are also worth a read, should you run into trouble. For the eager and quick, below you'll find instructions on installing and configuring Mercurial, instructions on receiving an Hg account commit priviledges, as well as a few tasks you can complete without account priviledges.
...change, run hg qrefresh to commit your changes to the patch. Navigate to your <repository>/.hg/patches to find your .patch. You may repeat from step 4 to create another patch. Your patches will be incremental, i.e. new patches are created based on old patches. If you want to commit all the patches to the repository and cleanup the patch queue, run hg qfinish. Please refer to MqTutorial and Mq documentation for further uses of Mq extension to manage patches. Mercurial account priviledges Eventually, you or your team leader will need Hg account priviledges. Let's face it, it's just more convenient to commit and push your work to the remote repo yourself, rather than creating patches and asking someone else to push them for you. To get write access to the l10n hg repositories on the Mozilla se...
Localization formats
Warning: This document pertains to the development of Mozilla web sites and not to the development of Gecko-based extensions or applications. There are 4 main approaches to web l10n with regards to the choice of technology used for localization logic: HTML/PHP .lang gettext (.po) wiki (TBD) The choice of the filetype depends on a couple of factors: How much content is there to be localized? How often, if at all, the site will be updated after the launch? Is this a long-term project with continuous updates to content? Is this a long-term project with stable content? Is this a short-term project? Will the content differ per locale? If so, to what extent? As every new web-dev project takes shape, a project manager should ask themselves these questions an...
...f the code, protecting it from unintended changes Disadvantage of gettext .po file needs to be compiled into a .mo file for localizer to see changes Using regular diff to see changes to a file is sometimes impossible because the editing tool can save the .po file using a completely different structure or order of entities. Read more about gettext on Wikipedia and on MDC. Wiki Blogging, documentation, and other types of Mozilla content often surface as wikis. Case study: Download Day In the above Gettext example, notice how the web developer used "certificate_intro" as the value of the msgid. This is not the actual content that was translated. So, if a localizer wanted to use one of the many powerful Gettext tools, like po-editor, the msgid provides NO CONTEXT for translation or for ot...
Mozilla Framework Based on Templates (MFBT)
throughout Mozilla code, including in the JavaScript engine. 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. ...
...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. It also attempts to define its functionality in well-named files, such that simply skimming the contents of mfbt/ will quickly suggest the relevant header to examine. Therefore this document primarily attempts to direct readers to the correct file to read those comments. Feel free to file a documentation bug if you think this approach could be improved, and feel free to make improvements to this document if you see them. Functionality Types and type manipulation StandardInteger.h implements the <stdint.h> interface. (The <stdint.h> standard header is not available on all platforms...
MathML Demo: <mspace> - space
trol" href="javascript:downdepth();" title="decrease depth">-</a> <math display="block"> <mstyle displaystyle="true"> <msqrt> <mrow> <mn>3</mn> <mspace style="background-color: yellow" id="thespace" height="0.1ex" depth="0.1ex" width="0.1em" /> <mi>x</mi> </mrow> </msqrt> </mstyle> </math> </p> JavaScript Content var height=0; var width=0; var depth=0; function upheight() { height++; document.getElementById("thespace").setAttribute("height",height+".1ex"); } function downheight() { height--; document.getElementById("thespace").setAttribute("height",height+".1ex"); } function upwidth() { width++; document.getElementById("thespace").setAttribute("width",width+".1em"); } function downwidth() { width--; document.getElementById("thespace").setAttribute("width",width+".1em"); } ...
...ribute("height",height+".1ex"); } function downheight() { height--; document.getElementById("thespace").setAttribute("height",height+".1ex"); } function upwidth() { width++; document.getElementById("thespace").setAttribute("width",width+".1em"); } function downwidth() { width--; document.getElementById("thespace").setAttribute("width",width+".1em"); } function updepth() { depth++; document.getElementById("thespace").setAttribute("depth",depth+".1ex"); } function downdepth() { depth--; document.getElementById("thespace").setAttribute("depth",depth+".1ex"); } ...
Mozilla MathML Project
elp us improving MathML in Mozilla. Links Installing fonts for Mozilla's MathML engine MathML Version 3.0 - W3C Recommendation, 21 October 2010 W3C MathML Test Suite - Designed to check the implementation of each element one attribute (or built-in rendering behavior) at a time in a fairly thorough manner. MathML in Mozilla Developer Network MathML Accessibility in Mozilla Sample MathML Documents Screenshots MathML Start Page - with translations in different languages ( Arabic, Chinese, Hebrew, Thai) MathML Basics - Document tailored to display correctly with just the Symbol font that is pre-installed by default on most OS configurations. MathML Torture Test - Comparative testing of MathML rendering against TeX. Demo of some MathML tags: mfrac, mo, mtable, mspace, mmultiscripts, m...
... Test - Comparative testing of MathML rendering against TeX. Demo of some MathML tags: mfrac, mo, mtable, mspace, mmultiscripts, msqrt-mroot. MathML Extras - Technology demonstration of some interesting upshots from building natively upon the browser environment. Various MathML Tests - These pages were imported from layout/mathml/tests/. Blog with comments that include MathML. Create MathML Documents Authoring MathML Editors Converters Stylesheets Original Document Information Author(s): Roger B. Sidje Other Contributors: Frederic Wang Last Updated Date: April 4, 2010 Copyright Information: Portions of this content are (C) 1999-2010 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Mozilla Style System
code that turns the specified values into computed values. The barrier between these two halves consists of three abstract interfaces, plus some smaller structures associated with some methods on each: nsIStyleSheet nsIStyleSheet represents what one would think of as a style sheet: the in-memory representation of a CSS file or other source of style data. Some style sheets are managed by the document; some apply to all documents. The style system actually has relatively little to do with style sheets; it instead deals with style rule processors. nsIStyleRuleProcessor a style rule processor represents an origin within the CSS cascade. Thus there is a single style rule processor for all user-agent CSS style sheets, a single style rule processor for all user CSS style sheets, and a single s...
...s->mWidth.GetUnit() == eStyleUnit_Coord) { nscoord w = stylePos->mWidth.GetCoordValue(); ... } else if (stylePos->mWidth.GetUnit() == eStyleUnit_Percent) { ... Rule tree Style data computation CSS style sheet backend Loading Parsing Data structures Cascading HTML Mapped Attribute backend CSS style attribute backend Handling of dynamic changes See Also Mozilla Style System Documentation (2002) Style System Tech Talk (2002) ...
Refcount tracing and balancing
cShell XPCOM_MEM_REFCNT_LOG=./refcounts.log ./mach run This will log the AddRef and Release calls only for instances of nsDocShell while running the browser using mach, to a file refcounts.log. Note that setting XPCOM_MEM_LOG_CLASSES will also list the serial number of each object that leaked in the "bloat log" (that is, the file specified by the XPCOM_MEM_BLOAT_LOG variable; see the BloatView documentation for more details). An object's serial number is simply a unique number, starting at one, that is assigned to the object when it is allocated. You may use an object's serial number with the following variable to further restrict the reference count tracing: XPCOM_MEM_LOG_OBJECTS Set this variable to a comma-separated list of object serial number or ranges of serial number, e.g., 1,37...
...eleases from smart pointers. If you've checked (see above) that the leak wasn't from a smart pointer, you can ignore the references that came from smart pointers (where we can use the pointer identity of the smart pointer to match the AddRef and the Release). This requires using an XPCOM_MEM_REFCNT_LOG and an XPCOM_MEM_COMPTR_LOG that were collected at the same time. For more details, see the old documentation (which should probably be incorporated here). This is best used with --ignore-balanced Play Mah Jongg. An unbalanced tree is not necessarily an evil thing. More likely, it indicates that one AddRef() is cancelled by another Release() somewhere else in the code. So the game is to try to match them with one another. Exclude Functions. To aid in this process, you can create an "excludes file"...
Scroll-linked effects
- in short, something we want to avoid. Below are a couple of examples of effects that would not work well with asynchronous scrolling, along with equivalent versions that would work well: Example 1: Sticky positioning Here is an implementation of a sticky-positioning effect, where the "toolbar" div will stick to the top of the screen as you scroll down. <body 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...
...If it is, then it triggers an animation...
TimerFirings logging
Invocation TimerFirings logging uses Gecko's own logging mechanism, and so is able to be used in any build. ...
...timer (ONE_SHOT): [content] http://widgets.outbrain.com/outbrain.js:20:330 186 fn timer (ONE_SHOT): nsBrowserStatusFilter::TimeoutHandler 138 fn timer (ONE_SHOT): [content] https://self-repair.mozilla.org/repair/:7:13669 118 fn timer (ONE_SHOT): [content] http://a.visualrevenue.com/vrs.js:6:9423 108 fn timer (SLACK): LayerActivityTracker 104 fn timer (SLACK): nsIDocument::SelectorCache 104 fn timer (SLACK): CCTimerFired ...
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). ...
... 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 exit; re-read the source files each time the window or dialog needs to be displayed. False: Cache XUL documents in memory and save the cache to disk on exit to improve performance. (Default) See also: http://kb.mozillazine.org/Nglayout.debug.disable_xul_cache ...
Preference reference
ed.mail.tabs.drawInTitlebarStarting in Thunderbird 17.0, the tabs are drawn in the title bar. ...
....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.alertNotificationOriginui.alertN...
Preferences system
This document describes Toolkit's preferences system. Using this system it is possible to create preferences windows that display and operate appropriately on various platforms (Windows, MacOS X and GNOME). The system is implemented through a few XUL elements and attributes. ...
... This document describes Toolkit's preferences system. Using this system it is possible to create preferences windows that display and operate appropriately on various platforms (Windows, MacOS X and GNOME). The system is implemented through a few XUL elements and attributes. ...
A guide to searching crash reports
The Mozilla crash-stats site provides facilities for investigating large numbers of Firefox crash reports. This guide to searching through crash reports may help you locate the crash reports that will help you find and fix the Firefox bug you're working on. Specifically, crash-stats offers two basic functions: Searching You can search the crash reports database by over 100 criteria: crash signature, date, platform, product, version, etc. Grouping You can cluster the results of each search into groups using the same criteria. To achieve full power and flexibility requires a good understanding of both of these functions. ...
...e of the 100+ fields available for searching and grouping. One way to learn about them is to read lots of individual crash reports; note that all fields shown in the Details tab of an individual crash report have a tool-tip that indicates its key for search. Alternatively, you can browse the complete list. There is also an API through which searches can be performed programmatically. See the API documentation for full details; note that it uses the term "aggregation" for grouping/faceting. ...
L20n HTML Bindings
Download L20n with HTML Bindings We maintain a repository with L20n optimized for production use: one file (~110KB) one file, minified (~35KB) It's recommended to include the l20n.js file as the last script in the head element. <head> ... <script src="l20n.js"></script> </head> Create Manifest Use a localization manifest to define available languages and their resource files. ...
...milarly, href and onclick attributes are not allowed in translations and they are not inserted in the final DOM. However, the title attribute is safe. It is important to note that applying translations doesn't replace DOM elements, but only modifies their text nodes and their attributes. This makes it possible to use L20n in conjunction with MVC frameworks. When all DOM nodes are localized, the document element will fire a DocumentLocalized event, which you can listen to: document.addEventListener('DocumentLocalized', function() { // the DOM has been localized and the user sees it in their language YourApp.init(); }); Exposing Context Data You can expose important bits of data to the localization context in form of context data. <script type="application/l10n-data+json"> { "newNotifi...
L20n Javascript API
sten 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. ctx.localize(['hello', 'new'], function(l10n) { var node = document.querySelector('[data-l10n-id=hello]'); node.textContent = l10n.entities.hello.value; node.classList.remove('hidden'); }); ctx.registerLocales(defaultLocale: String?, availableLocales: Array<String>?) Register the default locale of the Context instance, as well as all other locales available to the Context instance before the language negotiation. Locales are referenced by their BCP 47 lan...
...le code of the language the entity is in; it can be different than the first locale in the current fallback chain if the entity couldn't be evaluated and a fallback translation had to be used. ctx.localize(ids: Array<String>, callback: Function) Registers a callback which fires when all entities listed in ids have been retrieved. ctx.localize(['hello', 'about'], function(l10n) { var node = document.querySelector('[data-l10n-id=hello]'); node.textContent = l10n.entities.hello.value; node.classList.remove('hidden'); }); The callback becomes bound to the entities on the ids list. It will be called when the entities become available (asynchronously) or whenever the translation of any of the entities changes. localize should be the preferred way of localizing the UI. The callback functi...
Localization Use Cases
In all presented examples, we try to show the existing code, explain the problem from the localizers' or developers' perspective, and suggest a solution. Declensions In Gaia's Browser app, there's an about-browser string defined as follows in apps/browser/locales/browser: about-browser=About {{browserBrandShortName}} Problem definition In many inflected languages (e.g. German, Finnish, Hungarian, all Slavic languages), the about preposition governs the grammatical case of the complement. It might be the accusative (German), ablative (Latin) or locative (Slavic languages). Let's take Slovenian as an example. ...
...B = 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) { // ... ...
AsyncTestUtils extended framework
syncUrlListener. copy listener: asyncCopyListener. Bringing messages into the picture Synthetic set definitions Most of the code involved in creating synthetic messages takes an object that defines how to generate the set. The following is a list of frequently used attributes where the default value is listed after the attribute name. There are more attributes you can specify; consult the documentation for more information. (See the bottom of this page for links to the source files.) count: 10 The number of messages that should be in the set. Note that the default is subject to change, so if you want 10, say 10, instead of relying on the default. msgsPerThread: 1 How many messages should be in each thread? The default is that every message is its own thread; no message is a reply to ...
...and add them to the provided folders. Like make_folders_with_sets, the messages are spread across the folders. Folders Create a folder let folderHandle = make_empty_folder(aOptionalFolderName); You do not have to specify a folder name - if you don't care, we'll make one up for you. If you need to get fancy about having flags set on the folder, we support that, but please check the method documentation. Get / create the Junk folder let junkFolder = get_junk_folder(); Create a Virtual folder (a folder whose contents are the result of a saved search) let virtualFolder = make_virtual_folder([aFolderToSearch1, aFolderToSearch2, ...], {subject: "", body: "", from: "", to: "", cc: "", recipient: "", involves: ""}, ...
NSPR Poll Method
The poll method is not to be confused with the PR_Poll function. The poll method operates on a single NetScape Portable Runtime (NSPR) file descriptor, whereas PR_Poll operates on a collection of NSPR file descriptors. PR_Poll uses the poll method behind the scene, but it is also possible to use the poll method directly. We consider a stack of NSPR I/O layers on top of the network transport. Each I/O layer is represented by a PRFileDesc structure and the protocol of that layer is implemented by a PRIOMethods table. The bottom layer is a wrapper for the underlying network transport. ...
...or PR_Send when the underlying network transport is readable If new_flags contains PR_POLL_WRITE, you should try PR_Recv or PR_Send when the underlying network transport is writable Important do not use out_flags in any way other than testing if (new_flags & out_flags) is 0. This is how PR_Poll (the primary user and hence the de facto specification of the poll method) uses out_flags. Original Document Information Author: Wan Teh Chang Last Updated Date: June 27, 2006 ...
NSS Certificate Download Specification
Data Formats NSS can accept certificates in several formats. In all cases the certificates are X509 version 1, 2, or 3. Binary Formats NSS's certificate loader will recognize several binary formats. They are: DER encoded certificate: This is a single binary DER encoded certificate. PKCS#7 certificate chain: This is a single PKCS#7 SignedData object. The only significant field in the SignedData object is the certificates field, which may contain multiple certificates to be imported together. The contents of the version, digestAlgorithms, contentInfo, crls, and signerInfos fields are ignored. ...
... be the server or CA certificate, and any subsequent certificates will be added as untrusted CA certificates to the local database. ...
Certificate functions
The public functions listed here are used to interact with certificate databases. If documentation is available for a function listed below, the function name is linked to either its MDC wiki page or its entry in the old SSL Reference. The Mozilla Cross Reference (MXR) link for each function provides access to the function definition, prototype definition, and source code references. The NSS version column indicates which versions of NSS support the function. ...
...cumentation is available for a function listed below, the function name is linked to either its MDC wiki page or its entry in the old SSL Reference. The Mozilla Cross Reference (MXR) link for each function provides access to the function definition, prototype definition, and source code references. The NSS version column indicates which versions of NSS support the function. ...
Cryptography functions
The public functions listed here perform cryptographic operations based on the PKCS #11 interface. If documentation is available for a function listed below, the function name is linked to either its MDC wiki page or its entry in the old SSL Reference. The Mozilla Cross Reference (MXR) link for each function provides access to the function definition, prototype definition, and source code references. The NSS version column indicates which versions of NSS support the function. ...
...ation is available for a function listed below, the function name is linked to either its MDC wiki page or its entry in the old SSL Reference. The Mozilla Cross Reference (MXR) link for each function provides access to the function definition, prototype definition, and source code references. The NSS version column indicates which versions of NSS support the function. ...
NSS FAQ
Mozilla › Projects › NSS › FAQ
It provides a complete open-source implementation of the crypto libraries used by Mozilla and other companies in the Firefox browser, AOL Instant Messenger (AIM), server products from Red Hat, and other products. For an overview of NSS, see Overview of NSS. For detailed information on the open-source NSS project, see NSS Project Page. ...
...ols. It works with common Internet standard application protocols (HTTP, POP3, FTP, SMTP, etc.) as well as custom application protocols using TCP/IP. How long does it take to integrate NSS into my application? The integration effort depends on an number of factors, such as developer skill set, application complexity, and the level of security required for your application. NSS includes detailed documentation of the SSL API and sample code that demonstrates basic SSL functionality (setting up an encrypted session, server authentication, and client authentication) to help jump start the integration process. However, there is little or no documentation currently available for the rest of the NSS API. If your application requires sophisticated certificate management, smart card support, or hardware ...
HTTP delegation
P Delegation feature in your NSS-based application, you need to implement several callback functions. Your callback functions might be a full implementation of a HTTP client. Or you might choose to leverage an existing HTTP client library and implement the callback functions as a thin layer that forwards requests from NSS to the HTTP client library. To learn about all the details, please read the documentation contained in the NSS C header files. Look for function SEC_RegisterDefaultHttpClient and all functions having names that start with SEC_Http. To find an example implementation, you may look at bug 111384, which tracks the implementation in Mozilla client applications. Specifying an OCSP proxy The remainder of this document is a short HOWTO. One might expect the API defines a simple function ...
...S is finished providing all details, it will request to initiate the actual network communication (SEC_HttpRequest_TrySendAndReceiveFcn). The application should try to reuse existing network connections associated with the server session object. Once the HTTP response has been obtained from the HTTP server, the function will provide the results in its "out parameters". Please read the source code documentation to learn how to use this API synchronously or asynchronously. Now that we have explained the interaction between NSS, the callback functions and the application, let's look at the steps required by the application to initially register the callbacks. Make sure you have completed the NSS initialization before you attempt to register the callbacks. Look at SEC_HttpClientFcn, which is a (versio...
HTTP delegation
P Delegation feature in your NSS-based application, you need to implement several callback functions. Your callback functions might be a full implementation of a HTTP client. Or you might choose to leverage an existing HTTP client library and implement the callback functions as a thin layer that forwards requests from NSS to the HTTP client library. To learn about all the details, please read the documentation contained in the NSS C header files. Look for function SEC_RegisterDefaultHttpClient and all functions having names that start with SEC_Http. To find an example implementation, you may look at bug 111384, which tracks the implementation in Mozilla client applications. Specifying an OCSP proxy The remainder of this document is a short HOWTO. One might expect the API defines a simple function ...
...S is finished providing all details, it will request to initiate the actual network communication (SEC_HttpRequest_TrySendAndReceiveFcn). The application should try to reuse existing network connections associated with the server session object. Once the HTTP response has been obtained from the HTTP server, the function will provide the results in its "out parameters". Please read the source code documentation to learn how to use this API synchronously or asynchronously. Now that we have explained the interaction between NSS, the callback functions and the application, let's look at the steps required by the application to initially register the callbacks. Make sure you have completed the NSS initialization before you attempt to register the callbacks. Look at SEC_HttpClientFcn, which is a (versio...
Introduction to Network Security Services
...
... ...
JSS
Mozilla › Projects › NSS › JSS
SS project has been relocated! As of April 6, 2018, JSS has been migrated from Mercurial on Mozilla to Git on Github. JSS source should now be checked out from the Github: git clone git@github.com:dogtagpki/jss.git -- OR -- git clone https://github.com/dogtagpki/jss.git All future upstream enquiries to JSS should now use the Pagure Issue Tracker system: https://pagure.io/jss/issues Documentation regarding the JSS project should now be viewed at: http://www.dogtagpki.org/wiki/JSS NOTE: As much of the JSS documentation is sorely out-of-date, updated information will be a work in progress, and many portions of any legacy documentation will be re-written over the course of time. Stay tuned! Legacy JSS information can still be found at: SOURCE: https://hg.mozilla.org/projects...
...1.6 or higher needs to be used. A current limitation to the configured SunPKCS11-NSS bridge configuration is if you add a PKCS#11 module to the NSS database such as for a smartcard, you won't be able to access that smartcard through the SunPKCS11-NSS bridge. If you use JSS, you can easily get lists of modules and tokens that are configured in the NSS DB and freely access all of it. Documentation Before you use JSS, you should have a good understanding of the crypto technologies it uses. You might want to read these documents: Introduction to Public-Key Cryptography. Explains the basic concepts of public-key cryptography that underlie NSS and JSS. Introduction to SSL. Introduces the SSL protocol, including information about cryptographic ciphers supported by SSL ...
NSS_3.12.2_release_notes.html
NSS 3.12.2 Release Notes 2008-10-20 Newsgroup: mozilla.dev.tech.crypto Contents Introduction Distribution Information New in NSS 3.12.2 Bugs Fixed Documentation Compatibility Feedback Introduction Network Security Services (NSS) 3.12.2 is a patch release for NSS 3.12. The bug fixes in NSS 3.12.2 are described in the "Bugs Fixed" section below. NSS 3.12.2 is tri-licensed under the MPL 1.1/GPL 2.0/LGPL 2.1. Distribution Information The CVS tag for the NSS 3.12.2 release is NSS_3_12_2_RTM. NSS 3.12.2 requires NSPR 4.7.1. See the Documentation section for the build instructions. NSS 3.12.2 source and binary distributions are also available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss...
... of kilobytes of useless strings in libPKIX Bug 457984: Enable PKCS11 module logging in optimized builds Bug 458905: Memory leaks in PKIX bridge certificates. Bug 459231: Memory leak in cert fetching - AIA extension. Bug 459248: Support Intel AES extensions. Bug 459359: ForwardBuilderState object is leaked when AIA path incorrect Bug 459481: NSS build problem with GCC 3.4.6 on OS/2 Documentation For a list of the primary NSS documentation pages on mozilla.org, see NSS Documentation. New and revised documents available since the release of NSS 3.11 include the following: Build Instructions for NSS 3.11.4 and above NSS Shared DB Compatibility NSS 3.12.2 shared libraries are backward compatible with all older NSS 3.x shared libraries. A program linked with older NSS 3.x shared...
NSS 3.14.2 release notes
Network Security Services (NSS) 3.14.2 is a patch release for NSS 3.14. The bug fixes in NSS 3.14.2 are described in the "Bugs Fixed" section below. NSS 3.14.2 should be used with NSPR 4.9.5 or newer. The release is available for download from https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_14_2_RTM/src/ For the primary NSS documentation pages please visit /docs/NSS New in NSS 3.14.2 NSS will now make use of the Intel AES-NI and AVX instruction sets for hardware-accelerated AES-GCM on 64-bit Linux systems. Note: the new assembly code requires GNU as version 2.19 or newer. On Red Hat Enterprise Linux 5.x systems, install the binutils220 package and add /usr/libexec/binutils220 to the beginning of your PATH environment variable. Initial manual pages for some NSS comm...
...rated AES-GCM on 64-bit Linux systems. Note: the new assembly code requires GNU as version 2.19 or newer. On Red Hat Enterprise Linux 5.x systems, install the binutils220 package and add /usr/libexec/binutils220 to the beginning of your PATH environment variable. Initial manual pages for some NSS command line tools have been added. They are still under review, and contributions are welcome. The documentation is in the docbook format and can be rendered as HTML and UNIX-style manual pages using an optional build target. New Types: in certt.h cert_pi_useOnlyTrustAnchors in secoidt.h SEC_OID_MS_EXT_KEY_USAGE_CTL_SIGNING Notable Changes in NSS 3.14.2 Bug 805604 - Support for AES-NI and AVX accelerated AES-GCM was contributed by Shay Gueron of Intel. If...
nss tech note4
Pulling certificate extension information out of SSL certificates NSS Technical Note: 4 Note: This document contains code snippets that focus on essential aspects of the task and often do not illustrate all the cleanup that needs to be done. Also, this document does not attempt to be an exhaustive survey of all possible ways to do a certain task; it merely tries to show a certain way. Include these files #include "ssl.h" #include "cert.h" Get the handle of the cert associated with an SSL connection CERTCertificate* cert = SSL_PeerCertificate(PRFileDesc *fd); If SSL client, this will get you the server's cert handle; If SSL server, this will get you the client's cert handle IF client auth i...
...Alloc to allocate buffer for the decoded value, The caller should free up the storage allocated in value->data. ...
FC_Initialize
ibrary parameters string has this format: "configdir='dir' certPrefix='prefix1' keyPrefix='prefix2' secmod='file' flags= " Here are some examples. ...
...Return value FC_Initialize returns the following return codes. CKR_OK: library initialization succeeded. CKR_ARGUMENTS_BAD pInitArgs is NULL. pInitArgs->LibraryParameters is NULL. only some of the lock functions were provided by the application. CKR_CANT_LOCK: the CKF_OS_LOCKING_OK flag is not set in pInitArgs->flags. The NSS cryptograph...
NSS tools : crlutil
Name crlutil -- List, generate, modify, or delete CRLs within the NSS security database file(s) and list, create, modify or delete certificates entries in a particular CRL. Synopsis crlutil [options] [[arguments]] STATUS This documentation is still work in progress. Please contribute to the initial review in Mozilla NSS bug 836477[1] Description The Certificate Revocation List (CRL) Management Tool, crlutil, is a command-line utility that can list, generate, modify, or delete CRLs within the NSS security database file(s) and list, create, modify or delete certificates entries in a particular CRL. The key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database(see certuti...
...modify, or delete CRLs within the NSS security database file(s) and list, create, modify or delete certificates entries in a particular CRL. The key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database(see certutil tool) and continues with certificates expiration or revocation. This document discusses certificate revocation list management. For information on security module database management, see Using the Security Module Database Tool. For information on certificate and key database management, see Using the Certificate Database Tool. To run the Certificate Revocation List Management Tool, type the command crlutil option [arguments] where options and arguments are combinati...
NSS tools : modutil
Please contribute to the initial review in Mozilla NSS bug 836477[1] Description The Security Module Database Tool, modutil, is a command-line utility for managing PKCS #11 module information both within secmod.db files and within hardware tokens. ...
... #11 module to the database using the named JAR file. Use this command with the -installdir and -tempdir arguments. The JAR file uses the NSS PKCS #11 JAR format to identify all the files to be installed, the module's name, the mechanism flags, and the cipher flags, as well as any files to be installed on the target machine, including the PKCS #11 module library file and other files such as documentation. This is covered in the JAR installation file section in the man page, which details the special script needed to perform an installation through a server or with modutil. -list [modulename] Display basic information about the contents of the secmod.db file. Specifying a modulename displays detailed information about a particular module and its slots and tokens. -rawadd Add the modu...
OLD SSL Reference
OLD SSL Reference We are migrating this SSL Reference into the format described in the MDN Style Guide. If you are inclined to help with this migration, your help would be very much appreciated. Upgraded documentation may be found in the Current NSS Reference SSL Reference Newsgroup: mozilla.dev.tech.crypto Writer: Sean Cotter Manager: Wan-Teh Chang Chapter 1 Overview of an SSL Application SSL and related APIs allow compliant applications to configure sockets for authenticated, tamper-proof, and encrypted communications. This chapter introduces some of the basic SSL functions. Chapter 2, "Getting Started With SSL" illustrates their use in sample client and server applications. Initialization Initializing Caches ...
...Additional types are described with the functions that use them or in the header files. Types and Structures CERTCertDBHandle CERTCertificate PK11SlotInfo SECItem SECKEYPrivateKey SECStatus Managing SECI...
sslintro.html
This chapter introduces some of the basic SSL functions. ...
...ient and server applications. An SSL application typically includes five parts: Initialization Configuration Communication Functions Used by Callbacks Cleanup Although the details differ somewhat for client and server applications, the concepts and many of the functions are the same for both. WARNING: Some of the SSL header files provided as part of NSS 2.0 include both public APIs documented in the NSS 2.0 documentation set and private APIs intended for internal use by the NSS implementation of SSL. You should use only the SSL APIs (and related certificate, key, and PKCS #11 APIs) that are described in this document, the SSL Reference. Other APIs that may be exposed in the header files are not supported for application use. Initialization Initialization includes setting up con...
SSL functions
The public functions listed here are used to configure sockets for communication via the SSL and TLS protocols. In addition to the functions listed here, applications that support SSL use some of the Certificate functions, Crypto functions, and Utility functions described below on this page. Other sources of information: The NSS_reference documents the functions most commonly used by applications to support SSL. The NSS home page links to additional SSL documentation. If documentation is available for a function listed below, the function name is linked to either its MDC wiki page or its entry in the old SSL Reference. The Mozilla Cross Reference (DXR) link for each function provides access to the function definition, prototype definition, and source code references. The NSS version...
...entation is available for a function listed below, the function name is linked to either its MDC wiki page or its entry in the old SSL Reference. The Mozilla Cross Reference (DXR) link for each function provides access to the function definition, prototype definition, and source code references. The NSS version column indicates which versions of NSS support the function. ...
Utility functions
The public functions listed here perform initialization tasks and other services. If documentation is available for a function listed below, the function name is linked to either its MDC wiki page or its entry in the old SSL Reference. The Mozilla Cross Reference (MXR) link for each function provides access to the function definition, prototype definition, and source code references. The NSS version column indicates which versions of NSS support the function. ...
...ation is available for a function listed below, the function name is linked to either its MDC wiki page or its entry in the old SSL Reference. The Mozilla Cross Reference (MXR) link for each function provides access to the function definition, prototype definition, and source code references. The NSS version column indicates which versions of NSS support the function. ...
NSS Tools modutil
The tasks associated with security module database management are part of a process that typically also involves managing key databases (key3.db files) and certificate databases (cert8.db files). The key, certificate, and PKCS #11 module management process generally begins with creating the keys and key database necessary to generate and manage certificates and the certificate database. This document discusses security module database management. For information on certificate database and key database management, see Using the Certificate Database Tool. Availability This tool is known to build on Solaris 2.5.1 (SunOS 5.5.1) and Windows NT 4.0. Syntax To run the Security Module Database Tool, type the command modutil option [arguments] where option and arguments are combinations ...
... using the named JAR file. Use this option with the -installdir and -tempdir arguments. The JAR file uses the Netscape Server PKCS #11 JAR format to identify all the files to be installed, the module's name, the mechanism flags, 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 docum...
The Necko HTTP module
References RFC 2616 for the HTTP/1.1 specification. RFC 2617 for the HTTP/1.1 basic and digest authentication specifications. Notes Class Overview This document provides an overview of the classes used to implement the http module. It's meant as a guide to developers wishing to extend the HTTP implementation. Transaction Model This document describes the lifetime of a HTTP transaction, the threads involved, and the relevant objects. Pipelining FAQ This document gives an overview of HTTP/1.1 pipelining by answering some frequently asked questions. Caching FAQ This document gives an overview of how HTTP caching is implemented in necko. It answers some of the common questions concerning what is cached and for how long. HTTP Cache (v2) Describes in detail the API and...
... overview of HTTP/1.1 pipelining by answering some frequently asked questions. Caching FAQ This document gives an overview of how HTTP caching is implemented in necko. It answers some of the common questions concerning what is cached and for how long. HTTP Cache (v2) Describes in detail the API and the implementation details of the content (HTTP, but not only) cache. HTTP Logging This document describes how to enable HTTP logging for various platforms. Original Document Information Last Updated Date: May 12, 2003 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details ...
Necko
etwork library that provides a platform-independent API for several layers of networking, ranging from transport to presentation layers. This API is used in many Mozilla-based client applications (including Firefox) and can be used for writing other networking clients. Currently the library is built as part of the Mozilla distribution. ...
...etworking clients. Currently the library is built as part of the Mozilla distribution. You can get the whole distribution as described in the Build Documentation. Eventually we'd like to move to a binary distribution mechanism for the networking library so that you can build your application that uses this library without having to build Mozilla. Browse our code in its latest state at netwerk/ Documents A necko code walkthrough Necko Architecture Necko multithreading Necko FAQ Necko Interfaces overview The Necko HTTP module Proxies in Necko PAC files Community View Mozilla forums... Mailing list Newsgroup RSS feed ...
How to embed the JavaScript engine
d the MozillaBuild package. Get the SpiderMonkey source code. You can download a source archive or use Mercurial (hg) to pull the SpiderMonkey repository. On Windows, do not install the SpiderMonkey source code under the MSYS root directory (which is usually c:\mozilla-build\msys). Instead use something like c:\mozjs-31.2.0 Compile SpiderMonkey using the build instructions at SpiderMonkey Build Documentation. By default this will build a SpiderMonkey shared library that you will link into your application in a later step. Copy the code example above into a text editor and save the file as helloworld.cpp in the 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 ...
...nName(cx, target, "onClick", argv, &rval); /* Now test rval to see whether we should cancel the event. */ if (rval.isBoolean() && !rval.toBoolean()) CancelEvent(event); Again, I've elided error checking (such as testing for !ok after the call), and I've faked up some C event management routines that emulate the DOM's convention of canceling an event if its handler returns false. Original Document Information Author: Brendan Eich ...
Bytecode Descriptions
Constants Undefined Stack: => undefined Push undefined. Null Stack: => null Push null. False, True Stack: => true/false Push a boolean constant. Int32 Operands: (int32_t val) Stack: => val Push the int32_t immediate operand as an Int32Value. JSOp::Zero, JSOp::One, JSOp::Int8, JSOp::Uint16, and JSOp::Uint24 are all compact encodings for JSOp::Int32. Zero Stack: => 0 Push the number 0. One Stack: => 1 Push the number 1. Int8 Operands: (int8_t val) Stack: => val Push the int8_t immediate operand as an Int32Value. Uint16 Operands: (uint16_t val) Stack: => val Push the uint16_t immediate operand as an Int32Value. ...
...of JSOp::GetElem checks for optimized arguments (see GetElemOptimizedArguments). Example 2: f.apply(this, arguments) is supported; therefore our implementation of Function.prototype.apply checks for optimized arguments (see js::fun_apply), and all JSOp::FunApply implementations must check for cases where f.apply turns out to be any other function (see GuardFunApplyArgumentsOptimization). It's not documented anywhere exactly which opcodes support JS_OPTIMIZED_ARGUMENTS; see the source of AnalyzeArgumentsUsage. Rest Stack: => rest Create and push the rest parameter array for current function call. This must appear only in a script for a function that has a rest parameter. Format: JOF_TYPESET, JOF_IC FunctionThis Stack: => this Determines the this value for current function frame and pushes it ...
Property cache
at obj does not have an own property with the desired name and does not inherit a JSPROP_SHARED or JSPROP_READONLY property with that name from any prototype. It is guaranteed that vword.isSprop(), and vword.toSprop() describes the property that should be added to obj. With regard to property attributes, getters, setters, and so forth, the property cache entry must take into account several rules documented at JS_SetProperty. Sometimes the new property can be created simply by calling JSScope::extend, but there are many special cases and pitfalls to watch out for. When a prototype gains a property that could invalidate an entry of this type, rt->protoHazardShape is bumped, effectively marking all such entries invalid at once. Entry value words For the .vword member of a non-adding property cach...
...d its value is vword.toObject(). This special kind of entry is used only for JOF_CALL instructions and only when the result is a Function. It helps the JIT avoid extra loads and guards when calling methods. Branded scopes exist to support this case. When a property cache entry of this type is created, the scope of the object that contains the property is branded. The "branded scope guarantee" documented above ensures that any changes to function-valued own properties of that object will bump its shape, conservatively invalidating all property cache entries of this type for that object (and JIT code that might inline a call to the function). The JIT uses a fourth kind of PCVal, having pcval.isNull(), internally to indicate that a property lookup missed entirely. But property cache entries a...
SpiderMonkey Internals
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. ...
...) in its Date class. jsfile.cpp, jsfile.h, jsfile.msg Obsolete. Do not use these files. Makefile.in, build.mk Mozilla makefiles. If you're building Gecko or Firefox, the larger build system will use these files. They are also used for current standalone builds. Makefile.ref, rules.mk, config.mk, config/* Obsolete SpiderMonkey standalone makefiles from 1.8 and earlier. See SpiderMonkey Build Documentation. See also jsd ...
JSAPI User Guide
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. ...
...ion to expose some of its own objects and functions to JavaScript code. Browsers expose DOM objects. Your application will expose objects that are relevant for the kind of scripts you want to write. It is up to the application developer to decide what objects and methods are exposed to scripts. Hello world Using the SpiderMonkey library To build SpiderMonkey from source, see SpiderMonkey Build Documentation. Some systems (such as Debian) provide SpiderMonkey as a prebuilt package. Build it from source instead. Your program will be easier to debug. C++ code accesses SpiderMonkey via the JSAPI, by including the header "jsapi.h". An overview of JSAPI functionality follows. For more details, see the JSAPI Reference. The SpiderMonkey universe In order to run any JavaScript code in SpiderMonkey, ...
Web Replay
ed to as the child process -- is managed via a separate middleman content process. The child process is extended so that it can communicate with the middleman, using a special bidirectional channel and messages separate from IPDL state. Middleman process The middleman is the same as a normal content process, except that it spawns and communicates with the child process, and avoids creating any documents itself. Using the middleman provides the following advantages: IPDL communication is greatly simplified. The chrome and middleman processes communicate using the standard browser protocols (PContent, PBrowser, etc.) and implementations for their actors, while the middleman and child processes communicate with their own channel and messages, which is tuned to the demands of the recording/rep...
...ernel. This project records all behavior outside of system library calls which the process makes, with exceptions carved out for the allowed non-determinism and for draw targets. Microsoft's and WebKit's projects record a smaller subset of the browser's behavior. This project is at a good point on this spectrum. Compared to a higher level project, this is able to operate on stable, thoroughly documented library APIs. By focusing on intercepting these APIs, browser instrumentation, recording overhead, and the maintenance burden going forward are all minimized. Compared to a lower level project, this is able to tolerate more non-determinism. All code whose behavior is recorded is compiled into Gecko (rather than being part of immutable, usually closed-source libraries) and can be lightly modi...
WebReplayRoadmap
Time Travel Features More features are planned for the timeline, as described below. ...
...otential features for the Firefox developer tools that are based on Web Replay, along with their UI. The low level, yet flexible architecture (described here) provides an extremely powerful platform for implementing debugging and analysis features. We would like to use Web Replay to radically improve not just the debugging experience but the entire web development experience. To that end, this document will be revised over time as we find new and better ways of helping developers. Time Travel Features More features are planned for the timeline, as described below. Retroactive Console Logging Console logging is one of the primary tools most developers use to debug a page. Seeing messages in the console provides a simple and intuitive view into the order in which events have happened. Witho...
Secure Development Guidelines
is exploitable (in some browsers) with a simple request such as: http://www.victim.com?something=<SCRIPT>alert('Oops')</...
...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 &amp; -> & &lt; -> < &gt; -> > &quot; -> " &apos; -> ' URL encoding % encoding Java/VBs...
A Web PKI x509 certificate primer
In general, x509 certificates bind a signature to a validity period, a public key, a subject, an issuer, and a set of extensions. The extensions define extra properties of the certificate such as extra attributes of the certificate or constraints on the use of the certificate. ...
... issue that is not commonly known is that the x509 trust graph is not a forest (a bunch of trees where each root is a trusted root) but a cyclic graph, where the same key/issuer can be a root or an intermediate for another root in the browsers key store (when roots create intermediates for each other it is called cross-signing). Extensions While RFC 5280 defines 16 extensions for webpki in this document we will be describing the six extensions we considered critical for understanding. Certificates can have other extensions not described on RFC 5280, but that is out of the scope of this document. Extensions can be marked as critical or non-critical, conforming certificate verification libraries should stop processing verification when encountering a critical extension that they do not understand ...
Browser security
An important aspect of developing code for any browser, including Firefox, as well as any Web-oriented project, is its security. These articles provide important guides and references to ensuring the code you write is secure, including both design recommendations and testing guidelines. A Web PKI x509 certificate primerX.509 (in this document referred as x509) is an ITU standard to describe certificates. ...
...esting guidelines. A Web PKI x509 certificate primerX.509 (in this document referred as x509) is an ITU standard to describe certificates. This article provides an overview of what these are and how they work.Exploitable crashesThis article will help you determine if a crash is exploitable, find crashes which are exploitable, and to fix exploitable crashes.Handling Mozilla Security BugsThis document describes how the new security organizational structure will work, and how security-related Mozilla bug reports will be handled.Pinning violation reportsIf a site makes use of key pinning, and your browser sees a certificate chain for that site which does not match the pin, Firefox will reject the connection and display an error page. Secure Development GuidelinesThe following content will li...
AT APIs Support
But in the meantime it more up-to-date and contains more details than existed analogues for AT-SPI and MSAA This documentation explains how makers of screen readers, voice dictation packages, onscreen keyboards, 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. ...
...ux Desktop, Microsoft Windows and Macintosh users to rival programs like FrontPage and Dreamweaver. Open Komodo - platform for building developer environments Miro - a free, open source internet tv and video player Any XulRunner application (Songbird media player, etc.) Extensions to other XUL apps (e.g. Firefox extensions) Gecko Version For Firefox and all other Gecko-based products: this documentation applies to up-to-date product builds based on Gecko 1.9.2 -- currently not available on official releases. However most of described features are supported starting from Gecko 1.9.0 (Firefox 3.0). However it's preferable to grab the current build of Firefox or any other Gecko-based product to be up to dated: Firefox recent builds Thunderbird recent builds Seamonkey recent builds Deter...
Embedded Dialog API
alogs and alerts posed by Gecko do reside in a single generic component, nsIPromptService (nsIPromptService). An MFC example is implemented in PromptService.cpp. A PowerPlant example is implemented in PromptService.cpp. (TestGtkEmbed doesn't override PromptService; it uses the default dialogs.) Both are source for a library set up as a Mozilla component and factory. (Note to self: is there decent documentation on writing factories or components? I can't find any.) Both contain implementations of nsIPromptService as native dialogs. The replacement library should be installed during application initialization. The default dialog-posing library is a component (PromptService for instance is part of the embedding component), registered as a component during Gecko initialization (by NS_InitEmbedding). (...
... API as consistent as possible, we'd like to impose a few coding conventions on these dialog-posing interfaces. ...
Places utilities for JavaScript
orURI(nsIURI aURI, object aAnnos); void setAnnotationsForURI(int aItemId, object aAnnos); getViewForNode(nsIDOMNode aNode); void markPageAsTyped(string aURL); void markPageAsFollowedBookmark(string aURL); boolean checkURLSecurity(nsINavHistoryResultNode aURINode); string getQueryStringForFolder(int aFolderId); string getDescriptionFromDocument(nsIDOMDocument doc); string setPostDataForBookmark(int aBoomarkId, string aPostData); string getPostDataForBookmark(int aBoomarkId); array string getURLAndPostDataForKeyword(string aKeyword); string getItemDescription(int aItemId); nsINavHistoryResultNode getMostRecentBookmarkForURI(nsIURI aURI); nsINavHistoryResultNode getMostRecentFolderForF...
...de) Parameters aURINode a URI node Return type Return true if it's safe to open the node in the browser, false otherwise. getQueryStringForFolder() Helper for getting a serialized Places query for a particular folder. getQueryStringForFolder(int aFolderId) Parameters aFolderId The folder id to get a query for. Return type Return string serialized place URI getDescriptionFromDocument() Get the description associated with a document, as specified in a <META> element. getDescriptionFromDocument(doc) Parameters doc A DOM Document to get a description for Return type Returns a description string if a META element was discovered with a "description" or "httpequiv" attribute, empty string otherwise. setPostDataForBookmark() Set the POST data associated with a bookmark...
Places
ex querying to make handling the places the user goes easier and more convenient. It also includes new features including favicon storage and the ability to annotate pages with arbitrary information. It also introduces new user interfaces for managing all this information; see Places on the Mozilla wiki. Places stores its data in an SQLite database using the mozStorage interfaces. Documentation Places migration guide Migrating existing code to use the Places API. Manipulating bookmarks using Places Examples for how to work with bookmarks using the Places API. Using the Places tagging service How to use the tagging service. Using the Places history service How to access history information using the Places API. Using the Places favi...
...g 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" algorithm The algorithm behind the Places location bar (sometimes called the "awesomebar"). ...
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...
..._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 backslashes within the string. The third parameter for open() and create() is the access mode. It is specified as a bitwise combination of flags defined on the interface. You can read the interface documentation for a full explanation, but we will show only the three most commonly used modes here: ACCESS_READ -- For reading values, enumerating keys, and receiving notifications ACCESS_WRITE -- For setting values and creating sub keys ACCESS_ALL -- Access for all operations In addition to open() and create(), there are the openChild() and createChild() methods. You can call these methods on an ...
Aggregating the In-Memory Datasource
do_QueryInterface(mInner); rv = ds->Assert(/* something useful here */); // etc... return NS_OK; } It may be tempting to keep a pointer to the aggregate's nsIRDFDataSource in a member variable, butyou can't do that. Why? Because if you did, you'd hold a circular reference that would never unwind. Notes Describing all of the vagaries of XPCOM aggregation is beyond the scope of this document. The basic idea is to overload QueryInterface(), allowing it to return adelegate object that supports the interface. There is some trickery involved on the delegate's part to ensure that reference counting is done sanely, and that the reflexive, symmetric, and transitive properties of QueryInterface() are preserved. If you're really interested, I'd recommend reading about it in a COM book. For m...
... adelegate object that supports the interface. There is some trickery involved on the delegate's part to ensure that reference counting is done sanely, and that the reflexive, symmetric, and transitive properties of QueryInterface() are preserved. If you're really interested, I'd recommend reading about it in a COM book. For more information on writing a datasource, see the RDF Datasource How-To document. You could also forward other interfaces to the mInner that youknow it can support; however, this is extremely risky. It's risky because another implementation of the same object mightnot support those interfaces. Then the QueryInterface() will be forwarded back to you, and we'll recurse off to infinity (and beyond!... Interwiki Language Links ...
Finishing the Component
blocking any site, the component would simply log all URLs that are loaded. In any case, the process to make the XPCOM component is the same. The method that handles the check before page loading and the only method we care about in our own implementation of nsIContentPolicy is ShouldLoad(). The other method on the nsIContentPolicy interface is for blocking processing of specific elements in a document, but our policy is more restrictive: if the URL isn't on the white list, the entire page should be blocked. In the WebLock component, the ShouldLoad method looks like this: NS_IMETHODIMP WebLock::ShouldLoad(PRInt32 contentType, nsIURI *contentLocation, nsISupports *ctxt, nsIDOMWindow *window, ...
...nto 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 derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. ...
Preface
vior. Although, XPCOM can be used in many environments which are unrelated to web browsing, XPCOM's main client is Gecko, an open source, standards compliant, embeddable web browser, where it's easiest and most practical to illustrate XPCOM's functionality. A full description of the component in this tutorial can be found in the What We'll Be Working On section of the tutorial. Despite what old documentation says, XPCOM should not be used to make NPAPI plugins scriptable. Starting with Gecko 1.7.5 (Firefox 1.0) a special NPAPI extension for scriptability is supported, see Scripting plugins. Organization of the Tutorial The following list provides an overview of the steps that we will take to build an XPCOM component called WebLock, which provides site blocking functionality to Gecko-based bro...
...c Flett for technical reviews. A special thanks goes to Darin Fisher for his very acute observations, close reading, and attention to detail. Next >> 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 derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. ...
Starting WebLock
ces and clients. The next section shows the interface of the WebLock component, iWebLock, in XPIDL. Once the interface has been described in the XPIDL language, the interface file can be used to generate the header files needed for the implementation code, the binary type library files that let you use the interface of the WebLock component from JavaScript, and even broken linkjavadoc 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 bridg...
...d to write the linked list to disk and release the memory occupied by the linked list. We leave these as exercises for the reader. << 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 derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. ...
Using XPCOM Utilities to Make Things Easier
d rv will be set to a specific error code corresponding to the reason for the failure. In this construct, the result code rv is an optional parameter. If you don't care what the error code is, you can simply drop it from the function call. From this point on, we'll be using nsCOMPtrs as much as possible in WebLock. For a complete listing of smart pointer functionality, see mozilla.org's nsCOMPtr documentationXXX this should be in devmo. Note: other-parts This section discusses the main parameters of this structure. For a complete listing of all available options you can look at the complete reference in the XPCOM API Reference. Note: nsISupports-warning Note that NS_DECL_ISUPPORTS doesn't obey the general rule in which every interface has a declaration macro of the form NS_DECL_INTERFACENAME,...
...embedded nulls. Note: other-string-classes There are other abstract string classes, but they are outside the scope of this book. << 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 derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. ...
Creating XPCOM components
Finishing the Component Using Frozen Interfaces Copying Interfaces Into Your Build Environment Implementing the nsIContentPolicy Interface Receiving Notifications Implementing the nsIContentPolicy Uniform Resource Locators Checking the White List Creating nsIURI Objects Building the WebLock UI User Interface Package List Client Code Overview XUL The XUL Document The Locking UI Site Adding UI weblock.xul Overlaying New User Interface Into Mozilla webLockOverlay.xul Other Resources weblock.css Image Resources Packaging WebLock Component Installation Overview Archiving Resources The WebLock Installation Script The WebLock Trigger Script Distributing Your Component Appendix A - Setting up the Gecko SDK Downloading ...
...s Project A Makefile for Unix Appendix B - Resources WebLock Resources Gecko Resources XPCOM Resources General Development Resources Next >> 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 derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. ...
Detailed XPCOM hashtable guide
There are many different types of hash functions. Mozilla has tuned a good general-purpose hash algorithm for strings and nsID. Original Document Information Author(s): Benjamin Smedberg <benjamin@smedbergs.us> ...
...string nsAString HashString() nsACString nsID& nsIDHashKey::HashKey() Writing a good hash function is well beyond the scope of this document, and has been discussed extensively in computer-science circles for many years. There are many different types of hash functions. Mozilla has tuned a good general-purpose hash algorithm for strings and nsID. Original Document Information Author(s): Benjamin Smedberg <benjamin@smedbergs.us> ...
Components.utils.evalInWindow
lies on XrayWrappers to wrap the returned content, otherwise the result is structured-cloned. This does impose some restrictions on the sorts of things that can be returned: in particular, the result can't contain any functions, because functions can't be structured-cloned. ...
...rayWrappers to wrap the returned content, otherwise the result is structured-cloned. This does impose some restrictions on the sorts of things that can be returned: in particular, the result can't contain any functions, because functions can't be structured-cloned. ...
XPCShell Reference
) print() is useful to print something to the screen. It dumps whatever is passed to the screen, putting spaces between arguments 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 argumen...
...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 Author: David Bradley <dbradley@netscape.com> Last Updated Date: 17 March 2003 Copyright Information: Portions of this content are (C) 1998-2008 by individual mozilla.org contributors; content available under a Creative Commons license. ...
IAccessibleText
the data depends on how the server manages the life cycle of its objects. Also, note that the server may have different life cycle management strategies for controls depending on whether or not a control manages its children. Lists, trees, and tables can have a large number of children and thus it's possible that the child objects for those controls would only be created as needed. Servers should document their life cycle strategy as this will be of interest to assistive technology or script engines accessing data out of process or from other threads. Servers only need to save the last inserted block of text() and a scope of the entire application is adequate. [propget] HRESULT newText( [out] IA2TextSegment newText ); Parameters newText The text() that was just inserted. Return value S_FALSE ...
...the data depends on how the server manages the life cycle of its objects. Also, note that the server may have different life cycle management strategies for controls depending on whether or not a control manages its children. Lists, trees, and tables can have a large number of children and thus it's possible that the child objects for those controls would only be created as needed. Servers should document their life cycle strategy as this will be of interest to assistive technology or script engines accessing data out of process or from other threads. Servers only need to save the last removed block of text() and a scope of the entire application is adequate. [propget] HRESULT oldText( [out] IA2TextSegment oldText ); Parameters oldText The text() that was just removed. Return value S_FALSE if...
inIDOMUtils
the element, in ascending order of weight. getParentForNode() Returns the parent of the specified node. nsIDOMNode getParentForNode( in nsIDOMNode aNode, in boolean aShowingAnonymousContent ); Parameters aNode The node to return the parent of. aShowingAnonymousContent Whether you are interested in the XBL flattened tree. Return value Returns the parent of a node. The parent of a document node is the frame/iframe containing that document. If you have requested anonymous content and the element's parent has an XBL binding then the element containing the insertion point is returned instead. getRuleLine() Returns the line number of the specified CSS style rule in its source file. unsigned long getRuleLine( in nsIDOMCSSStyleRule aRule ); Parameters aRule The style rule to r...
... style rule in its source file. unsigned long getRuleColumn( in nsIDOMCSSStyleRule aRule ); Parameters aRule The style rule to retrieve the column number of. Return value The column number of the style rule; the URL of the rule can be obtained from its parent style sheet object. getUsedFontFaces() Returns a list of the fonts specified using @font-face in the specified portion of the document. nsIDOMFontFaceList getUsedFontFaces( in nsIDOMRange aRange ); Parameters aRange The DOM range to retrieve the font faces of. Return value An nsIDOMFontFaceList object listing all the font faces used by the text in the range. isIgnorableWhitespace() Determines if the specified text node contains only ignorable whitespace characters. boolean isIgnorableWhitespace( in nsIDOMCharact...
nsIAccessNode
ng pseudoElt, in DOMString propertyName); void scrollTo(in unsigned long aScrollType); void scrollToPoint(in unsigned long aCoordinateType, in long aX, in long aY); Attributes Note: Attempting to access the attributes of a node that is unattached from the accessible tree will result in an exception - NS_ERROR_FAILURE. Attribute Type Description document nsIAccessibleDocument The document accessible that this access node resides in. Read only. Note: Renamed from accessibleDocument in Gecko 2.0 DOMNode Node The DOM node this nsIAccessNode is associated with. Read only. firstChildNode nsIAccessNode The first nsIAccessNode child. Read only. Obsolete since Gecko 2.0 innerHTML DOMString The innerHTML ...
...o 2.0 ownerWindow voidPtr The OS window handle for the window this node is being displayed in. Read only. Native code only! Obsolete since Gecko 8.0 parentNode nsIAccessNode The parent nsIAccessNode. Read only. Obsolete since Gecko 2.0 previousSiblingNode nsIAccessNode The previous nsIAccessNode sibling. Read only. Obsolete since Gecko 2.0 rootDocument nsIAccessibleDocument The root document accessible that this access node resides in. Read only. uniqueID voidPtr A unique ID calculated for this DOM node, for the purposes of caching and referencing this object. Read only. Native code only! Methods getChildNodeAt() Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Get t...
nsIAccessibilityService
accessible/public/nsIAccessibilityService.idlScriptable Please add a summary to this article. ...
... accessible/public/nsIAccessibilityService.idlScriptable Please add a summary to this article. ...
nsIAccessibleProvider
e representing the type of accessible object. See constants for details. Read only. Constants Common use Constants Constant Value Description NoAccessible 0 Do not create an accessible for this object This is useful if an ancestor binding already implements nsIAccessibleProvider, but no accessible is desired for the inheriting binding. OuterDoc 0x00000001 For elements that spawn a new document. For example now it is used by <xul:iframe>, <xul:browser> and <xul:editor>. XUL Controls Constants Constant Value Description XULAlert 0x00001001 XULButton 0x00001002 XULCheckbox 0x00001003 XULColorPicker 0x00001004 XULColorPickerTile 0x00001005 XULCombobox 0x00001006 XULDropmarker 0x00001007 XULGroupbox 0x00001008 XULImage 0x00001009 XULLink 0x0000100...
...nput 0x00002004 Used for input and textarea elements. XFormsInputBoolean 0x00002005 Used for input[xsd:boolean] element. XFormsInputDate 0x00002006 Used for input[xsd:date] element. XFormsSecret 0x00002007 Used for secret element. XFormsSliderRange 0x00002008 Used for range element represented by slider. XFormsSelect 0x00002009 Used for select and select1 that are implemented using host document's native widget. For example, a select1 in a xhtml document may be represented by the native html control html:select. XFormsChoices 0x00002010 Used for xforms choices element. XFormsSelectFull 0x00002011 Used for xforms full select/select1 elements that may be represented by group of checkboxes and radiogroup. XFormsItemCheckgroup 0x00002012 Used for xforms item element that is used inside...
nsICachingChannel
a. If not specified, data will be placed in "HTTP-offline". offlineCacheToken nsISupports The same as cacheToken but accessing the offline app cache token if there is any. Exceptions thrown NS_ERROR_NOT_AVAILABLE When there is not offline cache token. Constants Constant Value Description LOAD_NO_NETWORK_IO 1 << 26 This load flag inhibits fetching from the net. An error of NS_ERROR_DOCUMENT_NOT_CACHED will be sent to the listener's onStopRequest if network IO is necessary to complete the request. This flag can be used to find out whether fetching this URL would cause validation of the cache entry via the network. Combining this flag with LOAD_BYPASS_LOCAL_CACHE will cause all loads to fail. This flag differs from LOAD_ONLY_FROM_CACHE in that this flag fails the load if validation is...
...D_BYPASS_CACHE, it does not force an end-to-end load (That is, it does not affect proxy caches). LOAD_BYPASS_LOCAL_CACHE_IF_BUSY 1 << 29 This load flag causes the local cache to be skipped if the request would otherwise block waiting to access the cache. LOAD_ONLY_FROM_CACHE 1 << 30 This load flag inhibits fetching from the net if the data in the cache has been evicted. An error of NS_ERROR_DOCUMENT_NOT_CACHED will be sent to the listener's onStopRequest in this case. This flag is set automatically when the application is offline. LOAD_ONLY_IF_MODIFIED 1 << 31 This load flag controls what happens when a document would be loaded from the cache to satisfy a call to AsyncOpen. If this attribute is set to true, then the document will not be loaded from the cache. A stream listener can check i...
nsICharsetResolver
s aClosure); Methods notifyResolvedCharset() Some implementations may request that they be notified when the charset is actually detected. void notifyResolvedCharset( in ACString charset, in nsISupports closure ); Parameters charset The detected charset. closure The closure returned by requestCharset(). requestCharset() Called to resolve the charset that should be used for parsing the document being loaded from aChannel. If the charset cannot be resolved, but the implementation of nsICharsetResolver wants to be notified of the final resolved charset when one is available, it can set aWantCharset to true. If this is done, the caller of requestCharset is responsible for calling notifyResolvedCharset() and passing it the final resolved charset and the closure that requestCharset set. ACSt...
...antCharset to true. If this is done, the caller of requestCharset is responsible for calling notifyResolvedCharset() and passing it the final resolved charset and the closure that requestCharset set. ACString requestCharset( in nsIWebNavigation aWebNavigation, in nsIChannel aChannel, out boolean aWantCharset, out nsISupports aClosure ); Parameters aWebNavigation The nsIWebNavigation the document is being loaded in. May be null. aChannel The channel the document is coming in from. aWantCharset Gets set to true if notifyResolvedCharset() should be called with the given aClosure object. aClosure A resulting object which should be passed to notifyResolvedCharset() if aWantCharset is set to true. Return value The resolved charset, or an empty string if no charset could be determined. ...
nsIDOMEvent
Inherits from: nsISupports Last changed in Gecko 16.0 (Firefox 16.0 / Thunderbird 16.0 / SeaMonkey 2.13) Note: As of Gecko 16.0, the nsIPrivateDOMEvent interface was merged into this interface. Everything marked as Gecko 16.0 was previously available in that interface. See bug 761613. ...
...idelines GetInternalNSEvent() nsEventPtr GetInternalNSEvent(); Parameters None. Return value getPreventDefault() Note: Use the defaultPrevented attribute instead. This method will be removed in future releases, see bug 691151. boolean getPreventDefault(); Parameters None. Return value initEvent() This method is used to initialize the value of an Event created through the DocumentEvent interface. This method may only be called before the Event has been dispatched via the dispatchEvent method, though it may be called multiple times during that phase if necessary. If called multiple times the final invocation takes precedence. If called from a subclass of Event interface only the values specified in the initEvent method are modified, all other attributes are left unchanged. ...
nsIDOMEventGroup
dom/interfaces/events/nsIDOMEventGroup.idlScriptable This interface is the interface implemented by all event targets in the Document Object Model. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview boolean isSameEventGroup(in nsIDOMEventGroup other); Methods isSameEventGroup() Reports whether or not another event group is the same as this one. boolean isSameEventGroup( in nsIDOMEventGroup other ); Parameters other Instance of nsIDOMEventGroup object to compare against. ...
...ecko 1.7 Method overview boolean isSameEventGroup(in nsIDOMEventGroup other); Methods isSameEventGroup() Reports whether or not another event group is the same as this one. boolean isSameEventGroup( in nsIDOMEventGroup other ); Parameters other Instance of nsIDOMEventGroup object to compare against. Return value Returns true if the two objects are the same, otherwise false. See also Document Object Model (DOM) Level 3 Events Specification ...
nsIDOMSimpleGestureEvent
dom/interfaces/events/nsIDOMSimpleGestureEvent.idlScriptable This interface describes a mouse or trackpad gesture event. 1.0 66 Introduced Gecko 1.9.1 Inherits from: nsIDOMMouseEvent Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) The nsIDOMSimpleGestureEvent interface is the datatype for all Mozilla-specific simple gesture events in the Document Object Model. The following events are generated: MozSwipeGesture - Generated when the user completes a swipe across across the input device. MozMagnifyGestureStart - Generated when the user begins the magnify ("pinch") gesture. The "delta" value represents the initial movement. MozMagnifyGestureUpdate - Generated periodically while the user is continuing the magnify ("pinch") gesture. The "d...
...r rotation events (where positive values indicate clockwise rotation and negative values indicate counter-clockwise rotation). For magnify gestures, the units are implementation-specific; however, positive values indicate zooming in, and negative values indicate zooming out. Read only. Note: On Mac OS X, the units used for magnification gestures by the underlying operating system API are not documented at this time; typical values appear to be in the range 0.0 to 100.0, but currently you can only rely on the value being either positive or negative. On Windows, the units indicate the difference between the previous and current width between the two touch points, in pixels. direction unsigned long The direction in which the gesture moved. See Direction constants and Rotation ...
nsIDOMStorageManager
All data owned by a domain with the "offline-app" permission is removed from the database. void clearOfflineApps(); Parameters None. getLocalStorageForPrincipal() Returns the instance of the localStorage object for aURI's origin. This is used to ensure that only one local stor...
...s. All data owned by a domain with the "offline-app" permission is removed from the database. void clearOfflineApps(); Parameters None. getLocalStorageForPrincipal() Returns the instance of the localStorage object for aURI's origin. This is used to ensure that only one local storage area exists for a given origin. nsIDOMStorage getLocalStorageForPrincipal( nsIPrincipal aPrincipal, DOMString aDocumentURI ); Parameters aPrincipal The principal for which to return the local storage object. aDocumentURI The document's URI. Return value The local storage object for the specified principal. getUsage() Returns the amount of disk space used by a domain. Usage is checked against the domain of the page that set the key (the owner domain), not the domain of the storage object. long getUsage( AStri...
nsIEditorMailSupport
ertHTML); nsIDOMNode insertAsQuotation(in AString aQuotedText); void insertTextWithQuotations(in DOMString aStringToInsert); void pasteAsCitedQuotation(in AString aCitation, in long aSelectionType); void pasteAsQuotation(in long aSelectionType); void rewrap(in boolean aRespectNewlines); void stripCites(); Methods getEmbeddedObjects() Get a list of IMG and OBJECT tags in the current document. nsISupportsArray getEmbeddedObjects(); Parameters None. Return value An nsISupportsArray containing the IMG and OBJECT tags of the current document. insertAsCitedQuotation() Insert a string as quoted text (whose representation is dependent on the editor type), replacing the selected text (if any), including, if possible, a "cite" attribute. nsIDOMNode insertAsCitedQuotation( in AString aQuote...
... aCitation The "mid" URL of the source message. aSelectionType Text or html? pasteAsQuotation() Paste the text in the OS clipboard at the cursor position, as a quotation (whose representation is dependent on the editor type), replacing the selected text (if any). void pasteAsQuotation( in long aSelectionType ); Parameters aSelectionType Text or html? rewrap() Rewrap the selected part of the document, re-quoting if necessary. void rewrap( in boolean aRespectNewlines ); Parameters aRespectNewlines Try to maintain newlines in the original? stripCites() Strip any citations in the selected part of the document. void stripCites(); Parameters None. ...
nsIFeedProgressListener
/ SeaMonkey 1.0) Method overview void handleEntry(in nsIFeedEntry entry, in nsIFeedResult result); void handleFeedAtFirstEntry(in nsIFeedResult result); void handleStartFeed(in nsIFeedResult result); void reportError(in AString errorText, in long lineNumber, in boolean bozo); Methods handleEntry() Called after each entry or item is processed. If the document is a standalone item or entry, the HandleFeedAtFirstEntry() method will not already have been called, and the received nsIFeedEntry will have a null parent value. void handleEntry( in nsIFeedEntry entry, in nsIFeedResult result ); Parameters entry Pointer to an nsIFeedEntry containing information about the entry that was just processed. result Pointer to an nsIFeedResult containing t...
...will never be called. void handleFeedAtFirstEntry( in nsIFeedResult result ); Parameters result An nsIFeedResult describing the feed at the point at which the first entry is found, but before processing it. handleStartFeed() Called as soon as a reasonable start to a feed is detected; this lets your code know that the feed does appear to be an actual feed rather than some other sort of document. void handleStartFeed( in nsIFeedResult result ); Parameters result An nsIFeedResult describing the current state of the feed at the moment parsing begins. reportError() Called by the feed processor when a fatal XML parsing error occurs, or if the document isn't a feed. void reportError( in AString errorText, in long lineNumber, in boolean bozo ); Parameters errorText A s...
nsIGlobalHistory3
idlScriptable This interface provides information about global history to Gecko. 1.0 66 Introduced Gecko 1.8 Obsolete Gecko 9.0 Inherits from: nsIGlobalHistory2 Last changed in Gecko 1.9 (Firefox 3) This interface was originally created as part of nsIGlobalHistory2, but was split off during the transition to Places. Method overview void addDocumentRedirect(in nsIChannel aOldChannel, in nsIChannel aNewChannel, in PRInt32 aFlags, in boolean aTopLevel); unsigned long getURIGeckoFlags(in nsIURI aURI); void setURIGeckoFlags(in nsIURI aURI, in unsigned long aFlags); Methods addDocumentRedirect() Notifies the history system that the page loading via aOldChannel redirected to aNewChannel. Implementations s...
...ct pages. The other params to this function are the same as those for nsIChannelEventSink.OnChannelRedirect(). Implementors who wish to implement this interface but rely on nsIGlobalHistory2.addURI() for redirect processing may throw NS_ERROR_NOT_IMPLEMENTED from this method. If they do so, then callers must call nsIGlobalHistory2.addURI() upon getting the NS_ERROR_NOT_IMPLEMENTED result. void addDocumentRedirect( in nsIChannel aOldChannel, in nsIChannel aNewChannel, in PRInt32 aFlags, in boolean aTopLevel ); Parameters aOldChannel aNewChannel aFlags Flags to add. These are defined by the history that is implementing this interface. aTopLevel Whether the URI is loaded in a top-level window. If false, the load is in a subframe. ...
nsIHttpChannel
rrer, even when downgrading from https to http Attributes Attribute Type Description allowPipelining boolean This attribute is a hint to the channel to indicate whether or not the underlying HTTP transaction should be allowed to be pipelined with other transactions. This should be set to false, for example, if the application knows that the corresponding document is likely to be very large. This attribute is true by default, though other factors may prevent pipelining. This attribute may only be set before the channel is opened. Exceptions thrown NS_ERROR_FAILURE If set after the channel has been opened. redirectionLimit unsigned long This attribute specifies the number of redirects this channel i...
... ACString Set or get the HTTP request method (default is "GET"). Setter is case insensitive; getter returns an uppercase string. This attribute may only be set before the channel is opened. Note: The data for a "POST" or "PUT" request can be configured via nsIUploadChannel. However, after setting the upload data, it may be necessary to set the request method explicitly. The documentation for nsIUploadChannel has further details. Exceptions thrown NS_ERROR_IN_PROGRESS If set after the channel has been opened. requestSucceeded boolean Returns true if the HTTP response code indicates success. The value of nsIRequest.status() will be NS_OK even when processing a 404 File Not Found response because such a response may include...
nsIMessenger
void launchExternalURL(in ACString aURL); boolean canUndo(); boolean canRedo(); unsigned long getUndoTransactionType(); unsigned long getRedoTransactionType(); void undo(in nsIMsgWindow msgWindow); void redo(in nsIMsgWindow msgWindow); void sendUnsentMessages(in nsIMsgIdentity aIdentity, in nsIMsgWindow aMsgWindow); void setDocumentCharset(in ACString characterSet); void saveAs(in ACString aURI, in boolean aAsFile, in nsIMsgIdentity aIdentity, in AString aMsgFilename); void openAttachment(in ACString contentTpe, in ACString url, in ACString displayName, in ACString messageUri, in boolean isExternalAttachment); void saveAttachment(in ACString contentTpe, in ACString url, in ACString displayName, in ...
...indow The nsIMsgWindow to perform the redo transaction on. sendUnsentMessages() Creates a nsIMsgSendLater instance and sends all messages for the given identity. void sendUnsentMessages(in nsIMsgIdentity aIdentity, in nsIMsgWindow aMsgWindow); Parameters aIdentity The nsIMsgIdentity to send messages for. aMsgWindow The nsIMsgWindow to get messages from. setDocumentCharset() Redisplay the currently selected message (if any) using the given character set. void setDocumentCharset(in ACString characterSet); Parameters characterSet The character set to use. saveAs() Save the URL given. void saveAs(in ACString aURI, in boolean aAsFile, in nsIMsgIdentity aIdentity, in AString aMsgFilename); Parameters aURI ...
nsIMicrosummaryService
I); nsISimpleEnumerator getBookmarks(); nsIMicrosummaryGenerator getGenerator(in nsIURI generatorURI); nsIMicrosummarySet getMicrosummaries(in nsIURI pageURI, in long long bookmarkID); nsIMicrosummary getMicrosummary(in long long bookmarkID); boolean hasMicrosummary(in long long bookmarkID); nsIMicrosummaryGenerator installGenerator(in nsIDOMDocument xmlDefinition); boolean isMicrosummary(in long long bookmarkID, in nsIMicrosummary microsummary); nsIMicrosummary refreshMicrosummary(in long long bookmarkID); void removeMicrosummary(in long long bookmarkID); void setMicrosummary(in long long bookmarkID, in nsIMicrosummary microsummary); Methods addGenerator() Install the microsummary generator from the ...
...microsummary. boolean hasMicrosummary( in long long bookmarkID ); Parameters bookmarkID The bookmark for which to set the current microsummary. Return value Returns a boolean representing whether or not the given bookmark has a current microsummary. installGenerator() Install the microsummary generator in the given XML definition. nsIMicrosummaryGenerator installGenerator( in nsIDOMDocument xmlDefinition ); Parameters xmlDefinition An nsIDOMDocument XML document defining the generator. Return value Returns the nsIMicrosummaryGenerator that was installed. isMicrosummary() Reports whether or not the given microsummary is the current microsummary for the given bookmark. boolean isMicrosummary( in long long bookmarkID, in nsIMicrosummary microsummary ); Parameters b...
nsIPrincipal
name for the certificate. This pertains to the certificate authority organization. Throws if there is no certificate associated with this principal. Obsolete since Gecko 1.8 csp nsIContentSecurityPolicy A Content Security Policy associated with this principal. Native code only! domain nsIURI The domain URI to which this principal pertains. This is congruent with HTMLDocument.domain, and may be null. Setting this has no effect on the URI. Native code only! fingerprint AUTF8String The fingerprint ID of this principal's certificate. Throws if there is no certificate associated with this principal. Read only. hasCertificate boolean Whether this principal is associated with a certificate. Read only. hashValue unsigned long Ret...
...ificate. This may well not be a string that would mean much to a typical user on its own (e.g. it may have a number of different names all concatenated together with some information on what they mean in between). Throws if there is no certificate associated with this principal. Read only. URI nsIURI The codebase URI to which this principal pertains. This is generally the document URI. Read only. Note: This wasn't accessible by scripts prior to Gecko 2.0. Constants Principal capability constants These values indicate the capabilities of a principal. The order is significant; if an operation is performed on a set of capabilities, the minimum is computed. Constant Value Description ENABLE_DENIED 1 ENABLE_UNKNOWN ...
nsIProtocolHandler
nd 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" loads that would replace the document (such as a meta refresh, certain types of XLinks, and other non-user-triggered loads) are not allowed if the originating URI has this protocol flag. Keep in mind that the decision of what ...
... IRIs at the present time, so we must be careful about tracking the native charset of the origin server.) nsIURI newURI( in AUTF8String aSpec, in string aOriginCharset, in nsIURI aBaseURI ); Parameters aSpec The URI string in UTF-8 encoding. Depending on the protocol's implementation, Unicode character sequences may or may not be %xx escaped. aOriginCharset The character set of the document from which this URI string originated. This corresponds to the character set that should be used when communicating this URI to an origin server. If this is null, then UTF-8 encoding is assumed and no character transformation is not performed. aBaseURI If null, aSpec must specify an absolute URI. Otherwise, aSpec may be resolved relative to aBaseURI, depending on the protocol. If the protocol h...
nsIStyleSheetService
rContent.css and userChrome.css in the cascade (so the rules in it will have lower precedence than rules in those sheets). An agent sheet loaded via this API will come after ua.css in the cascade (so the rules in it will have higher precedence than rules in ua.css). The relative ordering of two user or two agent sheets loaded via this API is undefined. Sheets added via this API take effect on all documents, including already-loaded ones, immediately. void loadAndRegisterSheet( in nsIURI sheetURI, in unsigned long type ); Parameters sheetURI URI of the stylesheet to load and register. type One of the type constants. sheetRegistered() Check if a stylesheet has been registered boolean sheetRegistered( in nsIURI sheetURI, in unsigned long type ); Parameters ...
...ters sheetURI URI of the stylesheet to check. type One of the type constants. Return value Returns true if a style sheet at sheetURI has previously been added to the list of style sheets specified by type. unregisterSheet() Remove the style sheet at sheetURI from the list of style sheets specified by type. The removal takes effect immediately, even for already-loaded documents. void unregisterSheet( in nsIURI sheetURI, in unsigned long type ); Parameters sheetURI URI of the stylesheet to unregister. type One of the type constants. See also See Using the Stylesheet Service for examples. ...
nsISupports proxies
s, XPInstall was moved to its own thread. Now XPInstall can do its installations while the product renders, but now XPInstall can not access UI elements such as a progress meter or a confirmation dialog. How can a separate non-UI thread act as if it was on the UI thread? Herein lays the utility of nsISupports Proxies. I believe that other people working on Mozilla need similar solutions. In this document, I will try to explain how to use nsISupports Proxies. How do I use it? The API has changed in Mozilla 1.9, but the prose below hasn't been updated yet. See xpcom/proxy/public/nsIProxyObjectManager.idl for the updated interface and its documentation. See also . From a users point of view, you need only to look at the nsIProxyObjectManager. It has two entry points: NS_IMETHOD GetProxyForObje...
... ...
nsITXTToHTMLConv
...
...itialCaps style instead of the interCaps style. Methods preFormatHTML() Specifies whether or not to wrap the resulting HTML in an <pre> block. void preFormatHTML( in boolean value ); Parameters value true to wrap the resulting HTML in a <pre> block. setTitle() Sets the title to use on the resulting HTML document. void setTitle( in wstring text ); Parameters text Title to set for the HTML document. ...
nsITransferable
iated 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. ...
...vailable. 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. To get the appropriate load context in JavaScript callers, one needs to get to the document that the transferable corresponds to, and then get the load context from the document like this: var loadContext = doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsILoadContext); In C++ callers, if you have the corresponding document, you can just call nsIDocument.GetLoadContext() to get to the load context object. isLargeDataSet() Returns true if the data is large. boolean isL...
nsIUpdate
also contains information about the update that the front end and other application services can use to learn more about what is going on. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview nsIUpdatePatch getPatchAt(in unsigned long index); nsIDOMElement serialize(in nsIDOMDocument updates); Attributes Attribute Type Description appVersion AString The Application version of this update. billboardURL AString The URL to a page that is typically localized to display in the update prompt. buildID AString The build ID of this update. This is used to identify a particular build, down to the hour, minute, and second of its creation. This lets the system differentiate...
...version AString The application version of the update.Obsolete since Gecko 2.0 Methods getPatchAt() Retrieves a patch. nsIUpdatePatch getPatchAt( in unsigned long index ); Parameters index The index of the patch to retrieve. Return value An nsIUpdatePatch object describing the specified patch. serialize() Serializes the update object into a DOM element. nsIDOMElement serialize( in nsIDOMDocument updates ); Parameters updates The DOM document into which to serialize the update. Return value The patch object serialized into an nsIDOMElement. See also nsIUpdatePatch nsIUpdateCheckListener nsIUpdateChecker nsIApplicationUpdateService nsIUpdateManager nsIUpdatePrompt nsIUpdateTimerManager ...
nsIUpdatePatch
nsIUpdateService.idlScriptable An interface that describes an object representing a patch file that can be downloaded and applied to a version of this application so that it can be updated. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview nsIDOMElement serialize(in nsIDOMDocument updates); Attributes Attribute Type Description finalURL AString The final URL this patch was being downloaded from. hashFunction AString The hash function to use when determining the integrity of the patch file. hashValue AString The value of the hash function named in hashFunction that should be computed if the file is not corrupt. selected boolean true if this patch is currently...
...this patch. type AString The type of patch represented by the object: "partial" A binary difference between two application versions. "complete" A complete patch containing all the replacement files to update to the new version. URL AString The URL from which the patch was downloaded. Methods serialize() Serializes the patch object into a DOM element. nsIDOMElement serialize( in nsIDOMDocument updates ); Parameters updates The DOM document into which to serialize the patch. Return value The patch object serialized into an nsIDOMElement. See also nsIUpdate nsIUpdateCheckListener nsIUpdateChecker nsIApplicationUpdateService nsIUpdateManager nsIUpdatePrompt nsIUpdateTimerManager ...
nsIWebBrowserFind
. To change this behavior, and to explicitly set the frame to search, QueryInterface to nsIWebBrowserFindInFrames. Method overview boolean findNext(); Attributes Attribute Type Description entireWord boolean Whether to match entire words only. Default is false. findBackwards boolean Whether to find backwards (towards the beginning of the document). Default is false (search forward). matchCase boolean Whether to match case (case sensitive) when searching. Default is false. searchFrames boolean Whether to search through all frames in the content area. Default is true. Note: That you can control whether the search propagates into child or parent frames explicitly using nsIWebBrowserFindInFrames, but if ...
...can control whether the search propagates into child or parent frames explicitly using nsIWebBrowserFindInFrames, but if one, but not both, of searchSubframes and searchParentFrames are set, this returns false. searchString wstring The string to search for. This must be non-empty to search. wrapFind boolean Whether the search wraps around to the start (or end) of the document if no match was found between the current position and the end (or beginning). Works correctly when searching backwards. Default is false. Methods findNext() Finds, highlights, and scrolls into view the next occurrence of the search string, using the current search settings. Fails if the search string is empty. boolean findNext(); Parameters None. Return value Whether an occurrence was fou...
nsIWebNavigation
be used to satisfy the load. LOAD_FLAGS_BYPASS_PROXY 512 This flag specifies that any intermediate proxy caches should be bypassed (That is, that the content should be loaded from the origin server). LOAD_FLAGS_CHARSET_CHANGE 1024 This flag specifies that a reload was triggered as a result of detecting an incorrect character encoding while parsing a previously loaded document. LOAD_FLAGS_STOP_CONTENT 2048 If this flag is set, Stop() will be called before the load starts and will stop both content and network activity (the default is to only stop network activity). Effectively, this passes the STOP_CONTENT flag to Stop(), in addition to the STOP_NETWORK flag. LOAD_FLAGS_FROM_EXTERNAL 4096 A hint this load was prompted by an extern...
...ool 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 true this indicates that there is forward session history available for navigation. Read only. currentURI nsIURI The currently loaded URI or null. Read only. document nsIDOMDocument Retrieves the current DOM document for the frame, or lazily creates a blank document if there is none. This attribute never returns null except for unexpected error situations. Read only. referringURI nsIURI The referring URI for the currently loaded URI or null. Read only. sessionHistory nsISHistory The session history object used by this web na...
nsIWebProgress
oid addProgressListener(in nsIWebProgressListener aListener, in unsigned long aNotifyMask); void removeProgressListener(in nsIWebProgressListener aListener); Attributes Attribute Type Description DOMWindow nsIDOMWindow The DOM window associated with this nsIWebProgress instance. Read only. Exceptions thrown NS_ERROR_FAILURE Indicates that there is no associated DOM window. isLoadingDocument PRBool Indicates whether or not a document is currently being loaded in the context of this nsIWebProgress instance. Read only. Constants The following flags may be combined to form the aNotifyMask parameter for the addProgressListener() method. They limit the set of events that are delivered to an nsIWebProgressListener instance. These flags indicate the state transistions to observe, corresp...
... events that are delivered to an nsIWebProgressListener instance. These flags indicate the state transistions to observe, corresponding to nsIWebProgressListener.onStateChange(). Constant Value Description NOTIFY_STATE_REQUEST 0x00000001 Only receive the nsIWebProgressListener.onStateChange() event if the aStateFlags parameter includes nsIWebProgressListener::STATE_IS_REQUEST. NOTIFY_STATE_DOCUMENT 0x00000002 Only receive the nsIWebProgressListener.onStateChange() event if the aStateFlags parameter includes nsIWebProgressListener::STATE_IS_DOCUMENT. NOTIFY_STATE_NETWORK 0x00000004 Only receive the nsIWebProgressListener.onStateChange() event if the aStateFlags parameter includes nsIWebProgressListener::STATE_IS_NETWORK. NOTIFY_STATE_WINDOW 0x00000008 Only receive the nsIWebProgressListe...
nsIXULTemplateQueryProcessor
RI objects or nsIDOMNode objects. This method may return an object corresponding to these URIs and the builder will supply this object to other query processor methods. For example, for an XML source, the datasource might be an nsIDOMNode. All of these URIs are checked by the builder so it is safe to use them, however note that a URI that redirects may still needs to be checked to ensure that the document containing aRootNode may access it. This is the responsibility of the query processor if it needs to load the content of the URI. If the query processor needs to load the datasource asynchronously, it may set the aShouldDelayBuilding returned parameter to true to delay building the template content, and call the builder's Rebuild method when the data is available. nsISupports getDatasource( in ...
...ld method when the data is available. nsISupports getDatasource( in nsIArray aDataSources, in nsIDOMNode aRootNode, in boolean aIsTrusted, in nsIXULTemplateBuilder aBuilder, out boolean aShouldDelayBuilding ); Parameters aDataSources The list of nsIURI objects and/or nsIDOMNode objects. aRootNode The root node the builder is attached to. aIsTrusted true if the template is in a trusted document. aBuilder The template builder. aShouldDelayBuilding Whether the builder should wait to build the content or not. Return value A datasource object. initializeForBuilding() Initialize for query generation. This will be called before the rules are processed and whenever the template is rebuilt. This method must be called once before any of the other query processor methods except for translateRef(...
nsIXULWindow
that XUL windows do not currently track child XUL windows. void addChildWindow( in nsIXULWindow aChild ); Parameters aChild The child window being added. Native code only!applyChromeFlags Back-door method to force application of chrome flags at a particular time. Do NOT call this unless you know what you are doing! In particular, calling this when this XUL window does not yet have a document in its docshell could cause problems. void applyChromeFlags(); Parameters None. assumeChromeFlagsAreFrozen() Begin assuming chromeFlags do not change hereafter, and assert if they do change. The state change is one-way and idempotent. void assumeChromeFlagsAreFrozen(); Parameters None. center() Move the window to a centered position. void center( in nsIXULWindow aRelative, in boo...
... new window. nsIXULWindow createNewWindow( in PRInt32 aChromeFlags, in nsIAppShell aAppShell ); Parameters aChromeFlags See nsIWebBrowserChrome. aAppShell The app shell passed to nsIAppShellService's CreateTopLevelWindow method. Return value The newly minted window. In the case of a content window, the function creates a browser window and waits for it to load. You can then load a document into the window's primary content shell. getContentShellById() The content shell specified by the supplied id. Note: That this is a docshell tree item and therefore can not be assured of what object it is. It could be an editor, a docshell, or a browser object. Or down the road any other object that supports being a DocShellTreeItem Query accordingly to determine the capabilities. nsIDocShell...
nsIZipWriter
Adding a file to a Zip archive This code synchronously adds the file specified by the nsIFile theFile to the Zip archive. var zipWriter = Components.Constructor("@mozilla.org/zipwriter;1", "nsIZipWriter"); var zipW = new zipWriter(); zipW.open(myZipFilePath, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.addEntryFile("Path/For/This/File/In/Zip Archive", C...
....init(window, 'Select Directory to Compile', Ci.nsIFilePicker.modeGetFolder); fp.appendFilters(Ci.nsIFilePicker.filterAll | Ci.nsIFilePicker.filterText); var rv = fp.show(); if (rv == Ci.nsIFilePicker.returnOK) { var dir = fp.file; //dir must exist, as the user selected it. ...
Using nsCOMPtr
This document is the sum total of everything written down about nsCOMPtr. If you have a question about nsCOMPtr, and this document doesn't answer it, there probably isn't a document that answers it. You'll have to turn to the XPCOM newsgroup or another experienced nsCOMPtr user, or find the answer by experimentation. If you've never used nsCOMPtr before, you're starting in the right place. Just keep reading. You'll know when to stop. After you've been using nsCOMPtrs for a while, and you reach unfamiliar territory, or run into compiler errors; you may want to return to this document to get help from the Reference Manual or the FAQ. Contents Status, Recent Changes, and Plans Recent changes to nsCOMPtr Getting Started Guide Introduction Using nsCOMPtr Summary ...
... Recent changes to nsCOMPtr Getting Started Guide Introduction Using nsCOMPtr Summary Reference Manual The Basics Initialization and Assignment Using an nsCOMPtr<T> as a T* Efficiency and Correctness Compiler Annoyances Frequently Asked Questions Buildtime Errors Runtime Errors How do I... General Bibliography Original Document Information Author(s): Scott Collins Last Updated Date: December 11, 2001 Copyright Information: Copyright (C) 1999, 2000 by the Mozilla organization; use is subject to the MPL. Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Weak reference
sting event, even. But in this design, by hitching its life to the observable, it is kept on life-support long past any need or use. What is actually needed in this case, is either out-of-band signaling, where when the observer wants to go away, it unregisters itself from the observable, which then releases its owning reference, allowing the observer to die, or else a new kind of reference. This document describes an implementation ofweak references. A weak reference does not hold its referent in existence, but also will not dangle. When the referent is destroyed, the weak reference automatically becomes nsnull. This technique can significantly simplify certain relationships, and you should consider it when an owning reference is inappropriate, but where a raw pointer might end up dangling. How ...
...t out-of-band; this must be before the destructor, which would otherwise never be called. You might hold a raw pointer (without AddRefing and Releaseing it), and avoid using it in cases where it might dangle. See also The source xpcom/base/nsIWeakReference.idl xpcom/glue/nsWeakReference.h xpcom/glue/nsWeakReference.cpp XPCOM ownership guidelines Using nsCOMPtr Original Document Information Author: Scott Collins Last Updated Date: September 23, 2000 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
XPCOM tasks
stration. In any case, the process of registration can, I think, be simplified. 5.1 Should we provide type-safe templatized containers, e.g., over nsISupportsArray? 5.1 We want to provide some mechanism for user-specific components in a multi-user environment. 5.1 Fix the shutdown issues that complicate life for embedding applications. Things we need to evangelize We need to keep up-to-date documentation, samples, and have brown-bags to keep people informed. We've been doing this, but it should be in the plan. General XPCOM guidelines. See, e.g., XPCOM Code FAQ, IDL Author's Guide, and Implementing QueryInterface. Writing and using components and modules. Building ownership models that work (see XPCOM ownership guidelines), using raw pointers, nsCOMPtr (see The nsCOMPtr User's Manual), n...
...COM guidelines. See, e.g., XPCOM Code FAQ, IDL Author's Guide, and Implementing QueryInterface. Writing and using components and modules. Building ownership models that work (see XPCOM ownership guidelines), using raw pointers, nsCOMPtr (see The nsCOMPtr User's Manual), nsIWeakReference (see nsIWeakReference), nsCWeakReference, and (across threads) proxies (see nsISupports proxies). Original Document Information Author(s): unknown Last Updated Date: May 8, 2003 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
xpidl
Mozilla › Tech › XPIDL › xpidl
eplaced with pyxpidl in the Gecko SDK. pyxpidl has been used for some time now, but now this older tool has been fully retired. xpidl is based on the libIDL idl compiler from the Gnome project. The libIDL compiler depends on glib, also from the Gnome project. The xpidl compiler is now part of the build process, allowing us to generate headers used by the XPCOM components. Please check the Build Documentation for further information on where to get libIDL and glib. Using xpidl To add an IDL file to the build, use the XPIDLSRCS makefile variable. For testing purposes, or one-off interface compilation, xpidl can be run from the command line: Usage: ./xpidl -m mode [-w] [-v] [-t version number] [-d filename.pp] [-I path] [-o basename | -e filename.ext] filename.idl -a emit annota...
... -I add entry to start of include path for ``#include "nsIThing.idl" -o use basename (e.g. ...
Mozilla technologies
APNG is a simpler alternative to MNG, providing a spec suitable for the most common usage of animated images on the Internet.DocShellDocshell is the second iteration of what originally started out as WebShell. ...
...d services to XUL applications. These services include:Viewing and searching Mozilla source code onlineSource 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. The module is structured as a drop-in component 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. It has multiple language bindings, allowin...
LDAP Support
It is not intended as an introduction to LDAP and Mozilla products. It assumes you are already familiar with configuring preferences for deployed builds in addition to setting up Thunderbird to use an LDAP directory. It should be noted that all of this information applies to both Thunderbird and the SeaMonkey application suite. Mail Compose Typedown In mail compose, when typing a partial mail address, a typedown window appears listing possible matches against address books and LDAP directories. For large companies, there may be a large number of users in the directory with the same name. ...
... ...
Mail event system
For example, when a folder gets a new message, its total message count increases. The folder pane needs to know that this changed so that it can update the message count so the user can see it. ...
... listener->OnIntPropertyChanged(folder, kTotalMessagesAtom, 4, 5); The folder datasource is a listener on all folders and receives this notification. In its implementation of OnIntPropertyChanged, it notifies RDF (via the nsIRDFObserver system) that the message count has changed. RDF handles the notification by updating the message counts in the folder pane. ...
Theme Packaging
Theme File Layout Thunderbird themes are packaged in an XPI file with the following structure: theme.xpi: install.rdf preview.png icon.png chrome/ browser/files communicator/files global/files mozapps/files ... ...
... Theme File Layout Thunderbird themes are packaged in an XPI file with the following structure: theme.xpi: install.rdf preview.png icon.png chrome/ browser/files communicator/files global/files mozapps/files ... ...
Using popup notifications
back by clicking on the notification icon again. Implementing a timeout function for the popup notification You can use a timeout to make your notification automatically disappear after some amount of time, by calling notification.remove() as shown below. ...
...meout function for the popup notification You can use a timeout to make your notification automatically disappear after some amount of time, by calling notification.remove() as shown below. ...
Flash Activation: Browser Comparison - Plugins
ome 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. ...
...ur up your HTML with a callback that calls the JavaScript function pluginCreated(), like this: <object type="application/x-my-plugin" data="somedata.mytype" id="myPlugin"> <param name="callback" value="pluginCreated()"> </object> The pluginCreated() function is then responsible for the setup of your script and any calls back into the plugin that you need to make: function pluginCreated() { document.getElementById('myPlugin').callPluginMethod(); } ...
Preferences System
This document describes Toolkit's preferences system. Using this system it is possible to create preferences windows that display and operate appropriately on various platforms (Windows, MacOS X and GNOME). The system is implemented through a few XUL elements and attributes. ...
... This document describes Toolkit's preferences system. Using this system it is possible to create preferences windows that display and operate appropriately on various platforms (Windows, MacOS X and GNOME). The system is implemented through a few XUL elements and attributes. ...
Inspecting web app manifests - Firefox Developer Tools
In this article we will look at inspecting app manifests using the Firefox DevTools Application panel. When you open the Application panel's Manifest view on a page that doesn't have an app manifest successfully deployed, you'll get the following output shown: Deploying a manifest To get a manifest deployed successfully, you need to include a <link> element in the <head> of your document that points to your .webmanifest file: <link rel="manifest" href="/manifest.webmanifest"> The .webmanifest extension is recommended in the spec, and should be served with an application/manifest+json mime type, although browsers generally tend to support manifests with other appropriate extensions like .json (mime type: application/json). You also need to make sure the JSON inside the file is of the corre...
... ...
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
ser from the scratchpad's Environment menu, as described in step 2.) Save the following HTML text to a file, and visit the file in your browser. Make sure the current browser tab is displaying this page. <div onclick="doDivsAndSpans()"> Click here to make the page do some allocations. ...
...This begins logging allocations in the current browser tab. ...
Deprecated tools - Firefox Developer Tools
Over the course of DevTools development, we have added several experimental panels to try out new ideas. Not all of these have had wide adoption, and due to the cost of maintenance, seldom used panels are eventually removed. We have created this list of deprecated or removed panels. This page documents the deprecated panels and the bugs that track their removal. Although these panels have been removed, you still have access to the old code, and there are alternative webextensions that you can try to get similar functionality. When we deprecate a panel, we begin by getting feedback from the community to determine the impact of removing that panel. Once we have decided to remove the panel, we will provide a warning message, and finally, we will remove the panel from the codebase. You may see a w...
...are planned but not ported yet: remote browser screenshots and edit remote browser configuration. More details on the mailing-list thread. Canvas debugger Bugzilla issue: bug 1403938 Removed as of Firefox 67 Description Canvas Debugger allowed users to inspect the canvas element and see how frequently a given function is called. It was deprecated due to lack of use. We do not have dedicated documentation for the Canvas Debugger. Alternatives Spector.js is a WebExtension that can provide these features with 3D contexts. Web Audio editor Bugzilla issue: bug 1403944 Removed as of Firefox 67 Description The Web Audio Editor allowed you to examine an audio context constructed in the page and provided a visualization of its graph. This gave a high-level view of its operation, and enabled ...
All keyboard shortcuts - Firefox Developer Tools
This page lists all keyboard shortcuts used by the developer tools built into Firefox. The first section lists the shortcut for opening each tool and the second section lists shortcuts that are applicable to the Toolbox itself. After that there's one section for each tool, which lists the shortcuts that you can use within that tool. Because access keys are locale-dependent, they're not documented in this page. Opening and closing tools These shortcuts work in the main browser window to open the specified tool. The same shortcuts will work to close tools hosted in the Toolbox, if the tool is active. For tools like the Browser Console that open in a new window, you have to close the window to close the tool. Command Windows macOS Linux Open Toolbox (with the most rec...
...S Cmd + S Ctrl + S Open an existing pad Ctrl + O Cmd + O Ctrl + O Create a new pad Ctrl + N Cmd + N Ctrl + N Close Scratchpad Ctrl + W Cmd + W Ctrl + W Pretty print the code in Scratchpad Ctrl + P Cmd + P Ctrl + P Show autocomplete suggestions Ctrl + Space Ctrl + Space Ctrl + Space Show inline documentation Ctrl + Shift + Space Ctrl + Shift + Space Ctrl + Shift + Space Eyedropper Command Windows macOS Linux Select the current color Enter Return Enter Dismiss the Eyedropper Esc Esc Esc Move by 1 pixel Arrow keys Arrow keys Arrow keys Move by 10 pixels Shift + arrow keys Shift + arrow keys ...
DOM allocation example - Firefox Developer Tools
tures of the Memory tool. You can try out the site at https://mdn.github.io/performance-scenarios/dom-allocs/alloc.html. ...
...; function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function createToolbarButton() { var toolbarButton = document.createElement("span"); toolbarButton.classList.add("toolbarbutton"); // stop Spidermonkey from sharing instances toolbarButton[getRandomInt(0,5000)] = "foo"; return toolbarButton; } function createToolbar() { var toolbar = document.createElement("div"); // stop Spidermonkey from sharing instances toolbar[getRandomInt(0,5000)] = "foo"; for (var i = 0; i < toolbarButtonCount; i++) { var toolbarButton = createToolbarButton(); toolbar.appendChild(toolbarButton); } return toolbar; } function createToolbars() { var container = document.getElementById("container"); for (var i = 0; i < toolbarCount; i++) { ...
Network request details - Firefox Developer Tools
hould be included with requests. (See Referrer-Policy for a description of possible values) Blocking: If the request is to a site that is associated with a known tracker, an icon and a message are shown; otherwise, this field is not shown. Response headers The response headers section shows details about the response. For each line in the response headers section, a question mark links to the documentation for that response header, if one is available. A Raw toggle button in the section heading controls whether the headers are shown with formatting, or as plain, unformatted text. Note that the keys in the response header are all in lowercase, while the request headers keys are not. HTTP/2 requires that all headers be lowercase; response headers are shown as they are received from the server...
...org/" }, { "name": "TE", "value": "Trailers" }, { "name": "User-Agent", "value": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0" } ] } } Request headers The Request headers section shows details about the request headers. For each line in the request headers section, a question mark links to the documentation for that request header, if one is available. A Raw toggle button in the section heading controls whether the headers are shown with formatting, or as plain, unformatted text. Cookies tab This tab lists full details of any cookies sent with the request or response: As with headers, you can filter the list of cookies displayed. The full list of cookie attributes is shown--see the foll...
Animation inspector example: Web Animations API - Firefox Developer Tools
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', easing: 'ease-in', endDelay: 100 } var noteKeyframeOptions = { duration: 500, fill: 'forwards', easing: 'ease-out', delay: 150 } var icon = document.getElementById("icon"); var note = document.getElementById("note"); var iconAnimation = icon.animate(iconKeyframeSet, iconKeyframeOptions); var noteAnimation = note.animate(noteKeyframeSet, noteKeyframeOptions); iconAnimation.pause(); noteAnimation.pause(); var firstTime = true; function animateChannel(e) { if (e.button != 0) { return; } if (e.target.id != "icon") { return; } ...
...mate(noteKeyframeSet, noteKeyframeOptions); iconAnimation.pause(); noteAnimation.pause(); var firstTime = true; function animateChannel(e) { if (e.button != 0) { return; } if (e.target.id != "icon") { return; } if (firstTime) { iconAnimation.play(); noteAnimation.play(); firstTime = false; } else { iconAnimation.reverse(); noteAnimation.reverse(); } } document.addEventListener("click", animateChannel); ...
Waterfall - Firefox Developer Tools
ack console.time(), with links to functions. Stack at End (New in Firefox 41). Call stack at console.timeEnd(). If this is inside a callback from a Promise, this will also show the "Async stack". Timestamp A single call to console.timeStamp(). Label The argument passed to timeStamp(). DOMContentLoaded The document's DOMContentLoaded event. Load The document's load event. Worker event in main thread Shown when the main thread sends a message to a worker, or receives a message from a worker. One of: Serialize data on the main thread The main thread is serializing a message to be sent to the worker. Deserialize ...
...x 41, the right-hand sidebar will also show the stack at the end of the period: that is, at the point console.timeEnd() was called. If console.timeEnd() was called from the resolution of a Promise, it will also display "(Async: Promise)", under which it will show the "async stack": that is, the call stack at the point the promise was made. ...
Validators - Firefox Developer Tools
Sidebar tabs are not available at this time. Tune-up wizard links back to devedge If you're writing new code that isn't validating immediately, see the available standards-compliant authoring and development tools. Firefox Extensions for Validation Quick Reference Sidebar Tabs Install DevEdge Toolbox Sidebars for quick access to web development references. Checky Checky adds a submenu to your Netscape or Mozilla context menu that allows you to run whatever page you're on through one of (currently) 18 different online validaton and analysis services. ...
... ...
View Source - Firefox Developer Tools
not be flagged in View Source. If you want to check that HTML is valid, you should use an HTML validator, such as the one offered by W3C. Not all parse errors are reported Even though all the reported errors are parse errors according to the HTML specification, not all parse errors are reported by View Source. Among the errors that don't get reported: Bytes that are illegal according to the document's encoding aren't marked as errors. Forbidden characters aren't reported as errors. Errors related to the end-of-file aren't reported. Tree builder errors relating to text (as opposed to tags, comments, or doctypes) aren't reported. Parse errors related to xmlns attributes aren't reported. XML syntax highlighting View Source uses the HTML tokenizer when highlighting XML source. While the t...
...ce. While the tokenizer has support for processing instructions when highlighting XML source, that's the only XML-specific capability provided. Because of this, doctypes that have an internal subset are not highlighted correctly, and entity references to custom entities are also not highlighted correctly. This mishighlighting can be seen by viewing the source of Firefox chrome files (such as XUL documents). However, this shouldn't be a problem in practice when viewing typical XML files. ...
Console messages - Firefox Developer Tools
n save up a collection of invalidating changes and recalculate their effect at once. However, if some JavaScript code reads a style that has been modified, then the browser must perform a synchronous reflow in order to calculate the computed style to return. For example, code like this will cause an immediate, synchronous, reflow, when it calls window.getComputedStyle(thing).height: var thing = document.getElementById("the-thing"); thing.style.display = "inline-block"; var thingHeight = window.getComputedStyle(thing).height; Because of this, it's a good idea to avoid interleaving write and read calls to an element's styles when manipulating the DOM, because every time you read back a style that has been invalidated by a previous write call, you force a synchronous reflow. Security The securit...
...provides a console API. Your server-side code uses this API to log messages. The server-side library creates JSON objects from the messages and encodes them for transmission. The messages are transmitted to the client as a response header named X-ChromeLogger-Data. The Web Console decodes these headers and displays them. To find a suitable library for your server code, see the Chrome Logger documentation. Interpreter input/output Commands sent to the browser using the Web Console's JavaScript interpreter, and the corresponding responses, are logged in the console messages. For responses that contain objects or variables, the following context menu options are available: Reveal in Inspector Shows the selected DOM node in the Inspector pane. Store as Global Variable Creates a global v...
Rich output - Firefox Developer Tools
Click on the triangle, and the object will be expanded to show its contents: Starting with Firefox 67 (available now in Firefox Developer) you can use the arrow keys on your keyboard to navigate ...
...w next to the request and a details panel will open that is equivalent to the Headers panel in the Network Monitor tool. Export output to the clipboard Once you have output in the console window, you can save it to the clipboard by right-clicking on the output and selecting Export visible messages to clipboard: This will copy all of the output to the clipboard. Then you can paste it into a document. The output will look something like this: console.log(todoList) Array(4) [ {...}, {...}, {...}, {...} ] debugger eval code:1:9 undefined If you expand objects, such as arrays, you get slightly different content. For example, by expanding the array in the above list, I get the following: console.log(todoList) (4) [...] 0: Object { status: "Done", description: "Morning Pages", dateCreated: 155...
Firefox Developer Tools
Click this button to take a screenshot of the current page. (Note: This feature is not turned on by default and must be enabled in settings before the icon will appear.) Toggles Responsive Design Mode. Opens the menu that includes docking options, the ability to show or hide the split console, and Developer 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, exam...
...ent. Measure a portion of the page Measure a specific area of a web page. Rulers Overlay horizontal and vertical rulers on a web page For the latest developer tools and features, try Firefox Developer Edition. Download Firefox Developer Edition Connecting the Developer Tools If you open the developer tools using keyboard shortcuts or the equivalent menu items, they'll target the document hosted by the currently active tab. But you can attach the tools to a variety of other targets, too, both within the current browser and in different browsers or even different devices. about:debugging Debug add-ons, content tabs, and workers running in the browser. Connecting to Firefox for Android Connect the developer tools to an instance of Firefox running on an Android device. Connec...
Animation() - Web APIs
SequenceEffects or GroupEffects might be possible, the only kind of effect currently available is KeyframeEffect. This can be null (which is the default) to indicate that there should be no effect applied. timeline Optional Specifies the timeline with which to associate the animation, as an object of a type based on the AnimationTimeline interface. Currently the only timeline type available is DocumentTimeline, but in the future there my be timelines associated with gestures or scrolling, for example. The default value is Document.timeline, but this can be set to null as well. Examples In the Follow the White Rabbit example, the Animation() constructor is used to create an Animation for the rabbitDownKeyframes using the document's timeline: var rabbitDownAnimation = new Animation(rabbitDown...
...ut in the future there my be timelines associated with gestures or scrolling, for example. The default value is Document.timeline, but this can be set to null as well. Examples In the Follow the White Rabbit example, the Animation() constructor is used to create an Animation for the rabbitDownKeyframes using the document's timeline: var rabbitDownAnimation = new Animation(rabbitDownKeyframes, document.timeline); Specifications Specification Status Comment Web AnimationsThe definition of 'Animation()' in that specification. Working Draft Editor's draft. ...
Animation.onfinish - Web APIs
nt occurs when the animation completes naturally, as well as when the Animation.finish() method is called to immediately cause the animation to finish up. The "paused" play state supersedes the "finished" play state; if the animation is both paused and finished, the "paused" state is the one that will be reported. You can force the animation into the "finished" state by setting its startTime to document.timeline.currentTime - (Animation.currentTime * Animation.playbackRate). Syntax var finishHandler = Animation.onfinish; Animation.onfinish = finishHandler; Value A function to be called to handle the finish event, or null if no finish event handler is set. Examples Animation.onfinish is used several times in the Alice in Web Animations API Land Growing/Shrinking Alice Game. Here is one in...
...lue A function to be called to handle the finish event, or null if no finish event handler is set. Examples Animation.onfinish is used several times in the Alice in Web Animations API Land Growing/Shrinking Alice Game. Here is one instance where we add pointer events back to an element after its opacity animation has faded it in: // Add an animation to the game's ending credits var endingUI = document.getElementById("ending-ui"); var bringUI = endingUI.animate(keysFade, timingFade); // Pause said animation's credits bringUI.pause(); // This function removes pointer events on the credits. hide(endingUI); // When the credits are later faded in, // we re-add the pointer events when they're done bringUI.onfinish = function() { endingUI.style.pointerEvents = 'auto'; }; Specifications ...
Animation.onremove - Web APIs
ve event. This event is sent when the animation is removed (i.e., put into an active replace state). Syntax var removeHandler = animation.onremove; animation.onremove = removeHandler; Value A function to be called to handle the remove event, or null if no remove event handler is set. ...
...n the animation is removed (i.e., put into an active replace state). Syntax var removeHandler = animation.onremove; animation.onremove = removeHandler; Value A function to be called to handle the remove event, or null if no remove event handler is set. ...
Animation.persist() - Web APIs
Web › API › Animation › persist
The persist() method of the Web Animations API's Animation interface explicitly persists an animation, when it would otherwise be removed due to the browser's Automatically removing filling animations behavior. Syntax animation.persist(); Parameters None. Return value None. ...
...Web Animations API's Animation interface explicitly persists an animation, when it would otherwise be removed due to the browser's Automatically removing filling animations behavior. Syntax animation.persist(); Parameters None. Return value None. ...
Animation.playbackRate - Web APIs
Working Draft ...
... Working Draft ...
Animation.replaceState - Web APIs
e of the animation's replace state; when the animation has been removed by the browser's Automatically removing filling animations behavior. persisted: The animation has been explicitly persisted by invoking Animation.persist() on it. removed: The animation has been explicitly removed. ...
...te; when the animation has been removed by the browser's Automatically removing filling animations behavior. persisted: The animation has been explicitly persisted by invoking Animation.persist() on it. removed: The animation has been explicitly removed. ...
AnimationTimeline - Web APIs
Properties AnimationTimeline.currentTime Read only Returns the time value in milliseconds for this timeline or null if this timeline is inactive. ...
... Properties AnimationTimeline.currentTime Read only Returns the time value in milliseconds for this timeline or null if this timeline is inactive. ...
AudioContext.createMediaStreamDestination() - Web APIs
ened that points to a URL created from the blob. From here, you can play and save the opus file. ...
...); osc.stop(0); e.target.disabled = true; } }); mediaRecorder.ondataavailable = function(evt) { // push each chunk (blobs) in an array chunks.push(evt.data); }; mediaRecorder.onstop = function(evt) { // Make blob out of our blobs, and open it. var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); document.querySelector("audio").src = URL.createObjectURL(blob); }; </script> </body> </html> Note: You can view this example live, or study the source code, on Github. Specifications Specification Status Comment Web Audio APIThe definition of 'createMediaStreamDestination()' in that specification. Working Draft ...
AudioContext.getOutputTimestamp() - Web APIs
sition), in the same units and origin as the context's AudioContext.currentTime. Basically, this is the time after the audio context was first created. AudioTimestamp.performanceTime: An estimation of the moment when the sample frame corresponding to the stored contextTime value was rendered by the audio output device, in the same units and origin as performance.now(). This is the time after the document containing the audio context was first rendered. Syntax var timestamp = AudioContext.getOutputTimestamp() Parameters None. Returns An AudioTimestamp object, which has the following properties. contextTime: A point in the time coordinate system of the currentTime for the BaseAudioContext; the time after the audio context was first created. performanceTime: A point in the time coordinate...
...tax var timestamp = AudioContext.getOutputTimestamp() Parameters None. Returns An AudioTimestamp object, which has the following properties. contextTime: A point in the time coordinate system of the currentTime for the BaseAudioContext; the time after the audio context was first created. performanceTime: A point in the time coordinate system of a Performance interface; the time after the document containing the audio context was first rendered Examples In the following code we start to play an audio file after a play button is clicked, and start off a requestAnimationFrame loop running, which constantly outputs the contextTime and performanceTime. You can see full code of this example at output-timestamp (see it live also). play.addEventListener('click', () => { if(!audioCtx) { ...
AudioParam.setValueAtTime() - Web APIs
). ...
...in variable is incremented/decremented by 0.25, then the setValueAtTime() method is used to set the gain value equal to currGain, one second from now (audioCtx.currentTime + 1.) // create audio context var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext(); // set basic variables for example var myAudio = document.querySelector('audio'); var pre = document.querySelector('pre'); var myScript = document.querySelector('script'); pre.innerHTML = myScript.innerHTML; var targetAtTimePlus = document.querySelector('.set-target-at-time-plus'); var targetAtTimeMinus = document.querySelector('.set-target-at-time-minus'); // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var source = audioCtx.createMediaElementSource(myAudio); //...
BatteryManager.onchargingchange - Web APIs
Where battery is a BatteryManager object, and funcRef is a function to be called when the chargingchange event occurs. ...
... to be called when the chargingchange event occurs. ...
BatteryManager.onchargingtimechange - Web APIs
BatteryManager object, and funcRef is a function to be called when the chargingtimechange event occurs. ...
...e chargingtimechange event occurs. ...
BatteryManager.ondischargingtimechange - Web APIs
nager object, and funcRef is a function to be called when the dischargingtimechange event occurs. ...
...ingtimechange event occurs. ...
BiquadFilterNode.getFrequencyResponse() - Web APIs
requencyArray[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>Biquad filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqResponseOutput = document.querySelector('.freq-response-output'); Finally, after creating our biquad 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 biquadFilter = audioCtx.createBiquadFilter(); biquadFilter.type = "lowshelf"; biquadFilter.frequency.value = 1000; biquadFi...
...le list at the bottom of the page: var biquadFilter = audioCtx.createBiquadFilter(); biquadFilter.type = "lowshelf"; biquadFilter.frequency.value = 1000; biquadFilter.gain.value = range.value; ... ...
Blob - Web APIs
Web › API › Blob
ative format. 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. To create a blob that contains a subset of another blob's data, use the slice() method. To obtain a Blob object for a file on the user's file system, see the File documentation. The APIs accepting Blob objects are also listed in the File documentation. Constructor Blob() Returns a newly created Blob object which contains a concatenation of all of the data in the array passed into the constructor. Instance properties Blob.prototype.size Read only The size, in bytes, of the data contained in the Blob object. Blob.prototype.type Read only A string indi...
...ways, including as the value of the <img> element's src attribute (assuming the data contains an image, of course). function typedArrayToURL(typedArray, mimeType) { return URL.createObjectURL(new Blob([typedArray.buffer], {type: mimeType})) } const bytes = new Uint8Array(59); for(let i = 0; i < 59; i++) { bytes[i] = 32 + i; } const url = typedArrayToURL(bytes, 'text/plain'); const link = document.createElement('a'); link.href = url; link.innerText = 'Open the array URL'; document.body.appendChild(link); Result Click the link in the example to see the browser decode the object URL. Extracting data from a blob One way to read content from a Blob is to use a FileReader. The following code reads the content of a Blob as a typed array: const reader = new FileReader(); reader.addEventLi...
Body.text() - Web APIs
Web › API › Body › text
data-page identifier passed to it as an argument -- when one of the links is clicked. When getData() is run, we create a new request using the Request() constructor, then use it to fetch a specific .txt file. When the fetch is successful, we read a USVString (text) object out of the response using text(), then set the innerHTML of the <article> element equal to the text object. ...
... -- when one of the links is clicked. When getData() is run, we create a new request using the Request() constructor, then use it to fetch a specific .txt file. When the fetch is successful, we read a USVString (text) object out of the response using text(), then set the innerHTML of the <article> element equal to the text object. ...
CSS Object Model (CSSOM) - Web APIs
CSS Typed Object Model CSSImageValue CSSKeywordValue CSSMathInvert CSSMathMax CSSMathMin CSSMathNegate CSSMathProduct CSSMathSum CSSMathValue CSSMatrixComponent CSSNumericArray CSSNumericValue CSSPerspective CSSPositionValue CSSRotate CSSScale CSSSkew CS...
... ...
Using the CSS Painting API - Web APIs
s 200 units wide by 20 units tall, positioned 0 units from the left and 15 units from the top of the content box. We can use the CSS background-size and background-position properties to re-size or relocate this background image, but this is the default size and placement of the yellow box we created in our paint worklet. We tried to keep the example simple. For more options, look at the canvas documentation. We also add a little bit of complexity later in this tutorial. Using the paint worklet To use the paint worklet, we need to register it using addModule() and include it in our CSS, ensuring the CSS selector matches a DOM node in our HTML Registering the worklet The setup and design of our paint worklet took place in the external script shown above. We need to register that worklet from ...
...DOM node in our HTML Registering the worklet The setup and design of our paint worklet took place in the external script shown above. We need to register that worklet from our main script. CSS.paintWorklet.addModule('nameOfPaintWorkletFile.js'); This can be done using the paint worklet's addModule() method in a <script> within the main HTML or in an external JavaScript file linked to from the document. In our example, the paintworklet is stored on Github. CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/01partOne/header-highlight.js'); Reference the paint worklet in CSS Once we have a registered paint worklet, we can use it in CSS. Employ the CSS paint() function like we would any other <image> type, using the same string identifier we used in the paintwor...
Cache.match() - Web APIs
Web › API › Cache › match
it resolves with the first matching response only (that is, response[0]). Examples This example is taken from the custom offline page example (live demo). It uses a cache to supply selected data when a request fails. A catch() clause is triggered when the call to fetch() throws an exception. Inside the catch() clause, match() is used to return the correct response. In this example, only HTML documents retrieved with the GET HTTP verb will be cached. If our if() condition is false, then this fetch handler won't intercept the request. If there are any other fetch handlers registered, they will get a chance to call event.respondWith(). If no fetch handlers call event.respondWith(), the request will be handled by the browser as if there were no service worker involvement. If fetch() returns a val...
...With(). If no fetch handlers call event.respondWith(), the request will be handled by the browser as if there were no service worker involvement. If fetch() returns a valid HTTP response with an response code in the 4xx or 5xx range, the catch() will NOT be called. self.addEventListener('fetch', function(event) { // We only want to call event.respondWith() if this is a GET request for an HTML document. if (event.request.method === 'GET' && event.request.headers.get('accept').indexOf('text/html') !== -1) { console.log('Handling fetch event for', event.request.url); event.respondWith( fetch(event.request).catch(function(e) { console.error('Fetch failed; returning offline page instead.', e); return caches.open(OFFLINE_CACHE).then(function(cache) { r...
CanvasRenderingContext2D.addHitRegion() - Web APIs
bel for accessibility tools to use as a description of the region, if there is no control. Defaults to null. role An ARIA role for accessibility tools to determine how to represent this region, if there is no control. Defaults to null. Examples Using the addHitRegion method This example demonstrates the addHitRegion() method. ...
...layable-code" style="height:250px"> ctx.beginPath(); ctx.arc(100, 100, 75, 0, 2 * Math.PI, false); ctx.lineWidth = 5; ctx.stroke(); // eyes ctx.beginPath(); ctx.arc(70, 80, 10, 0, 2 * Math.PI, false); ctx.arc(130, 80, 10, 0, 2 * Math.PI, false); ctx.fill(); ctx.addHitRegion({id: "eyes"}); // mouth ctx.beginPath(); ctx.arc(100, 110, 50, 0, Math.PI, false); ctx.stroke();</textarea> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var textarea = document.getElementById("code"); var reset = document.getElementById("reset"); var edit = document.getElementById("edit"); var code = textarea.value; function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addEventListener("click", function() { textarea.value = code;...
CanvasRenderingContext2D.arc() - Web APIs
tart 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?). ...
...0?), and ends at an angle of 2? ...
CanvasRenderingContext2D.bezierCurveTo() - Web APIs
ol 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. ...
...mple, 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 Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.beziercurveto' in that specification. Living Standard ...
CanvasRenderingContext2D.clearRect() - Web APIs
ues are to the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples Erasing the whole canvas This code snippet erases the entire canvas. This is commonly required at the start of each frame in an animation. The dimensions of the cleared area are set to equal the <canvas> element's width and height attributes. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); Erasing part of a canvas This example draws a blue triangle on top of a yellowish background. The clearRect() method then erases part of the canvas. HTML <canvas id="canvas"></canvas> JavaScript The cleared area is rectangular in shape, with its top-left corner at (10, 10). The ...
...learRect(0, 0, canvas.width, canvas.height); Erasing part of a canvas This example draws a blue triangle on top of a yellowish background. The clearRect() method then erases part of the canvas. HTML <canvas id="canvas"></canvas> JavaScript The cleared area is rectangular in shape, with its top-left corner at (10, 10). The cleared area has a width of 120 and a height of 100. ...
CanvasRenderingContext2D.clip() - Web APIs
ing 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. ...
...illRect(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
(); 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). ...
... 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. ...
CanvasRenderingContext2D.createImageData() - Web APIs
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); // 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 f...
...: 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. ...
CanvasRenderingContext2D.drawImage() - Web APIs
s 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, 104, 124, 21, 20, 87, 104); }); Result Understanding source element size The drawImage() method uses the source element's intrinsic size in CSS pixels when drawing. For example, if you load an Image and specify...
...e 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
e, 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?). ...
...tx.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
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 the "nonzero" rule), the ho...
... 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.fillRect() - Web APIs
alues 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 other things may then be drawn. To achieve this, the dimensions of the rectangle are set to equal the <canvas> elemen...
...Context('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 other things may then be drawn. To achieve this, the dimensions of the rectangle are set to equal the <canvas> element's width and height attributes. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.fillRect(0, 0, canvas.width, canvas.height); Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.fillRect' in that specification. Living Standard ...
CanvasRenderingContext2D.fillStyle - Web APIs
tx.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 square, and only modify the re...
... 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 square, and only modify the red and green values. (The blue channel has a fixed value.) By modifying the channels, you can generate all kinds of palettes. ...
CanvasRenderingContext2D.fillText() - Web APIs
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 call fillText() to draw the text "Hello world," starting at the coordinates...
...xt. 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.getImageData() - Web APIs
object containing the image data for the rectangle of the canvas specified. The coordinates of the rectangle's top-left corner are (sx, sy), while the coordinates of the bottom corner are (sx + sw, sy + sh). Exceptions IndexSizeError Thrown if either sw or sh are zero. SecurityError The canvas contains or may contain pixels which were loaded from an origin other than the 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 retriev...
...s 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 = ctx.getImageData(60, 60, 200, 100); ctx.putImageData(imageData, 150, 10); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.getImageData' in that specification. Living Standard ...
CanvasRenderingContext2D.globalAlpha - Web APIs
ween 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 background composed of four ...
...ter that, we use a for loop to draw a series of circles with increasing radii. With each new circle, the opacity of the previous circles underneath is effectively increased. If we were to increase the step count (and thus draw more circles), the background would eventually disappear completely from the center of the image. ...
CanvasRenderingContext2D.isPointInPath() - Web APIs
sed. 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 becomes green, otherwise it is...
...sult = 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
oolean 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 yes, the ellipse's stroke...
...'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.lineCap - Web APIs
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 added. Each of these lines ...
...s the default "butt" option. It's drawn completely flush with the guides. The second is set to use the "round" option. This adds a semicircle to the end that has a radius half the width of the line. The line on the right uses the "square" option. This adds a box with an equal width and half the height of the line thickness. ...
CanvasRenderingContext2D.lineDashOffset - Web APIs
"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. ...
...x.moveTo(0, 100); ctx.lineTo(300, 100); ctx.stroke(); Result The line with a dash offset is drawn in red. Marching ants The marching ants effect is an animation technique often found in selection tools of computer graphics programs. It helps the user to distinguish the selection border from the image background by animating the border. ...
CanvasRenderingContext2D.lineJoin - Web APIs
egment. "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="canvas" width="150" height...
...nst 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. ...
CanvasRenderingContext2D.lineTo() - Web APIs
() 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). ...
...0); // 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. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.moveTo(90, 130); ctx.lineTo(95, 25); ctx.lineTo(150, 80); ctx.lineTo(205, 25); ctx.lineTo(210, 130); ctx.lineWidth = 15; ctx.stroke(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.lineTo' in that specification. Living Standard ...
CanvasRenderingContext2D.miterLimit - Web APIs
ation. ...
...canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.beginPath(); ctx.moveTo(0,0); ctx.lineWidth = 15; ctx.lineTo(100, 100); ctx.stroke();</textarea> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var textarea = document.getElementById("code"); var reset = document.getElementById("reset"); var edit = document.getElementById("edit"); var code = textarea.value; function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addEventListener("click", function() { textarea.value = code; drawCanvas(); }); edit.addEventListener("click", function() { textarea.focus();...
CanvasRenderingContext2D.putImageData() - Web APIs
ge 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(). ...
...ageData 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
uadraticCurveTo(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. ...
... 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 HTML Living StandardThe definition of 'CanvasRenderingContext2D.quadraticCurveTo' in that specification. Living Standard ...
CanvasRenderingContext2D.resetTransform() - Web APIs
id 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 Continuing with a regular matrix Whenever you're done drawing transformed shapes, you should call resetTransform() before rendering anything else. In this ...
...trix 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
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. ...
...ing 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). ...
CanvasRenderingContext2D.scale() - Web APIs
son. 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). ...
..., 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 Standard ...
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
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. ...
...s id="canvas" width="400" height="200" class="playable-canvas"> <input id="button" type="range" min="1" max="12"> </canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.beginPath(); ctx.rect(10, 10, 30, 30); ctx.scrollPathIntoView();</textarea> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var textarea = document.getElementById("code"); var reset = document.getElementById("reset"); var edit = document.getElementById("edit"); var code = textarea.value; function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addEventListener("click", function() { textarea.value = code;...
CanvasRenderingContext2D.setLineDash() - Web APIs
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. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); 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 ...
...ty 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. ...
CanvasRenderingContext2D.setTransform() - Web APIs
ingle 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 matrix from it using Canv...
... 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
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. ...
...nt 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. ...
CanvasRenderingContext2D.strokeRect() - Web APIs
o 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. ...
...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"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.shadowColor = '#d53'; ctx.shadowBlur = 20; ctx.lineJoin = 'bevel'; ctx.lineWidth = 15; ctx.strokeStyle = '#38f'; ctx.strokeRect(30, 30, 160, 90); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.strokeRect' in that specification. Livi...
CanvasRenderingContext2D.strokeStyle - Web APIs
okeStyle = 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 RGB color for each circle...
...e 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 RGB color for each circle, and only modify the green and blue values. ...
CanvasRenderingContext2D.strokeText() - Web APIs
he 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 call strokeText() to draw the text "Hello world," starting at the coordin...
.... 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
eft 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". ...
...gn = '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. ...
Canvas API - Web APIs
ngs, 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), and gives it a...
... <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), and gives it a size of 150 units wide by 100 tall. ...
ChildNode.remove() - Web APIs
Web › API › ChildNode › remove
See Symbol.unscopables for more information. ...
... Living Standard Initial definition. ...
ChildNode - Web APIs
Web › API › ChildNode
Properties There are neither inherited, nor specific properties. Methods There are no inherited methods. ChildNode.remove() Removes this ChildNode from the children list of its parent. ChildNode.before() Inserts a set of Node or DOMString objects in the children list of this ChildNode's parent, just before this ChildNode. DOMString objects are inserted as equivalent Text nodes. ...
...de or DOMString objects. DOMString objects are inserted as equivalent Text nodes. Specifications Specification Status Comment DOMThe definition of 'ChildNode' in that specification. Living Standard Split the ElementTraversal interface in ParentNode and ChildNode. previousElementSibling and nextElementSibling are now defined on the latter. The CharacterData and DocumentType implemented the new interfaces. Added the remove(), before(), after() and replaceWith() methods. Element Traversal SpecificationThe definition of 'ElementTraversal' in that specification. Obsolete Added the initial definition of its properties to the ElementTraversal pure interface and use it on Element. Polyfill External on GitHub: childNode.js ...
Clipboard API - Web APIs
ously read from and write to the system clipboard. Access to the contents of the clipboard is gated behind the Permissions API: The clipboard-write permission is granted automatically to pages when they are in the active tab. The clipboard-read permission must be requested, which you can do by trying to read data from the clipboard. ...
...ard-read permission must be requested, which you can do by trying to read data from the clipboard. This API is designed to supersede accessing the clipboard using document.execCommand(). Accessing the clipboard Instead of creating a Clipboard object through instantiation, you access the system clipboard through the Navigator.clipboard global: navigator.clipboard.readText().then( clipText => document.querySelector(".editor").innerText += clipText); This snippet fetches the text from the clipboard and appends it to the first element found with the class editor. Since readText() (and read(), for that matter) returns an empty string if the clipboard isn't text, this code is safe. Interfaces Clipboard Secure context Provides an interface for reading and writing text and data to or from the ...
Comment - Web APIs
Web › API › Comment
structor Comment() Returns a Comment object with the parameter as its textual content. Methods This interface has no specific method, but inherits those of its parent, CharacterData, and indirectly those of Node. Specifications Specification Status Comment DOMThe definition of 'Comment' in that specification. Living Standard Added the constructor. ...
...method, but inherits those of its parent, CharacterData, and indirectly those of Node. Specifications Specification Status Comment DOMThe definition of 'Comment' in that specification. Living Standard Added the constructor. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Comment' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Comment' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification Document Object Model (DOM) Level 1 SpecificationThe definition of 'Comment' in that specification. Obsolete Initial definition ...
Constraint validation API - Web APIs
"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. ...
... <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. If you wanted to instead display custom error messages, you could use JavaScript like the following: const nameInput = document.querySelector('input'); const form = document.querySelector('form'); nameInput.addEventListener('input', () => { nameInput.setCustomValidity(''); nameInput.checkValidity(); }); nameInput.addEventListener('invalid', () => { if(nameInput.value === '') { nameInput.setCustomValidity('Enter your username!'); } else { nameInput.setCustomValidity('Usernames can only contain upper and lowercase letters. Try again!'); } }); The e...
ContentIndex - Web APIs
ction that retrieves items within the content index and iterates over each entry, building a list for the interface. ...
...st() { // access our service worker registration const registration = await navigator.serviceWorker.ready; // get our index entries const entries = await registration.index.getAll(); // create a containing element const readingListElem = document.createElement('div'); // test for entries if (!Array.length) { // if there are no entries, display a message const message = document.createElement('p'); message.innerText = 'You currently have no articles saved for offline reading.' readingListElem.append(message); } else { // if entries are present, display in a list of links to the content const listElem = document.createElement('ul'); for (const entry of entries) { const listItem = document.createElement('li'); const anchorElem = docum...
CustomElementRegistry.upgrade() - Web APIs
The upgrade() method of the CustomElementRegistry interface upgrades all shadow-containing custom elements in a Node subtree, even before they are connected to the main document. Syntax customElements.upgrade(root); Parameters root A Node instance with shadow-containing descendant elements that are to be upgraded. If there are no descendant elements that can be upgraded, no error is thrown. Return value Void. ...
...shadow-containing custom elements in a Node subtree, even before they are connected to the main document. Syntax customElements.upgrade(root); Parameters root A Node instance with shadow-containing descendant elements that are to be upgraded. If there are no descendant elements that can be upgraded, no error is thrown. Return value Void. ...
DOMMatrixReadOnly.translate() - Web APIs
ything other than 0, the resulting matrix will be 3D. Return value Returns a DOMMatrix containing a new matrix being the result of the matrix being translated by the given vector. The original matrix 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. co...
...0"> <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 Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMMatrixReadOnly.translate()' in that specification. Candidate Recommendation Initial definition ...
DOMTokenList.remove() - Web APIs
ring 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. ...
...tent. 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; classes2.remove("c", "b"); span2.textContent = classes; Specifications Specification Status Comment DOMThe definition of 'remove()' in that specification. Living Standard Initial definition ...
DOMTokenList - Web APIs
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: <span class=" d ...
...sses = 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: <span class=" d d e f"></span> let span = document.querySelector("span"); let classes = span.classList; span.classList.add("x"); span.textContent = `span classList is "${classes}"`; The output looks like this: Specifications Specification Status Comment DOMThe definition of 'DOMTokenList' in that specification. Living Standard Initial definition ...
DataTransfer.clearData() - Web APIs
<span id="status">Drag to start</span></div> <div>Data is: <span id="data">uninitialized</span></div> CSS span.tweaked { display: inline-block; margin: 1em 0; padding: 1em 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } JavaScript window.addEventListener('DOMContentLoaded', function () { // Select HTML elements var draggable = document.getElementById('source'); var dropable = document.getElementById('target'); var status = document.getElementById('status'); var data = document.getElementById('data'); var dropped = false; // Register event handlers draggable.addEventListener('dragstart', dragStartHandler); draggable.addEventListener('dragend', dragEndHandler); dropable.addEventListener('dragover', dragOverHandle...
...entDefault(); } function dragLeaveHandler (event) { status.innerHTML = 'Drag in process (drop was available)'; event.preventDefault(); } function dropHandler (event) { dropped = true; status.innerHTML = 'Drop done'; event.preventDefault(); // Get data linked to event format << text >> var _data = event.dataTransfer.getData('text/plain'); var element = document.getElementById(_data); // Append drag source element to event's target element event.target.appendChild(element); // Change CSS styles and displayed text element.style.cssText = 'border: 1px solid black;display: block; color: red'; element.innerHTML = "I'm in the Drop Zone!"; } }) Specifications Specification Status Comment HTML Living Standard...
DataTransfer.getData() - Web APIs
Living Standard HTML 5.1The definition of 'getData()' in that specification. Recommendation Initial definition ...
... Living Standard HTML 5.1The definition of 'getData()' in that specification. Recommendation Initial definition ...
DataTransferItem.getAsFile() - Web APIs
e use of the getAsFile() method in a drop event handler. function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = event.dataTransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // This item is the target node data[i].getAsString(function (s){ ev.target.appendChild(document.getElementById(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // Drag data item is HTML console.log("... Drop: HTML"); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI console.log("... Drop: URI"); } else if ((data[i].kind == 'file') && ...
...s an image file var f = data[i].getAsFile(); console.log("... Drop: File "); } } } Specifications Specification Status Comment HTML Living StandardThe definition of 'getAsFile()' in that specification. Living Standard Initial value HTML 5.1The definition of 'getAsFile()' in that specification. Recommendation Snapshot of the HTML WHATWG document ...
DataTransferItem.getAsString() - Web APIs
ing() method as an inline function in a drop event handler. function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // This item is the target node data[i].getAsString(function (s){ ev.target.appendChild(document.getElementById(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // Drag data item is HTML console.log("... Drop: HTML"); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI console.log("... Drop: URI"); } else if ((data[i].kind == 'file') && ...
...mage file var f = data[i].getAsFile(); console.log("... Drop: File "); } } } Specifications Specification Status Comment HTML Living StandardThe definition of 'getAsString()' in that specification. Living Standard Initial definition. HTML 5.1The definition of 'getAsString()' in that specification. Recommendation Snapshot fo HTML WHATWG document ...
DataTransferItem.kind - Web APIs
xample This example shows the use of the kind property. function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = event.dataTransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // This item is the target node data[i].getAsString(function (s){ ev.target.appendChild(document.getElementById(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // Drag data item is HTML console.log("... Drop: HTML"); } else if ((data[i].kind == 'file') && (data[i].type.match('^image/'))) { // Drag data item is an image file var f = data[i].getAsFile(); console.log("... Drop: File "); } ...
... ...
DataTransferItem.type - Web APIs
Example This example shows the use of the type property. function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // This item is the target node data[i].getAsString(function (s){ ev.target.appendChild(document.getElementById(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // Drag data item is HTML console.log("... Drop: HTML"); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI console.log("... Drop: URI"); } else if ((data[i].kind == 'file') && ...
... data item is an image file var f = data[i].getAsFile(); console.log("... Drop: File "); } } } Specifications Specification Status Comment HTML Living StandardThe definition of 'type' in that specification. Living Standard Initial version HTML 5.1The definition of 'type' in that specification. Recommendation Snapshot of the HTML WHATWG document ...
DedicatedWorkerGlobalScope - Web APIs
dlers from the WorkerGlobalScope interface, and its parent EventTarget, and therefore implements event handlers from WindowTimers, WindowBase64, and WindowEventHandlers. DedicatedWorkerGlobalScope.onmessage Is an EventHandler representing the code to be called when the message event is raised. These events are of type MessageEvent and will be called when the worker receives a message from the document that started it (i.e. from the Worker.postMessage method.) DedicatedWorkerGlobalScope.onmessageerror Is an EventHandler representing the code to be called when the messageerror event is raised. Methods This interface inherits methods from the WorkerGlobalScope interface, and its parent EventTarget, and therefore implements methods from WindowTimers, WindowBase64, and WindowEventHandlers. ...
... 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 WindowBase64.atob() Decodes a string...
DirectoryReaderSync - Web APIs
This specification is pretty much abandoned, having failed to reach any substantial traction. ...
... This specification is pretty much abandoned, having failed to reach any substantial traction. ...
How to create a DOM tree - Web APIs
This page describes how to use the DOM Core API in JavaScript to create and modify DOM objects. It applies to all Gecko-based applications (such as Firefox) both in privileged (extensions) and unprivileged (web pages) code. ...
... <person first-name="jed" last-name="brown"> <address street="321 north st" city="atlanta" state="ga" country="usa"/> <address street="123 west st" city="seattle" state="wa" country="usa"/> <address street="321 south avenue" city="denver" state="co" country="usa"/> </person> </people> The W3C DOM API, supported by Mozilla, can be used to create an in-memory representation of this document like so: var doc = document.implementation.createDocument("", "", null); var peopleElem = doc.createElement("people"); var personElem1 = doc.createElement("person"); personElem1.setAttribute("first-name", "eric"); personElem1.setAttribute("middle-initial", "h"); personElem1.setAttribute("last-name", "jung"); var addressElem1 = doc.createElement("address"); addressElem1.setAttribute("street", "...
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...
...a = "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("P"); // put the text in the paragraph newElement.appendChild(newText); // and put the paragraph on the end of the document by appending it to // the BODY (which is the parent of para) para.parentNode.appendChild(newElement); } </script> </head> <body> <input type="button" value="Change this document." onclick="change()"> <h1>Header</h1> <p>Paragraph</p> </body> </head> ...
Element: auxclick event - Web APIs
textmenu 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). ...
... 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: blur event - Web APIs
he opposite of blur is focus. ...
...t) => { 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. Document Object Model (...
Element.className - Web APIs
Web › API › Element › className
The className property of the Element interface gets and sets the value of the class attribute of the specified element. Syntax var cName = elementNodeReference.className; elementNodeReference.className = cName; cName is a string variable representing the class or space-separated classes of the current element. Example let el = document.getElementById('item'); if (el.className === 'active'){ el.className = 'inactive'; } else { el.className = 'active'; } Notes The name className is used for this property instead of class because of conflicts with the "class" keyword in many languages which are used to manipulate the DOM. className can also be an instance of SVGAnimatedString if the element is an SVGElement. It is better to get/set the className of an element using Element.getAttrib...
...ss attribute. elm.setAttribute('class', elm.getAttribute('class')) The class is an HTML Attribute, while the className is a DOM Property. Specifications Specification Status Comment DOMThe definition of 'element.className' in that specification. Living Standard DOM4The definition of 'element.className' in that specification. Obsolete Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'element.className' in that specification. Obsolete Initial definition ...
Element: click event - Web APIs
<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 Document Object Model (DOM) Lev...
...ick 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 Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'click' in that specification. Obsolete Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'click' in that specification. Obsolete ...
Element: compositionend event - Web APIs
red when a text composition system such as an input method editor completes or cancels the current composition session. For example, this event could be fired after a user finishes entering a Chinese character using a Pinyin IME. ...
...on> </div> CSS body { padding: .2rem; display: grid; grid-template-areas: "control log"; } .control { grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } JS const inputElement = document.querySelector('input[type="text"]'); const log = document.querySelector('.event-log-contents'); const clearLog = document.querySelector('.clear-log'); clearLog.addEventListener('click', () => { log.textContent = ''; }); function handleEvent(event) { log.textContent = log.textContent + `${event.type}: ${event.data}\n`; } inputElement.addEventListener('compositionstart', handleEvent); in...
Element: compositionstart event - Web APIs
itionstart event is fired when a text composition system such as an input method editor starts a new composition session. For example, this event could be fired after a user starts entering a Chinese character using a Pinyin IME. ...
...on> </div> CSS body { padding: .2rem; display: grid; grid-template-areas: "control log"; } .control { grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } JS const inputElement = document.querySelector('input[type="text"]'); const log = document.querySelector('.event-log-contents'); const clearLog = document.querySelector('.clear-log'); clearLog.addEventListener('click', () => { log.textContent = ''; }); function handleEvent(event) { log.textContent = log.textContent + `${event.type}: ${event.data}\n`; } inputElement.addEventListener('compositionstart', handleEvent); in...
Element: compositionupdate event - Web APIs
r is received in the context of a text composition session controlled by a text composition system such as an input method editor. For example, this event could be fired while a user enters a Chinese character using a Pinyin IME. ...
...on> </div> CSS body { padding: .2rem; display: grid; grid-template-areas: "control log"; } .control { grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } JS const inputElement = document.querySelector('input[type="text"]'); const log = document.querySelector('.event-log-contents'); const clearLog = document.querySelector('.clear-log'); clearLog.addEventListener('click', () => { log.textContent = ''; }); function handleEvent(event) { log.textContent = log.textContent + `${event.type}: ${event.data}\n`; } inputElement.addEventListener('compositionstart', handleEvent); in...
Element: copy event - Web APIs
not affect the system clipboard. ...
...>Try copying text from this box...</div> <div class="target" contenteditable="true">...and pasting it into this one</div> CSS div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } JS const source = document.querySelector('div.source'); source.addEventListener('copy', (event) => { const selection = document.getSelection(); event.clipboardData.setData('text/plain', selection.toString().toUpperCase()); event.preventDefault(); }); Result Specifications Specification Status Clipboard API and events Working Draft ...
Element: dblclick event - Web APIs
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. ...
... Obsolete ...
Element: focus event - Web APIs
e opposite of focus is blur. ...
...nt) => { 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. Document Object Model (...
Element.hasAttributeNS() - Web APIs
hasAttributeNS returns a boolean value indicating whether the current element has the specified attribute. Syntax result = element.hasAttributeNS(namespace,localName) result is the boolean value true or false. namespace is a string specifying the namespace of the attribute. localName is the name of the attribute. ...
... Living Standard ...
Element.hasAttributes() - Web APIs
The hasAttributes() method of the Element interface returns a Boolean indicating whether the current element has any attributes or not. Syntax var result = element.hasAttributes(); Return value result holds the return value true or false. Examples let foo = document.getElementById('foo'); if (foo.hasAttributes()) { // Do something with 'foo.attributes' } Polyfill ;(function(prototype) { prototype.hasAttributes = prototype.hasAttributes || function() { return (this.attributes.length > 0); } })(Element.prototype); Specifications Specification Status Comment DOMThe definition of 'Element.hasAttributes()' in that specification. Living Standard Moved from the Node interface to the more specialized Element interface. Document Object M...
...otype); Specifications Specification Status Comment DOMThe definition of 'Element.hasAttributes()' in that specification. Living Standard Moved from the Node interface to the more specialized Element interface. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'hasAttributes()' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'hasAttributes()' in that specification. Obsolete Initial definition, on the Node interface. ...
Element.hasPointerCapture() - Web APIs
ement on which it is invoked has pointer capture for the pointer identified by the given pointer ID. Syntax targetElement.hasPointerCapture(pointerId); Parameters pointerId The pointerId of a PointerEvent object. Return value A Boolean value -- true if the element does have pointer capture, false if it doesn't. Examples <html> <script> function downHandler(ev) { const el = document.getElementById("target"); // Element 'target' will receive/capture further events el.setPointerCapture(ev.pointerId); /* ... */ // Check whether element still has pointer capture let pointerCap = el.hasPointerCapture(ev.pointerId); if(pointerCap) { // We've still got pointer capture } else { // oops, we've lost pointer capture! } ...
...target' will receive/capture further events el.setPointerCapture(ev.pointerId); /* ... */ // Check whether element still has pointer capture let pointerCap = el.hasPointerCapture(ev.pointerId); if(pointerCap) { // We've still got pointer capture } else { // oops, we've lost pointer capture! } } function init() { const el = document.getElementById("target"); el.onpointerdown = downHandler; } </script> <body onload="init();"> <div id="target">Touch this element with a pointer.</div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'hasPointerCapture()' in that specification. Recommendation ...
Element.insertAdjacentElement() - Web APIs
ised value. TypeError The element specified is not a valid element. Visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> Note: The beforebegin and afterend positions work only if the node is in a tree and has an element parent. ...
...ions work only if the node is in a tree and has an element parent. Example beforeBtn.addEventListener('click', function() { var tempDiv = document.createElement('div'); tempDiv.style.backgroundColor = randomColor(); if (activeElem) { activeElem.insertAdjacentElement('beforebegin',tempDiv); } setListener(tempDiv); }); afterBtn.addEventListener('click', function() { var tempDiv = document.createElement('div'); tempDiv.style.backgroundColor = randomColor(); if (activeElem) { activeElem.insertAdjacentElement('afterend',tempDiv); } setListener(tempDiv); }); Have a look at our insertAdjacentElement.html demo on Github (see the source code too.) Here we have a sequence of <div> elements inside a container. When one is clicked, it becomes selected and you can then press the...
Element: keydown event - Web APIs
IME): eventTarget.addEventListener("keydown", event => { if (event.isComposing || event.keyCode === 229) { return; } // do something }); Examples addEventListener keydown example This example logs the KeyboardEvent.code value whenever you press down a key inside the <input> element. ...
...", event => { if (event.isComposing || event.keyCode === 229) { return; } // do something }); Examples addEventListener keydown example This example logs the KeyboardEvent.code value whenever you press down a key inside the <input> element. ...
Element: keypress event - Web APIs
nch text composition system; blur and focus events; DOMActivate event; other event Examples addEventListener keypress example This example logs the KeyboardEvent.code value whenever you press a key after focussing the <input> element. ...
...ents; DOMActivate event; other event Examples addEventListener keypress example This example logs the KeyboardEvent.code value whenever you press a key after focussing the <input> element. ...
Element: keyup event - Web APIs
IME): eventTarget.addEventListener("keyup", event => { if (event.isComposing || event.keyCode === 229) { return; } // do something }); Examples addEventListener keyup example This example logs the KeyboardEvent.code value whenever you release a key inside the <input> element. ...
... event => { if (event.isComposing || event.keyCode === 229) { return; } // do something }); Examples addEventListener keyup example This example logs the KeyboardEvent.code value whenever you release a key inside the <input> element. ...
Element: mousedown event - Web APIs
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; y = e.offsetY; isDrawing = true; }); myPics.addEventListener('mousemove', e => { if (isDrawing === true) { dr...
... Obsolete ...
Element: mousemove event - Web APIs
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; y = e.offsetY; isDrawing = true; }); myPics.addEventListener('mousemove', e => { if (isDrawing === true) { dr...
... Obsolete ...
Element: mouseout event - Web APIs
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>. ...
... Obsolete ...
Element: mouseover event - Web APIs
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. ...
... Obsolete ...
Element: mouseup event - Web APIs
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; y = e.offsetY; isDrawing = true; }); myPics.addEventListener('mousemove', e => { if (isDrawing === true) { dr...
... Obsolete ...
Element.name - Web APIs
Web › API › Element › name
the name property of an element in the DOM. It only applies to the following elements: <a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, <input>, <map>, <meta>, <object>, <param>, <select>, and <textarea>. Note: The name property doesn't exist for other elements; unlike tagName and nodeName, it is not a property of the Node, Element or HTMLElement interfaces. name can be used in the document.getElementsByName() method, a form and with the form elements collection. When used with a form or elements collection, it may return a single element or a collection. Syntax HTMLElement.name = string let elName = HTMLElement.name let fControl = HTMLFormElement.elementName let controlCollection = HTMLFormElement.elements.elementName Example <form action="" name="formA"> <input type="text"...
...turn a single element or a collection. Syntax HTMLElement.name = string let elName = HTMLElement.name let fControl = HTMLFormElement.elementName let controlCollection = HTMLFormElement.elements.elementName Example <form action="" name="formA"> <input type="text" value="foo"> </form> <script type="text/javascript"> // Get a reference to the first element in the form let formElement = document.forms['formA'].elements[0] // Give it a name formElement.name = 'inputA' // Show the value of the input alert(document.forms['formA'].elements['inputA'].value) </script> Notes In Internet Explorer (IE), the name property of DOM objects created using document.createElement() can't be set or modified. ...
Element.scrollHeight - Web APIs
inline-block; margin-bottom: 12px; border-radius: 5px; width: 600px; padding: 5px; border: 2px #7FDF55 solid; } #rules { width: 600px; height: 130px; padding: 5px; border: #2A9F00 solid 2px; border-radius: 5px; } JavaScript function checkReading () { if (checkReading.read) { return; } checkReading.read = this.scrollHeight - this.scrollTop === this.clientHeight; document.registration.accept.disabled = document.getElementById("nextstep").disabled = !checkReading.read; checkReading.noticeBox.innerHTML = checkReading.read ? "Thank you." : "Please, scroll and read the following text."; } onload = function () { var oToBeRead = document.getElementById("rules"); checkReading.noticeBox = document.createElement("span"); document.registration.accept.checked = fals...
... Working Draft Initial definition ...
Element: select event - Web APIs
nterface, Event otherwise Event handler property onselect The event is not available for all elements in all languages. For example, in HTML, select events can be dispatched only on form <input type="text"> and <textarea> elements. ...
... <input type="text"> and <textarea> elements. Examples Selection logger <input value="Try selecting some text in this element."> <p id="log"></p> function logSelection(event) { const log = document.getElementById('log'); const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd); log.textContent = `You selected: ${selection}`; } const input = document.querySelector('input'); input.addEventListener('select', logSelection); onselect equivalent You can also set up the event handler using the onselect property: input.onselect = logSelection; Specifications Specification Status UI EventsThe definition of 'select' in that specification. Working Draft ...
Element.setAttribute() - Web APIs
ecified name and value. To get the current value of an attribute, use getAttribute(); to remove an attribute, call removeAttribute(). Syntax Element.setAttribute(name, value); Parameters name A DOMString specifying the name of the attribute whose value is to be set. The attribute name is automatically converted to all lower-case when setAttribute() is called on an HTML element in an HTML document. value A DOMString containing the value to assign to the attribute. Any non-string value specified is converted automatically into a string. Boolean attributes are considered to be true if they're present on the element at all, regardless of their actual value; as a rule, you should specify the empty string ("") in value (some people use the attribute's name; this works but is non-standard). ...
...ue 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 can specify any va...
Element.setAttributeNS() - Web APIs
value of an attribute with the given namespace and name. Syntax element.setAttributeNS(namespace, name, value) namespace is a string specifying the namespace of the attribute. name is a string identifying the attribute by its qualified name; that is, a namespace prefix followed by a colon followed by a local name. value is the desired string value of the new attribute. ...
... Living Standard ...
Element.setAttributeNodeNS() - Web APIs
replacedAttr = element.setAttributeNodeNS(attributeNode) replacedAttr is the replaced attribute node, if any, returned by this function. attributeNode is an Attr node. Example // <div id="one" xmlns:myNS="http://www.mozilla.org/ns/specialspace" // myNS:special-align="utterleft">one</div> // <div id="two">two</div> var myns = "http://www.mozilla.org/ns/specialspace"; var d1 = document.getElementById("one"); var d2 = document.getElementById("two"); var a = d1.getAttributeNodeNS(myns, "special-align"); d2.setAttributeNodeNS(a.cloneNode(true)); alert(d2.attributes[1].value) // returns: `utterleft' Notes If the specified attribute already exists on the element, then that attribute is replaced with the new one and the replaced one is returned. Note that if you try to set withou...
... Living Standard ...
Element.slot - Web APIs
Web › API › Element › slot
ates and slots for more information). Syntax var aString = element.slot element.slot = aString Value A DOMString. Examples In our simple-template example (see it live), we create a trivial custom element example called <my-paragraph> in which a shadow root 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 slottedS...
...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 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://g...
Comparison of Event Targets - Web APIs
</tr> </thead> <tr> <td id="target"></td> <td id="currentTarget"></td> <td id="relatedTarget"></td> <td id="explicitOriginalTarget"></td> <td id="originalTarget"></td> </tr> </table> <p>Clicking on the text will show the difference between explicitOriginalTarget, originalTarget, and target</p> <script> function handleClicks(e) { document.getElementById('target').innerHTML = e.target; document.getElementById('currentTarget').innerHTML = e.currentTarget; document.getElementById('relatedTarget').innerHTML = e.relatedTarget; document.getElementById('explicitOriginalTarget').innerHTML = e.explicitOriginalTarget; document.getElementById('originalTarget').innerHTML = e.originalTarget; } function ...
...erHTML = e.target; document.getElementById('currentTarget').innerHTML = e.currentTarget; document.getElementById('relatedTarget').innerHTML = e.relatedTarget; document.getElementById('explicitOriginalTarget').innerHTML = e.explicitOriginalTarget; document.getElementById('originalTarget').innerHTML = e.originalTarget; } function handleMouseover(e) { document.getElementById('target').innerHTML = e.target; document.getElementById('relatedTarget').innerHTML = e.relatedTarget; } document.addEventListener('click', handleClicks, false); document.addEventListener('mouseover', handleMouseover, false); </script> </body> </html> Use of target and relatedTarget The relatedTarget property for the mouseover event holds the node that the mou...
Event.cancelable - Web APIs
Web › API › Event › cancelable
cannot be canceled. function preventScrollWheel(event) { if (typeof event.cancelable !== 'boolean' || event.cancelable) { // The event can be canceled, so we do so. event.preventDefault(); } else { // The event cannot be canceled, so it is not safe // to call preventDefault() on it. console.warn(`The following event couldn't be canceled:`); console.dir(event); } } document.addEventListener('wheel', preventScrollWheel); Notes Whether an event can be canceled or not is something that's determined when that event is initialized. To cancel an event, call the preventDefault() method on the event. This keeps the implementation from executing the default action that is associated with the event. Specifications Specification Status Comment ...
... is something that's determined when that event is initialized. To cancel an event, call the preventDefault() method on the event. This keeps the implementation from executing the default action that is associated with the event. Specifications Specification Status Comment DOMThe definition of 'Event.cancelable' in that specification. Living Standard Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'Event.cancelable' in that specification. Obsolete Initial definition. ...
Event.currentTarget - Web APIs
h may be its descendant. Syntax var currentEventTarget = event.currentTarget; Value EventTarget Examples Event.currentTarget is interesting to use when attaching the same event handler to several elements. function hide(e){ e.currentTarget.style.visibility = 'hidden'; console.log(e.currentTarget); // When this function is used as an event handler: this === e.currentTarget } var ps = document.getElementsByTagName('p'); for(var i = 0; i < ps.length; i++){ // Console: print the clicked <p> element ps[i].addEventListener('click', hide, false); } // Console: print <body> document.body.addEventListener('click', hide, false); // Click around and make paragraphs disappear Note: The value of event.currentTarget is only available while the event is being handled. If you console.log() ...
... the console or use the debugger statement, which will pause the execution of your code thus showing you the value of event.currentTarget. Specifications Specification Status Comment DOMThe definition of 'Event.currentTarget' in that specification. Living Standard DOM4The definition of 'Event.currentTarget' in that specification. Obsolete Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'current event target' in that specification. Obsolete Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'Event.currentTarget' in that specification. Obsolete Initial definition ...
Event.timeStamp - Web APIs
Web › API › Event › timeStamp
The timeStamp read-only property of the Event interface returns the time (in milliseconds) at which the event was created. Note: This property only works if the event system supports it for the particular event. Syntax time = event.timeStamp; Value This value is the number of milliseconds elapsed from the beginning of the current document's lifetime till the event was created. ...
...ed. 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.reduceTimerPrecision preference is enabled by default and defaults t...
EventListener - Web APIs
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 is // treated just the same as a ...
... just the same as a function itself. buttonElement.addEventListener('click', { handleEvent: function (event) { alert('Element clicked through handleEvent property!'); } }); Result See Also: addEventListener Specifications Specification Status Comment DOMThe definition of 'EventListener' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'EventListener' in that specification. Obsolete Initial definition. ...
EventSource - Web APIs
n to an event source has opened. Additionally, the event source itself may send messages with an event field, which will create ad-hoc events keyed to that value. Examples In this basic example, an EventSource is created to receive unnamed events from the server; a page with the name sse.php is responsible for generating the events. var evtSource = new EventSource('sse.php'); var eventList = document.querySelector('ul'); evtSource.onmessage = function(e) { var newElement = document.createElement("li"); newElement.textContent = "message: " + e.data; eventList.appendChild(newElement); } Each received event causes our EventSource object's onmessage event handler to be run. It, in turn, creates a new <li> element and writes the message's data into it, then appends the new element to the ...
... Note: You can find a full example on GitHub -- see Simple SSE demo using PHP. To listen to named events, you'll require a listener for each type of event sent. ...
FeaturePolicy.allowedFeatures() - Web APIs
un on. As such, allowedFeatures() method returns a subset of directives returned by features(). Syntax const allowed = FeaturePolicy.allowedFeatures() Parameters None. Return value An array of strings representing the Feature Policy directive names that are allowed by the Feature Policy this method is called on. Example The followin example logs all the allowed directives for the current document. ...
...representing the Feature Policy directive names that are allowed by the Feature Policy this method is called on. Example The followin example logs all the allowed directives for the current document. Please note that these features might be restricted by the Permissions API, if the user did not grant the corrsponding permission yet. // First, get the Feature Policy object const featurePolicy = document.featurePolicy // Then query feature for specific const allowed = featurePolicy.allowedFeatures() for (const directive of allowed){ console.log(directive) } Specifications Specification Status Comment Feature PolicyThe definition of 'allowsFeature' in that specification. Editor's Draft Initial definition. ...
FeaturePolicy.allowsFeature() - Web APIs
ture(<feature>) or const allowed = FeaturePolicy.allowsFeature(<feature>, <origin>) Parameters Feature name A specific feature name must be specified. Origin name Optional An origin URL to check the feature on. If it is omitted the default origin is used. Return value A Boolean that is true if and only if the feature is allowed. ...
...s used. Return value A Boolean that is true if and only if the feature is allowed. Example The following example queries whether or not the document is allowed to use camera API by the Feature Policy. Please note that Camera API might be restricted by the Permissions API, if the user did not grant the corresponding permission yet. // First, get the Feature Policy object const featurePolicy = document.featurePolicy // Then query feature for specific const allowed = featurePolicy.allowsFeature("camera") if (allowed){ console.log("FP allows camera.") } else { console.log("FP does not allows camera.") } Specifications Specification Status Comment Feature PolicyThe definition of 'allowsFeature' in that specification. Editor's Draft Initial definition. ...
File.getAsDataURL() - Web APIs
Web › API › File › getAsDataURL
mmary The getAsDataURL provides a data: URL that encodes the entire contents of the referenced file. Note: This method is obsolete; you should use the FileReader method readAsDataURL() instead. ...
... ...
GlobalEventHandlers.onauxclick - Web APIs
nstead, since it's more flexible. Example 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 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). ...
...n 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 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). ...
GlobalEventHandlers.onblur - Web APIs
The blur 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. ...
...n 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 Living StandardThe defi...
GlobalEventHandlers.onclick - Web APIs
in 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> JavaScript let lo...
...ElementById('demo').onclick = function changeContent() { document.getElementById('demo').innerHTML = "Help me"; document.getElementById('demo').style = "Color: red"; } Result Getting the coordinates of clicks This example displays the coordinates at which the most recent mouse button click occurred. HTML <p>Click anywhere in this example.</p> <p id="log"></p> JavaScript let log = document.getElementById('log'); document.onclick = inputChange; function inputChange(e) { log.textContent = `Position: (${e.clientX}, ${e.clientY})`; } Result Specification Specification Status Comment HTML Living StandardThe definition of 'onclick' in that specification. Living Standard ...
GlobalEventHandlers.oncontextmenu - Web APIs
Living Standard ...
... Living Standard ...
GlobalEventHandlers.onload - Web APIs
There are also DOM Events like DOMContentLoaded and DOMFrameContentLoaded (which can be handled using EventTarget.addEventListener()) which a...
... console.log("load event detected!"); } window.onload = load; </script> // ES2015 <script> const load = () => { console.log("load event detected!"); } window.onload = load; </script> </head> <body> <p>The load event fires when the document has finished loading!</p> </body> </html> Notes The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading. There are also DOM Events like DOMContentLoaded and DOMFrameContentLoaded (which can be handled using EventTarget.addEventListener()) which are fired after the DOM for the page has been constructed, but do not wait for other resources to fini...
GlobalEventHandlers.onmousemove - Web APIs
onmouseover, and onmouseout event handlers. ...
...tooltip here &hellip;</a></p> <p><a href="#" data-tooltip="Second link">&hellip; or here!</a></p> CSS .tooltip { position: absolute; z-index: 9999; padding: 6px; background: #ffd; border: 1px #886 solid; border-radius: 5px; } JavaScript const tooltip = new (function() { const node = document.createElement('div'); node.className = 'tooltip'; node.setAttribute('hidden', ''); document.body.appendChild(node); this.follow = function(event) { node.style.left = event.clientX + 20 + 'px'; node.style.top = event.clientY + 10 + 'px'; }; this.show = function(event) { node.textContent = event.target.dataset.tooltip; node.removeAttribute('hidden'); }; this.hide = function() { node.setAttribute('hidden', ''); }; })(); const links = document.querySelect...
GlobalEventHandlers.onpointerdown - Web APIs
The GlobalEventHandlers event handler onpointerdown is used to specify the event handler for the pointerdown event, which is fired when the pointing device is initially pressed. This event can be sent to Window, Document, and Element objects. This is functionally equivalent to the mousedown event when generated due to user activity with a mouse or mouse-compatible device. If the pointerdown event isn't canceled through a call to preventDefault(), most user agents will fire a mousedown event, so that sites not using pointer events will work. ...
...rdown event isn't canceled through a call to preventDefault(), most user agents will fire a mousedown event, so that sites not using pointer events will work. You can also use addEventListener() to add a listener for pointerdown events. Syntax target.onpointerdown = downHandler; var downHandler = target.onpointerdown; Value A Function to handle the pointerdown event for the target Element, Document, or Window. It receives as input the PointerEvent describing the pointerdown event. Example This example demonstrates how to watch for and act upon pointerdown events using onpointerdown. You could also use addEventListener(), of course. JavaScript First, let's look at the JavaScript code that handles the pointerdown event. var targetBox = document.getElementById("target"); targetBox.onpoin...
GlobalEventHandlers.onscroll - Web APIs
Note: Don't confuse onscroll with onwheel! onwheel handles general wheel rotation, while onscroll handles scrolling of an object's content. Syntax target.onscroll = functionRef Value functionRef A function name, or a function expression. The function receives a UIEvent object as its sole argument. Only one onscroll handler can be assigned to an object at a time. ...
...t a time. For greater flexibility, you can pass a scroll event to the EventTarget.addEventListener() method instead. Example This example monitors scrolling on a <textarea>, and logs the element's vertical scroll position accordingly. HTML <textarea>1 2 3 4 5 6 7 8 9</textarea> <p id="log"></p> CSS textarea { width: 4rem; height: 8rem; font-size: 3rem; } JavaScript const textarea = document.querySelector('textarea'); const log = document.getElementById('log'); textarea.onscroll = logScroll; function logScroll(e) { log.textContent = `Scroll position: ${e.target.scrollTop}`; } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'onscroll' in that specification. Living Standard Document Object Mod...
GlobalEventHandlers.onselect - Web APIs
selected. Syntax target.onselect = functionRef; Value functionRef is a function name or a function expression. The function receives a UIEvent object as its sole argument. Examples This example logs the text you select inside a <textarea> element. ...
...he text you select inside a <textarea> element. HTML <textarea>Try selecting some text in this element.</textarea> <p id="log"></p> JavaScript function logSelection(event) { const log = document.getElementById('log'); const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd); log.textContent = `You selected: ${selection}`; } const textarea = document.querySelector('textarea'); textarea.onselect = logSelection; Result Specification Specification Status Comment HTML Living StandardThe definition of 'onselect' in that specification. Living Standard ...
GlobalEventHandlers.ontransitioncancel - Web APIs
topped before it has run to completion, e.g. by moving the mouse off a hover-transitioning element. Syntax var transitionCancelHandler = target.ontransitioncancel; target.ontransitioncancel = Function Value A Function to be called when a transitioncancel event occurs indicating that a CSS transition has been cancelled on the target, where the target object is an HTML element (HTMLElement), document (Document), or window (Window). The function receives as input a single parameter: a TransitionEvent object describing the event which occurred; the event's TransitionEvent.elapsedTime property's value should be the same as the value of transition-duration. Note: elapsedTime does not include time prior to the transition effect beginning; that means that the value of transition-delay doesn't aff...
...color 2s; transition: width 2s, height 2s, background-color 2s, transform 2s, color 2s; } .box:hover { background-color: #FFCCCC; color: #000000; width: 200px; height: 200px; -webkit-transform: rotate(180deg); transform: rotate(180deg); } JavaScript Next, we need to establish our event handlers to change the text content of the box when the transition begins and ends. ...
GlobalEventHandlers.ontransitionend - Web APIs
f the transition-property attribute which applies to the target. Another is if the display attribute is set to none. Syntax var transitionEndHandler = target.ontransitionend; target.ontransitionend = Function Value A Function to be called when a transitionend event occurs indicating that a CSS transition has completed on the target, where the target object is an HTML element (HTMLElement), document (Document), or window (Window). The function receives as input a single parameter: a TransitionEvent object describing the event which occurred; the event's TransitionEvent.elapsedTime property's value should be the same as the value of transition-duration. elapsedTime does not include time prior to the transition effect beginning; that means that the value of transition-delay doesn't affect th...
...: bold 1.6em "Helvetica", "Arial", sans-serif; transition: width 2s, height 2s, background-color 2s, transform 2s, color 2s; } .box:hover { background-color: #FFCCCC; color: #000000; width: 200px; height: 200px; transform: rotate(180deg); } JavaScript Next, we need to establish our event handlers to change the text content of the box when the transition begins and ends. let box = document.querySelector(".box"); box.ontransitionrun = function(event) { box.innerHTML = "Zooming..."; } box.ontransitionend = function(event) { box.innerHTML = "Done!"; } Result The resulting content looks like this: Notice what happens when you hover your mouse cursor over the box, then move it away. Specification Specification Status Comment CSS TransitionsThe def...
GlobalEventHandlers.onwheel - Web APIs
Living Standard ...
... Living Standard ...
GlobalEventHandlers - Web APIs
The GlobalEventHandlers mixin describes the event handlers common to several interfaces like HTMLElement, Document, or Window. Each of these interfaces can, of course, add more event handlers in addition to the ones listed below. Note: GlobalEventHandlers is a mixin and not an interface; you can't actually create an object of type GlobalEventHandlers. Properties This interface doesn't include any properties except for the event handlers listed below. Event handlers These event handlers are defined on the GlobalEventHandlers mixin, and implemented by HTMLElement, Document, Window, as well as by WorkerGlobalScope for Web Workers. GlobalEventHandlers.onabort Is an EventHandler representing the code to be called when the abort event is raised. GlobalEventHandlers.onanimationcancel An ...
...ing Is an EventHandler representing the code to be called when the waiting event is raised. Methods This interface defines no methods. Specifications Specification Status Comment Selection APIThe definition of 'Extension to GlobalEventHandlers' in that specification. Working Draft Adds onselectionchange. Pointer LockThe definition of 'Extension of Document' in that specification. Candidate Recommendation Adds onpointerlockchange and onpointerlockerror on Document. It is experimentally implemented on GlobalEventHandlers. HTML Living StandardThe definition of 'GlobalEventHandlers' in that specification. Living Standard No change since the latest snapshot, HTML 5.1. HTML 5.1The definition of 'GlobalEventHandlers' in that ...
HTMLAnchorElement.rel - Web APIs
The HTMLAnchorElement.rel property reflects the rel attribute. It is a DOMString containing a space-separated list of link types indicating the relationship between the resource represented by the <a> element and the current document. Syntax var relstr = anchorElt.rel; anchorElt.rel = relstr; Example var anchors = document.getElementsByTagName("a"); var length = anchors.length; for (var i = 0; i < length; i++) { alert("Rel: " + anchors[i].rel); } Specifications Specification Status Comment HTML Living StandardThe definition of 'rel' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'rel' in that specification. Ob...
...l: " + anchors[i].rel); } Specifications Specification Status Comment HTML Living StandardThe definition of 'rel' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'rel' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification Document Object Model (DOM) Level 1 SpecificationThe definition of 'rel' in that specification. Obsolete Initial definition. ...
HTMLAnchorElement.relList - Web APIs
The HTMLAnchorElement.relList read-only property reflects the rel attribute. It is a live DOMTokenList containing the set of link types indicating the relationship between the resource represented by the <a> element and the current document. The property itself is read-only, meaning you can't substitute the DOMTokenList with another one, but its contents can still be changed. ...
...ty reflects the rel attribute. It is a live DOMTokenList containing the set of link types indicating the relationship between the resource represented by the <a> element and the current document. The property itself is read-only, meaning you can't substitute the DOMTokenList with another one, but its contents can still be changed. ...
HTMLAreaElement.relList - Web APIs
The HTMLAreaElement.relList read-only property reflects the rel attribute. It is a live DOMTokenList containing the set of link types indicating the relationship between the resource represented by the <area> element and the current document. The property itself is read-only, meaning you can't substitute the DOMTokenList by another one, but the content of the returned list can be changed. ...
... the rel attribute. It is a live DOMTokenList containing the set of link types indicating the relationship between the resource represented by the <area> element and the current document. The property itself is read-only, meaning you can't substitute the DOMTokenList by another one, but the content of the returned list can be changed. ...
HTMLAreaElement - Web APIs
tils.protocol Is a USVString containing the protocol component (including trailing colon ':'), of the referenced URL. HTMLAreaElement.referrerPolicy Is a DOMString that reflects the referrerpolicy HTML attribute indicating which referrer to use when fetching the linked resource. HTMLAreaElement.rel Is a DOMString that reflects the rel HTML attribute, indicating relationships of the current document to the linked resource. HTMLAreaElement.relList Read only Returns a DOMTokenList that reflects the rel HTML attribute, indicating relationships of the current document to the linked resource, as a list of tokens. HTMLHyperlinkElementUtils.search Is a USVString containing the search element (including leading question mark '?'), if any, of the referenced URL. HTMLAreaElement.shape Is a DOMS...
...ements this mixin. HTML5The definition of 'HTMLAreaElement' in that specification. Recommendation Technically, the properties tabindex and accesskey are now defined on HTMLElement. The following property is now obsolete: nohref. The following properties have been added: rel, relList, media, hreflang, type, host, hostname, pathname, port, protocol, search, and hash. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLAreaElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLAreaElement' in that specification. Obsolete Initial definition ...
Audio() - Web APIs
Syntax audioObj = new Audio(url); Parameters url Optional An optional DOMString containing the URL of an audio file to be associated with the new audio element. Return value A new HTMLAudioElement object, configured to be used for playing back the audio from the file specified by url.The new object's preload property is set to auto and its src property is set to the specified URL or null if no URL is given. ...
...onfigured to be used for playing back the audio from the file specified by url.The new object's preload property is set to auto and its src property is set to the specified URL or null if no URL is given. If a URL is specified, the browser begins to asynchronously load the media resource before returning the new object. Usage notes You can also use other element-creation methods, such as the document object's createElement() method, to construct a new HTMLAudioElement. Determining when playback can begin There are three ways you can tell when enough of the audio file has loaded to allow playback to begin: Check the value of the readyState property. If it's HTMLMediaElement.HAVE_FUTURE_DATA, there's enough data available to begin playback and play for at least a short time. If it's HTMLMe...
HTMLBaseFontElement - Web APIs
quires that this element implements HTMLUnknownElement rather than HTMLBaseFontElement. Properties Inherits properties from its parent, HTMLElement. HTMLBaseFontElement.color Is a DOMString representing the text color using either a named color or a color specified in the hexadecimal #RRGGBB format. HTMLBaseFontElement.face Is a DOMString representing a list of one or more font names. The document text in the default style is rendered in the first font face that the client's browser supports. If no font listed is installed on the local system, the browser typically defaults to the proportional or fixed-width font for that system. HTMLBaseFontElement.size Is a DOMString representing the font size as either a numeric or relative value. Numeric values range from 1 to 7 with 1 being the smal...
... font for that system. HTMLBaseFontElement.size Is a DOMString representing the font size as either a numeric or relative value. Numeric values range from 1 to 7 with 1 being the smallest and 3 the default. Relative value starts with a '+' or a '-'. Methods No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLBaseFontElement' in that specification. Obsolete No change Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLBaseFontElement' in that specification. Obsolete Initial definition ...
HTMLBodyElement - Web APIs
lers. HTMLBodyElement.aLink Is a DOMString that represents the color of active hyperlinks. HTMLBodyElement.background Is a DOMString that represents the description of the location of the background image resource. Note that this is not an URI, though some older version of some browsers do expect it. HTMLBodyElement.bgColor Is a DOMString that represents the background color for the document. HTMLBodyElement.link Is a DOMString that represents the color of unvisited links. HTMLBodyElement.text Is a DOMString that represents the foreground color of text. HTMLBodyElement.vLink Is a DOMString that represents the color of visited links. Methods No specific methods; inherits methods from its parent, HTMLElement, and from WindowEventHandlers. Event handlers No specific eve...
...he definition of 'HTMLBodyElement' in that specification. Recommendation The following properties are now obsolete: aLink, bgColor, background, link, text, and vLink. The following properties have been added: onafterprint, onbeforeprint, onbeforeunload, onblur, onerror, onfocus, onhashchange, onload, onmessage, onoffline, ononline, onpopstate, onresize, onstorage, and onunload. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLBodyElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLBodyElement' in that specification. Obsolete Initial definition. ...
HTMLCollection.item - Web APIs
lection are live, changes to the underlying DOM can and will cause the position of individual nodes in the collection to change, so the index value will not necessarily remain constant for a given node. Syntax var element = HTMLCollection.item(index) Parameters index The position of the Node to be returned. ...
...hey appear in the document's source. Return value The Node at the specified index, or null if index is less than zero or greater than or equal to the length property. Usage notes The item() method returns a numbered element from an HTMLCollection. In JavaScript, it is easier to treat the HTMLCollection as an array and to index it using array notation. See the example below. ...
HTMLElement.click() - Web APIs
Web › API › HTMLElement › click
The HTMLElement.click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input>), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events. ...
...s up to elements higher in the document tree (or event chain) and fires their click events. Syntax element.click() Example Simulate a mouse-click when moving the mouse pointer over a checkbox: HTML <form> <input type="checkbox" id="myCheck" onmouseover="myFunction()" onclick="alert('click event occured')"> </form> JavaScript // On mouse-over, execute myFunction function myFunction() { document.getElementById("myCheck").click(); } Specification Specification Status Comment HTML Living Standard Living Standard Document Object Model (DOM) Level 2 HTML Specification Obsolete Initial definition. ...
HTMLElement.dir - Web APIs
Web › API › HTMLElement › dir
ngDirection is a string variable representing the text writing direction of the current element. newWritingDirection is a string variable representing the text writing direction value. Possible values for dir are ltr, for left-to-right, rtl, for right-to-left, and auto for specifying that the direction of the element must be determined based on the contents of the element. Example var parg = document.getElementById("para1"); parg.dir = "rtl"; // change the text direction on a paragraph identified as "para1" Specifications Specification Status Comment HTML Living StandardThe definition of 'dir' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML Speci...
...ph identified as "para1" Specifications Specification Status Comment HTML Living StandardThe definition of 'dir' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'dir' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'dir' in that specification. Obsolete Initial definition. ...
HTMLElement: gotpointercapture event - Web APIs
es a pointer using setPointerCapture(). Bubbles Yes Cancelable No Interface PointerEvent Event handler property ongotpointercapture Examples This example gets a <p> element and listens for the gotpointercapture event. It then calls setPointerCapture() on the element on a pointerdown event, which will trigger gotpointercapture. ...
...on the element on a pointerdown event, which will trigger gotpointercapture. ...
HTMLElement.innerText - Web APIs
nfused with Node.textContent, but there are important differences between the two. Basically, innerText is aware of the rendered appearance of text, while textContent is not. Syntax const renderedText = htmlElement.innerText htmlElement.innerText = string Value A DOMString representing the rendered text content of an element. If the element itself is not being rendered (e.g detached from the document or is hidden from view), the returned value is the same as the Node.textContent property. Example This example compares innerText with Node.textContent. Note how innerText is aware of things like <br> elements, and ignores hidden elements. HTML <h3>Source element:</h3> <p id="source"> <style>#source { color: red; } #text { text-transform: uppercase; }</style> <span id=text>Take a look at<b...
... uppercase; }</style> <span id=text>Take a look at<br>how this text<br>is interpreted below.</span> <span style="display:none">HIDDEN TEXT</span> </p> <h3>Result of textContent:</h3> <textarea id="textContentOutput" rows="6" cols="30" readonly>...</textarea> <h3>Result of innerText:</h3> <textarea id="innerTextOutput" rows="6" cols="30" readonly>...</textarea> JavaScript const source = document.getElementById("source"); const textContentOutput = document.getElementById("textContentOutput"); const innerTextOutput = document.getElementById("innerTextOutput"); textContentOutput.value = source.textContent; innerTextOutput.value = source.innerText; Result Specification Specification Status Comment HTML Living StandardThe definition of 'innerText' in that spe...
HTMLElement: lostpointercapture event - Web APIs
eased. Bubbles Yes Cancelable No Interface PointerEvent Event handler property onlostpointercapture Examples This example listens for the lostpointercapture event for an element, and captures the pointer for the element on pointerdown. When the user subsequently releases the pointer, the lostpointercapture event will be fired. ...
...ntly releases the pointer, the lostpointercapture event will be fired. ...
HTMLElement.oncopy - Web APIs
Value functionRef is a function name or a function expression. The function receives a ClipboardEvent object as its sole argument. Example This example blocks every copy and paste attempt from the <textarea>. ...
...d="editor" rows="3">Try copying and pasting text into this field!</textarea> <h3>Log:</h3> <p id="log"></p> JavaScript const log = document.getElementById('log'); function logCopy(event) { log.innerText = 'Copy blocked!\n' + log.innerText; event.preventDefault(); } function logPaste(event) { log.innerText = 'Paste blocked!\n' + log.innerText; event.preventDefault(); } const editor = document.getElementById('editor'); editor.oncopy = logCopy; editor.onpaste = logPaste; Result Specification WHATWG Standard ...
HTMLElement.oncut - Web APIs
Web › API › HTMLElement › oncut
copy and cut attempt. ...
... text area:</h3> <textarea id="editor" rows="3">Try copying and cutting the text in this field!</textarea> <h3>Log:</h3> <p id="log"></p> JavaScript function logCopy(event) { log.innerText = 'Copied!\n' + log.innerText; } function preventCut(event) { event.preventDefault(); log.innerText = 'Cut blocked!\n' + log.innerText; } const editor = document.getElementById('editor'); const log = document.getElementById('log'); editor.oncopy = logCopy; editor.oncut = preventCut; Result Specification WHATWG Standard ...
HTMLElement.onpaste - Web APIs
ple logs every copy and paste attempt to the <textarea>. ...
...extarea>. ...
HTMLElement: pointercancel event - Web APIs
lly. This can happen if, for example, the hardware supports palm rejection to prevent a hand resting on the display while using a stylus from accidentally triggering events. The touch-action CSS property prevents the input from continuing. After the pointercancel event is fired, the browser will also send pointerout followed by pointerleave. ...
...SS property prevents the input from continuing. After the pointercancel event is fired, the browser will also send pointerout followed by pointerleave. ...
HTMLElement: pointerdown event - Web APIs
o buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer. ...
...ct with the digitizer. ...
HTMLElement: pointerenter event - Web APIs
when a pointing device is moved into the hit test boundaries of an element or one of its descendants, including as a result of a pointerdown event from a device that does not support hover (see pointerdown). ...
...ee pointerdown). ...
HTMLElement: pointerleave event - Web APIs
nterleave event is fired when a pointing device is moved out of the hit test boundaries of an element. For pen devices, this event is fired when the stylus leaves the hover range detectable by the digitizer. ...
...e by the digitizer. ...
HTMLElement: pointermove event - Web APIs
terface PointerEvent Event handler property onpointermove Usage notes The event, which is of type PointerEvent, provides all the information you need to know about the user's interaction with the pointing device, including the position, movement distance, button states, and much more. ...
... user's interaction with the pointing device, including the position, movement distance, button states, and much more. ...
HTMLElement: pointerout event - Web APIs
g the pointerup event for a device that does not support hover (see pointerup); after firing the pointercancel event (see pointercancel); when a pen stylus leaves the hover range detectable by the digitizer. ...
...tectable by the digitizer. ...
HTMLElement: pointerover event - Web APIs
The pointerover event is fired when a pointing device is moved into an element's hit test boundaries. ...
...t's hit test boundaries. ...
HTMLElement: pointerup event - Web APIs
The pointerup event is fired when a pointer is no longer active. ...
... when a pointer is no longer active. ...
HTMLElement.title - Web APIs
Web › API › HTMLElement › title
The HTMLElement.title property represents the title of the element: the text usually displayed in a 'tooltip' popup when the mouse is over the node. Syntax var str = element.title; element.title = str; Example const link = document.createElement('a'); link.innerText = 'grapes'; link.href = 'https://en.wikipedia.org/wiki/Grape'; link.title = 'Wikipedia page on grapes'; Specifications Specification Status Comment HTML Living StandardThe definition of 'title' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'title' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. ...
...n Status Comment HTML Living StandardThe definition of 'title' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'title' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'title' in that specification. Obsolete Initial definition. ...
HTMLElement: transitionrun event - Web APIs
class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. ...
... height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. ...
HTMLElement: transitionstart event - Web APIs
essage"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. ...
... 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. ...
HTMLFieldSetElement - Web APIs
nging to this field set. The type of this property depends on the version of the spec that is implemented by the browser. HTMLFieldSetElement.formRead only An HTMLFormControlsCollection or HTMLCollection referencing the containing 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 r...
...ML 5.1The definition of 'HTMLFieldSetElement' in that specification. Recommendation HTML5The definition of 'HTMLFieldSetElement' in that specification. Recommendation The following properties have been added: disabled, elements, name, type, valdiationMessage, validity, and willValidate. The following methods have been added: checkValidity(), setCustomValidity(). Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLFieldSetElement' in that specification. Obsolete No change Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLFieldSetElement' in that specification. Obsolete Initial definition ...
HTMLFontElement.face - Web APIs
If no font listed is installed on the local system, the browser typically defaults to the proportional or fixed-width font for that system. ...
... ...
HTMLHeadElement - Web APIs
This object inherits all of the properties and methods described in the HTMLElement interface. ...
...atus Comment HTML Living StandardThe definition of 'HTMLHeadElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLHeadElement' in that specification. Recommendation No change from HTML5. HTML5The definition of 'HTMLHeadElement' in that specification. Recommendation The following property has been removed: profile. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLHeadElement' in that specification. Obsolete No change Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLHeadElement' in that specification. Obsolete Initial definition ...
HTMLHyperlinkElementUtils.toString() - Web APIs
The HTMLHyperlinkElementUtils.toString() stringifier method returns a USVString containing the whole URL. It is a read-only version of HTMLHyperlinkElementUtils.href. ...
... The HTMLHyperlinkElementUtils.toString() stringifier method returns a USVString containing the whole URL. It is a read-only version of HTMLHyperlinkElementUtils.href. ...
Image() - Web APIs
Disambiguation: image(), the CSS function notation. Syntax var htmlImageElement = new Image(width, height); Parameters width The width of the image (i.e., the value for the width attribute). height The height of the image (i.e., the value for the height attribute). Usage note The entire bitmap is loaded regardless of the sizes specified in the constructor. The size specified in the constructor is reflected through the properties HTMLImageElement.width and HTMLImageElement.height of the resulting instance. ...
...ImageElement.width and HTMLImageElement.height of the resulting instance. The intrinsic width and height of the image in CSS pixels are reflected through the properties HTMLImageElement.naturalWidth and HTMLImageElement.naturalHeight. If no size is specified in the constructor both pairs of properties have the same values. Examples var myImage = new Image(100, 200); myImage.src = 'picture.jpg'; document.body.appendChild(myImage); This would be the equivalent of defining the following HTML tag inside the <body>: <img width="100" height="200" src="picture.jpg"> Specifications Specification Status Comment HTML Living StandardThe definition of 'Image()' in that specification. Living Standard ...
HTMLImageElement.naturalHeight - Web APIs
utput"> </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%). ...
...el 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%). ...
HTMLImageElement.naturalWidth - Web APIs
utput"> </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%). ...
...el 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%). ...
HTMLImageElement.sizes - Web APIs
Each condition is specified using the same conditional format used by media queries. ...
...ay: 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 = image.sizes.replace(/40em,/, "50em,")); Result This result may be viewed in its own window here. Spe...
HTMLImageElement.srcset - Web APIs
rovided as an SVG file that should be used in all other cases. Notice that the candidates may use different image types. For more information on what image formats are available for use in the <img> element, see Image file type and format guide. Example HTML The HTML below indicates that the default image is the 200 pixel wide version of the clock image we use in several places throughout our documentation. Also specified by the srcset attribute is that the 200-pixel version should be used for 1x displays while the 400-pixel version should be used for 2x displays. <div class="box"> <img src="/files/16797/clock-demo-200px.png" alt="Clock" srcset="/files/16864/clock-demo-200px.png 1x, /files/16797/clock-demo-400px.png 2x"> </div> CSS The CSS simply specifies that the image an...
...ss 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); Result In the displayed output below, the selected URL will correspond with whether your display results in selecting the 1x or the 2x version of the image. If you happen to have both standard and high ...
HTMLImageElement.x - Web APIs
<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. ...
...serID</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. ...
HTMLImageElement.y - Web APIs
<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. ...
...serID</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. ...
HTMLLinkElement.rel - Web APIs
The HTMLLinkElement.rel property reflects the rel attribute. It is a DOMString containing a space-separated list of link types indicating the relationship between the resource represented by the <link> element and the current document. The most common use of this attribute is to specify a link to an external style sheet: the property is set to stylesheet, and the href attribute is set to the URL of an external style sheet to format the page. Syntax var relstr = linkElt.rel; linkElt.rel = relstr; Example var links = document.getElementsByTagName('link'); var length = links.length; for (var i = 0; i < length; i++) { alert(links[i]); } Specifications Specification Status Comment HTML Living StandardThe definition of 'rel' in that specification. Living Standa...
...o format the page. Syntax var relstr = linkElt.rel; linkElt.rel = relstr; Example var links = document.getElementsByTagName('link'); var length = links.length; for (var i = 0; i < length; i++) { alert(links[i]); } Specifications Specification Status Comment HTML Living StandardThe definition of 'rel' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'rel' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification Document Object Model (DOM) Level 1 SpecificationThe definition of 'rel' in that specification. Obsolete Initial definition. ...
HTMLLinkElement.relList - Web APIs
The HTMLLinkElement.relList read-only property reflects the rel attribute. It is a live DOMTokenList containing the set of link types indicating the relationship between the resource represented by the <link> element and the current document. The property itself is read-only, meaning you can substitute the DOMTokenList by another one, but the content of the returned list can be changed. ...
...ts the rel attribute. It is a live DOMTokenList containing the set of link types indicating the relationship between the resource represented by the <link> element and the current document. The property itself is read-only, meaning you can substitute the DOMTokenList by another one, but the content of the returned list can be changed. ...
HTMLMediaElement: abort event - Web APIs
The abort event is fired when the resource was not fully loaded, but not as the result of an error. ...
...urce was not fully loaded, but not as the result of an error. ...
HTMLMediaElement: canplay event - Web APIs
Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.oncanplay Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's canplay event, then post a message when that event handler has reacted to the event firing. ...
...s add an event listener for the HTMLMediaElement's canplay event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('canplay', (event) => { console.log('Video can start, but not sure it will play through.'); }); Using the oncanplay event handler property: const video = document.querySelector('video'); video.oncanplay = (event) => { console.log('Video can start, but not sure it will play through.'); }; Specifications Specification Status HTML Living StandardThe definition of 'canplay media event' in that specification. Living Standard HTML5The definition of 'canplay media event' in that specification. Recommendation ...
HTMLMediaElement: canplaythrough event - Web APIs
Event Target Element Default Action None Event handler property GlobalEventHandlers.oncanplaythrough Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's canplaythrough event, then post a message when that event handler has reacted to the event firing. ...
...h event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('canplaythrough', (event) => { console.log('I think I can play through the entire ' + ' video without ever having to stop to buffer.'); }); Using the oncanplaythrough event handler property: const video = document.querySelector('video'); video.oncanplaythrough = (event) => { console.log('I think I can play thru the entire ' + ' video without ever having to stop to buffer.'); }; Specifications Specification Status HTML Living StandardThe definition of 'canplaythrough media event' in that specification. Living Standard HTML5The definition of 'canplaythrough media e...
HTMLMediaElement: durationchange event - Web APIs
Event Target Element Default Action None Event handler property GlobalEventHandlers.ondurationchange Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's durationchange event, then post a message when that event handler has reacted to the event firing. ...
...r the HTMLMediaElement's durationchange event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('durationchange', (event) => { console.log('Not sure why, but the duration of the video has changed.'); }); Using the ondurationchange event handler property: const video = document.querySelector('video'); video.ondurationchange = (event) => { console.log('Not sure why, but the duration of the video has changed.'); }; Specifications Specification Status HTML Living StandardThe definition of 'durationchange media event' in that specification. Living Standard HTML5The definition of 'durationchange media event' in that specification. Rec...
HTMLMediaElement: ended event - Web APIs
None Event handler property GlobalEventHandlers.onended Specification HTML5 media This event is also defined in Media Capture and Streams and Web Audio API Examples These examples add an event listener for the HTMLMediaElement's ended event, then post a message when that event handler has reacted to the event firing. ...
...MLMediaElement's ended event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('ended', (event) => { console.log('Video stopped either because 1) it was over, ' + 'or 2) no further data is available.'); }); Using the onended event handler property: const video = document.querySelector('video'); video.onended = (event) => { console.log('Video stopped either because 1) it was over, ' + 'or 2) no further data is available.'); }; Specifications Specification Status HTML Living StandardThe definition of 'ended media event' in that specification. Living Standard HTML5The definition of 'ended media event' in that specification...
HTMLMediaElement: loadeddata event - Web APIs
rty GlobalEventHandlers.onloadeddata Specification HTML5 media Note that this event will not fire in mobile/tablet devices if data-saver is on in browser settings. Examples These examples add an event listener for the HTMLMediaElement's loadeddata event, then post a message when that event handler has reacted to the event firing. ...
...ddata event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('loadeddata', (event) => { console.log('Yay! The readyState just increased to ' + 'HAVE_CURRENT_DATA or greater for the first time.'); }); Using the onloadeddata event handler property: const video = document.querySelector('video'); video.onloadeddata = (event) => { console.log('Yay! The readyState just increased to ' + 'HAVE_CURRENT_DATA or greater for the first time.'); }; Specifications Specification Status HTML Living StandardThe definition of 'loadeddata media event' in that specification. Living Standard HTML5The definition of 'loadeddata media event'...
HTMLMediaElement: loadedmetadata event - Web APIs
nels. mozSampleRate Read only int The sample rate per second. mozFrameBufferLength Read only int The number of samples collected in all channels. Examples These examples add an event listener for the HTMLMediaElement's loadedmetadata event, then post a message when that event handler has reacted to the event firing. ...
...s loadedmetadata event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('loadedmetadata', (event) => { console.log('The duration and dimensions ' + ' of the media and tracks are now known. '); }); Using the onloadedmetadata event handler property: const video = document.querySelector('video'); video.onloadedmetadata = (event) => { console.log('The duration and dimensions ' + ' of the media and tracks are now known. '); }; Specifications Specification Status HTML Living StandardThe definition of 'loadedmetadata media event' in that specification. Living Standard HTML5The definition of 'canplay media event' in that speci...
HTMLMediaElement: loadstart event - Web APIs
idth: 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; } JS 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.addEventListener('canplay', handleEv...
...'); let source = null; function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}\n`; } video.addEventListener('loadstart', handleEvent); video.addEventListener('progress', handleEvent); video.addEventListener('canplay', handleEvent); video.addEventListener('canplaythrough', handleEvent); loadVideo.addEventListener('click', () => { if (source) { document.location.reload(); } else { loadVideo.textContent = "Reset example"; source = document.createElement('source'); source.setAttribute('src', 'https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm'); source.setAttribute('type', 'video/webm'); video.appendChild(source); } }); Result Specifications Specification Status...
HTMLMediaElement.play() - Web APIs
a possible delay before the returned promise is resolved. Be sure your code doesn't expect an immediate response. For even more in-depth information about autoplay and autoplay blocking, see our article Autoplay guide for media and Web Audio APIs. ...
...solved. Be sure your code doesn't expect an immediate response. For even more in-depth information about autoplay and autoplay blocking, see our article Autoplay guide for media and Web Audio APIs. ...
HTMLMediaElement: playing event - Web APIs
Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onplaying Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's playing event, then post a message when that event handler has reacted to the event firing. ...
... Examples These examples add an event listener for the HTMLMediaElement's playing event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('playing', (event) => { console.log('Video is no longer paused'); }); Using the onplaying event handler property: const video = document.querySelector('video'); video.onplaying = (event) => { console.log('Video is no longer paused.'); }; Specifications Specification Status HTML Living StandardThe definition of 'playing media event' in that specification. Living Standard HTML5The definition of 'playing media event' in that specification. Recommendation ...
HTMLMediaElement: progress event - Web APIs
rem; 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.addEventListener('canplay', handleEv...
...'); let source = null; function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}\n`; } video.addEventListener('loadstart', handleEvent); video.addEventListener('progress', handleEvent); video.addEventListener('canplay', handleEvent); video.addEventListener('canplaythrough', handleEvent); loadVideo.addEventListener('click', () => { if (source) { document.location.reload(); } else { loadVideo.textContent = "Reset example"; source = document.createElement('source'); source.setAttribute('src', 'https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm'); source.setAttribute('type', 'video/webm'); video.appendChild(source); } }); Result Specifications Specification Status...
HTMLMediaElement: ratechange event - Web APIs
terface Event Target Element Default Action None Event handler property GlobalEventHandlers.onratechange Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's ratechange event, then post a message when that event handler has reacted to the event firing. ...
...s These examples add an event listener for the HTMLMediaElement's ratechange event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('ratechange', (event) => { console.log('The playback rate changed.'); }); Using the onratechange event handler property: const video = document.querySelector('video'); video.onratechange = (event) => { console.log('The playback rate changed.'); }; Specifications Specification Status HTML Living StandardThe definition of 'ratechange media event' in that specification. Living Standard HTML5The definition of 'ratechange media event' in that specification. Recommendation ...
HTMLMediaElement: seeked event - Web APIs
Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onseeked Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's seeked event, then post a message when that event handler has reacted to the event firing. ...
...es add an event listener for the HTMLMediaElement's seeked event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('seeked', (event) => { console.log('Video found the playback position it was looking for.'); }); Using the onseeked event handler property: const video = document.querySelector('video'); video.onseeked = (event) => { console.log('Video found the playback position it was looking for.'); }; Specifications Specification Status HTML Living StandardThe definition of 'seeked media event' in that specification. Living Standard HTML5The definition of 'seeked media event' in that specification. Recommendation ...
HTMLMediaElement: seeking event - Web APIs
Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onseeking Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's seeking event, then post a message when that event handler has reacted to the event firing. ...
...ples These examples add an event listener for the HTMLMediaElement's seeking event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('seeking', (event) => { console.log('Video is seeking a new position.'); }); Using the onseeking event handler property: const video = document.querySelector('video'); video.onseeking = (event) => { console.log('Video is seeking a new position.'); }; Specifications Specification Status HTML Living StandardThe definition of 'seeking media event' in that specification. Living Standard HTML5The definition of 'seeking media event' in that specification. Recommendation ...
HTMLMediaElement: stalled event - Web APIs
Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onstalled Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's stalled event, then post a message when that event handler has reacted to the event firing. ...
...les These examples add an event listener for the HTMLMediaElement's stalled event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('stalled', (event) => { console.log('Failed to fetch data, but trying.'); }); Using the onstalled event handler property: const video = document.querySelector('video'); video.onstalled = (event) => { console.log('Failed to fetch data, but trying.'); }; Specifications Specification Status HTML Living StandardThe definition of 'stalled media event' in that specification. Living Standard HTML5The definition of 'stalled media event' in that specification. Recommendation ...
HTMLMediaElement: suspend event - Web APIs
Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onsuspend Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's suspend event, then post a message when that event handler has reacted to the event firing. ...
...ples These examples add an event listener for the HTMLMediaElement's suspend event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('suspend', (event) => { console.log('Data loading has been suspended.'); }); Using the onsuspend event handler property: const video = document.querySelector('video'); video.onsuspend = (event) => { console.log('Data loading has been suspended.'); }; Specifications Specification Status HTML Living StandardThe definition of 'suspend media event' in that specification. Living Standard HTML5The definition of 'suspend media event' in that specification. Recommendation ...
HTMLMediaElement: volumechange event - Web APIs
ace Event Target Element Default Action None Event handler property GlobalEventHandlers.onvolumechange Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's volumechange event, then post a message when that event handler has reacted to the event firing. ...
...es These examples add an event listener for the HTMLMediaElement's volumechange event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('volumechange', (event) => { console.log('The volume changed.'); }); Using the onvolumechange event handler property: const video = document.querySelector('video'); video.onvolumechange = (event) => { console.log('The volume changed.'); }; Specifications Specification Status HTML Living StandardThe definition of 'volumechange media event' in that specification. Living Standard HTML5The definition of 'volumechange media event' in that specification. Recommendation ...
HTMLMediaElement: waiting event - Web APIs
Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onwaiting Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's waiting event, then post a message when that event handler has reacted to the event firing. ...
...mples These examples add an event listener for the HTMLMediaElement's waiting event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('waiting', (event) => { console.log('Video is waiting for more data.'); }); Using the onwaiting event handler property: const video = document.querySelector('video'); video.onwaiting = (event) => { console.log('Video is waiting for more data.'); }; Specifications Specification Status HTML Living StandardThe definition of 'waiting media event' in that specification. Living Standard HTML5The definition of 'waiting media event' in that specification. Recommendation ...
Option() - Web APIs
. Note that a value of true does not set the option to selected if it is not already selected. selected Optional A Boolean that sets the option's selected state; the default is false (not selected). If omitted, even if the defaultSelected argument is true, the option is not selected. ...
...lowing HTML <select id='s'> </select> */ var s = document.getElementById('s'); var options = [Four, Five, Six]; options.forEach(function(element,key) { s[key] = new Option(element,key); }); Append options with different parameters /* assuming we have the following HTML <select id="s"> <option>First</option> <option>Second</option> <option>Third</option> </select> */ var s = document.getElementById('s'); var options = [ 'zero', 'one', 'two' ]; options.forEach(function(element, key) { if (element == 'zero') { s[s.options.length] = new Option(element, s.options.length, false, false); } if (element == 'one') { s[s.options.length] = new Option(element, s.options.length, true, false); // Will add the "selected" attribute } if (element == 'two') { s[s.options...
HTMLOptionElement - Web APIs
e last three values are optional. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLOptionElement' in that specification. Living Standard HTML5The definition of 'HTMLOptionElement' in that specification. Recommendation A constructor, Option(), has been added. The form property can be the null value. ...
...een added. The form property can be the null value. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLOptionElement' in that specification. Obsolete The selected property changed its meaning: it now indicates if the option is currently selected and no longer if it was initally selected. The defaultSelected property is no longer read-only. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLOptionElement' in that specification. Obsolete Initial definition ...
HTMLElement.blur() - Web APIs
MLElement.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 of '...
... Obsolete ...
HTMLOrForeignElement.tabIndex - Web APIs
ort it and assign tabIndex to 0, in the order they appear. Elements that are disabled do not participate in the tabbing order. Values don't need to be sequential, nor must they begin with any particular value. They may even be negative, though each browser trims very large values. Syntax element.tabIndex = index; var index = element.tabIndex; Value index is an integer Example const b1 = document.getElementById('button1'); b1.tabIndex = 1; Specifications Specification Status Comment HTML Living StandardThe definition of 'tabindex' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'tabindex' in that specification.
....tabIndex = 1; Specifications Specification Status Comment HTML Living StandardThe definition of 'tabindex' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'tabindex' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'tabindex' in that specification. Obsolete Initial definition. ...
HTMLOutputElement - Web APIs
defaultValue A DOMString representing the default value of the element, initially the empty string. HTMLOutputElement.formRead only An HTMLFormElement indicating the form associated with the control, reflecting the form HTML attribute if it is defined. HTMLOutputElement.htmlForRead only A DOMTokenList reflecting the for HTML attribute, containing a list of IDs of other elements in the same document that contribute to (or otherwise affect) the calculated value. HTMLOutputElement.labelsRead only A NodeList of <label> elements associated with the element. HTMLOutputElement.name A DOMString reflecting the name HTML attribute, containing the name for the control that is submitted with form data. HTMLOutputElement.typeRead only The DOMString "output". HTMLOutputElement.validationMessageR...
...ns a Boolean holding the check result. HTMLOutputElement.reportValidity() This method reports the problems with the constraints on the element, if any, to the user. If there are problems, fires an invalid event at the element, and returns false; if there are no problems, it returns true. When the problem is reported, the user agent may focus the element and change the scrolling position of the document or perform some other action that brings the element to the user's attention. User agents may report more than one constraint violation if this element suffers from multiple problems at once. If the element is not rendered, then the user agent may report the error for the running script instead of notifying the user. HTMLOutputElement.setCustomValidity() Sets a custom validity message for the e...
HTMLSelectElement.autofocus - Web APIs
The HTMLSelectElement.autofocus property is a Boolean that reflects the autofocus HTML attribute, which indicates whether the associated <select> element will get input focus when the page loads, unless the user overrides it. Only one form-associated element in a document can have this attribute specified. If there are several, the first element with the attribute set inserted, usually the first such element on the page, get the initial focus. Setting this property doesn't set the focus to the associated <select> element: it merely tells the browser to focus to it when the element 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 aSe...
... Living Standard HTML 5.2The definition of 'autofocus' in that specification. ...
HTMLSelectElement.disabled - Web APIs
tElement.disabled = aBool; Example HTML <label> Allow drinks? ...
... Living Standard ...
HTMLSelectElement.remove() - Web APIs
The HTMLSelectElement.remove() method removes the element at the specified index from the options collection for this select element. Syntax collection.remove(index); Parameters index is a long for the index of the HTMLOptionElement to remove from the collection. If the index is not found the method has no effect. ...
... <option value="3">Option: Value 3</option> </select> */ Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLSelectElement.remove()' in that specification. Living Standard HTML5The definition of 'HTMLSelectElement.remove()' in that specification. Recommendation Is a snapshot of HTML Living Standard. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLSelectElement.remove()' in that specification. Obsolete Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLSelectElement.remove()' in that specification. Obsolete Initial definition. ...
HTMLSelectElement.selectedIndex - Web APIs
tiple. The value -1 indicates that no element is selected. ...
...is selected. Syntax var index = selectElem.selectedIndex; selectElem.selectedIndex = index; Example HTML <p id="p">selectedIndex: 0</p> <select id="select"> <option selected>Option A</option> <option>Option B</option> <option>Option C</option> <option>Option D</option> <option>Option E</option> </select> JavaScript var selectElem = document.getElementById('select') var pElem = document.getElementById('p') // When a new <option> is selected selectElem.addEventListener('change', function() { var index = selectElem.selectedIndex; // Add that data to the <p> pElem.innerHTML = 'selectedIndex: ' + index; }) Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLSelectElement' in that specification. Living Standard ...
HTMLStyleElement - Web APIs
esenting the type of style being applied by this statement. HTMLStyleElement.disabled Is a Boolean value representing whether or not the stylesheet is disabled (true) or not (false). LinkStyle.sheet Read only Returns the StyleSheet object associated with the given element, or null if there is none HTMLStyleElement.scoped Is a Boolean value indicating if the element applies to the whole document (false) or only to the parent's sub-tree (true). Methods No specific method; inherits properties from its parent, HTMLElement, and LinkStyle. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLStyleElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLStyleElement' in that specification. ...
... Specification Status Comment HTML Living StandardThe definition of 'HTMLStyleElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLStyleElement' in that specification. Recommendation HTML5The definition of 'HTMLStyleElement' in that specification. Recommendation The following property has been added: scoped. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLStyleElement' in that specification. Obsolete Added a second inheritence, the LinkStyle interface. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLStyleElement' in that specification. Obsolete Initial definition ...
HTMLTableCaptionElement - Web APIs
Methods No specific method; inherits properties from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableCaptionElement' in that specification. Living Standard No change from HTML5. HTML5The definition of 'HTMLTableCaptionElement' in that specification. ...
... Specification Status Comment HTML Living StandardThe definition of 'HTMLTableCaptionElement' in that specification. Living Standard No change from HTML5. HTML5The definition of 'HTMLTableCaptionElement' in that specification. Recommendation No change from Document Object Model (DOM) Level 2 HTML Specification, though align was formerly obsoleted. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLTableCaptionElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLTableCaptionElement' in that specification. Obsolete Initial definition. ...
HTMLTableElement - Web APIs
The HTMLTableElement interface provides special properties and methods (beyond the regular HTMLElement object interface it also has available to it by inheritance) for manipulating the layout and presentation of tables in an HTML document. <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" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" a...
...ue IndexSizeError is raised. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement' in that specification. Living Standard Added the sortable property and the stopSorting() method. HTML5The definition of 'HTMLTableElement' in that specification. Recommendation Added the createTBody() method. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLTableElement' in that specification. Obsolete Defined when caption, tHead, tFoot, insertRow(), and deleteRow() raise exceptions. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLTableElement' in that specification. Obsolete Initial definition. ...
HTMLTableRowElement.rowIndex - Web APIs
s JavaScript to label all the row numbers in a table. ...
... <thead> <tr><th>Item</th> <th>Price</th></tr> </thead> <tbody> <tr><td>Bananas</td> <td>$2</td></tr> <tr><td>Oranges</td> <td>$8</td></tr> <tr><td>Top Sirloin</td> <td>$20</td></tr> </tbody> <tfoot> <tr><td>Total</td> <td>$30</td></tr> </tfoot> </table> JavaScript let rows = document.querySelectorAll('tr'); rows.forEach((row) => { let z = document.createElement("td"); z.textContent = `(row #${row.rowIndex})`; row.appendChild(z); }); Result ...
HTMLTrackElement: cuechange event - Web APIs
rlying TextTrack, indicated by the track property, receives a cuechange event every time the currently-presented cue is changed. This happens even if the track isn't associated with a media element. If the track is associated with a media element, using the <track> element as a child of the <audio> or <video> element, the cuechange event is also sent to the HTMLTrackElement. ...
...ted with a media element, using the <track> element as a child of the <audio> or <video> element, the cuechange event is also sent to the HTMLTrackElement. let textTrackElem = document.getElementById("texttrack"); textTrackElem.addEventListener("cuechange", (event) => { let cues = event.target.track.activeCues; }); In addition, you can use the oncuechange event handler: let textTrackElem = document.getElementById("texttrack"); textTrackElem.oncuechange = (event) => { let cues = event.target.track.activeCues; }); Specifications Specification Status HTML Living StandardThe definition of 'cuechange' in that specification. Living Standard ...
HTMLVideoElement.msHorizontalMirror - Web APIs
VideoElement.msHorizontalMirror: boolean; Value Boolean value set to true flips the video playback horizontally. Video perspective is flipped on a horizontal axis - this may be useful for playback of a webcam video, providing the user with better mirroring of their real behaviors (ie. ...
...e is flipped on a horizontal axis - this may be useful for playback of a webcam video, providing the user with better mirroring of their real behaviors (ie. when user moves left, their representation on-screen would move left as well). ...
Dragging and Dropping Multiple Items - Web APIs
will only work with Gecko based browsers. Mozilla supports the ability to drag multiple items using some additional non-standard methods. These are methods that mirror the types property as well as the getData(), setData() and clearData() methods, however, they take an additional argument that specifies the index of the item to retrieve, modify or remove. The drag processing described in this document use the DataTransfer interface. This processing does not use the DataTransferItem interface nor the DataTransferItemList interface. Setting and getting with indices The mozSetDataAt() method allows you to add multiple items during a dragstart event. This function similarly to setData() var dt = event.dataTransfer; dt.mozSetDataAt("text/plain", "Data to drag", 0); dt.mozSetDataAt("text/plain", ...
... i++) { output(" Item " + i + ":\n"); var types = dt.mozTypesAt(i); for (var t = 0; t < types.length; t++) { output(" " + types[t] + ": "); try { var data = dt.mozGetDataAt(types[t], i); output("(" + (typeof data) + ") : <" + data + " >\n"); } catch (ex) { output("<<error>>\n"); dump(ex); } } } } function output(text) { document.getElementById("output").textContent += text; dump(text); } </script> </head> <body> <div id="output" style="min-height: 100px; white-space: pre; border: 1px solid black;" ondragenter="document.getElementById('output').textContent = ''; event.stopPropagation(); event.preventDefault();" ondragover="event.stopPropagation(); event.preventDefault();" ondrop="event.stopPropagation()...
Recommended Drag Types - Web APIs
Dragging Text For dragging text, use the text/plain type. The second data parameter should be the dragged string. For example: event.dataTransfer.setData("text/plain", "This is text to drag"); Dragging text in textboxes and selections on web pages is done automatically by the browser, so you do not need to handle it yourself. ...
...aAt("image/png", stream, 0); dt.mozSetDataAt("application/x-moz-file", file, 0); dt.setData("text/uri-list", imageurl); dt.setData("text/plain", imageurl); Note the mozGetDataAt() method is used for non-textual data. As some contexts may only include some of these types, it is important to check which type is made available when receiving dropped images. Dragging Nodes Nodes and elements in a document may be dragged using the application/x-moz-node type. The data for the type should be a DOM node. This allows the drop target to receive the actual node where the drag was started from. Note that callers from a different domain will not be able to access the node even when it has been dropped. You should always include a text/plain alternative for the node. Dragging Custom Data You can also us...
IIRFilterNode.getFrequencyResponse() - Web APIs
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 feedforwardCoefficients = [0.1, 0.2, 0.3, 0.4, 0.5]; var feedbackCoefficients = [0.5, 0.4, 0.3, 0.2, 0.1]; var iirFilter = audioCt...
...edforwardCoefficients = [0.1, 0.2, 0.3, 0.4, 0.5]; var feedbackCoefficients = [0.5, 0.4, 0.3, 0.2, 0.1]; var iirFilter = audioCtx.createIIRFilter(feedforwardCoefficients, feedbackCoefficients); ... ...
ImageCapture.getPhotoCapabilities() - Web APIs
s() Return value A Promise that resolves with a PhotoCapabilities object. Example The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from getPhotoCapabilities() to modify the size of an input range. This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
...ure / Photo Resolution Sample, uses the results from getPhotoCapabilities() to modify the size of an input range. This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
ImageCapture.getPhotoSettings() - Web APIs
ean indicating whether the red-eye reduction should be used if it is available. Example The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from getPhotoSettings() to modify the size of an input range. This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
... Capture / Photo Resolution Sample, uses the results from getPhotoSettings() to modify the size of an input range. This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
ImageCapture.grabFrame() - Web APIs
. Syntax const bitmapPromise = imageCapture.grabFrame() Return value A Promise that resolves to an ImageBitmap object. Example This example is extracted from this Simple Image Capture demo. It shows how to use the Promise returned by grabFrame() to copy the returned frame to a <canvas> element. For simplicy it does not show how to instantiate the ImageCapture object. ...
... Return value A Promise that resolves to an ImageBitmap object. Example This example is extracted from this Simple Image Capture demo. It shows how to use the Promise returned by grabFrame() to copy the returned frame to a <canvas> element. For simplicy it does not show how to instantiate the ImageCapture object. ...
ImageCapture.takePhoto() - Web APIs
ting whether the red-eye reduction should be used if it is available. Return value A Promise that resolves with a Blob. Example This example is extracted from this Simple Image Capture demo. It shows how to use the Promise returned by takePhoto() to copy the returned Blob to an <img> element. For simplicy it does not show how to instantiate the ImageCapture object. ...
...s available. Return value A Promise that resolves with a Blob. Example This example is extracted from this Simple Image Capture demo. It shows how to use the Promise returned by takePhoto() to copy the returned Blob to an <img> element. For simplicy it does not show how to instantiate the ImageCapture object. ...
IntersectionObserver.root - Web APIs
The IntersectionObserver interface's read-only root property identifies the Element or Document whose bounds are treated as the bounding box of the viewport for the element which is the observer's target. If the root is null, then the bounds of the actual document viewport are used. Syntax var root = intersectionObserver.root; Value A Element or Document object whose bounding box is used as the bounds of the viewport for the purposes of determining how much of the target element is visible. The intersection of this bounding rectangle, offset by any margins specified in the options passed to the IntersectionObserver() constructor, the target element's bounds, minus the bounds of every element or other object which overlaps the target element, is considered to be the visible area of the target...
...mining how much of the target element is visible. The intersection of this bounding rectangle, offset by any margins specified in the options passed to the IntersectionObserver() constructor, the target element's bounds, minus the bounds of every element or other object which overlaps the target element, is considered to be the visible area of the target element. If root is null, then the owning document is used as the root, and the bounds its viewport (that is, the visible area of the document) are used as the root bounds. Example This example sets the border of the intersection observer's root element to be a 2-pixel medium green line. observer.root.style.border = "2px solid #44aa44"; Specifications Specification Status Comment Intersection ObserverThe definition o...
KeyboardEvent.charCode - Web APIs
ed 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 pressed generates a charac...
...t with keyCode = 229 and no other key events fire until the IME exits (which may happen after multiple characters are inputted). I'm not sure if other IME's work this way. For a list of the charCode values associated with particular keys, run Example 7: Displaying Event Object Properties and view the resulting HTML table. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'KeyboardEvent.charCode' in that specification. Obsolete Initial definition; specified as deprecated ...
KeyboardEvent.key - Web APIs
Web › API › KeyboardEvent › key
"> <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]`); else logMessage...
...Do something for "esc" key press. break; default: return; // Quit when this doesn't handle the key event. } // Cancel the default action to avoid it being handled twice event.preventDefault(); }, true); Specification Specification Status Comment UI EventsThe definition of 'KeyboardEvent.key' in that specification. Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'KeyboardEvent.key' in that specification. Obsolete Initial definition, included key values. ...
KeyframeEffect.target - Web APIs
The target property of a KeyframeEffect interface represents the element or pseudo-element being animated. It may be null for animations that do not target a specific element. It performs as both a getter and a setter, except with animations and transitions generated by CSS. ...
...ById("elementToAnimate"); var keyframes = new KeyframeEffect( targetElement, keyframeBlock, timingOptions ); // returns #elementToAnimate keyframes.target; // assigns keyframes a new target keyframes.target = newTargetElement; Value An Element, CSSPseudoElement, or null. ...
LocalFileSystemSync - Web APIs
This specification is more or less abandonned, failing to get significant traction. Basic concepts You can request access to a sandboxed file system by requesting LocalFileSystemSync object from within a web worker. ...
... This specification is more or less abandonned, failing to get significant traction. Basic concepts You can request access to a sandboxed file system by requesting LocalFileSystemSync object from within a web worker. ...
Location: toString() - Web APIs
Web › API › Location › toString
The toString() stringifier method of the Location interface returns a USVString containing the whole URL. It is a read-only version of Location.href. ...
... The toString() stringifier method of the Location interface returns a USVString containing the whole URL. It is a read-only version of Location.href. ...
MSCandidateWindowShow - Web APIs
tions need only register for this event once per element (the handler will remain valid for the lifetime of the element). ...
...andidateWindowClientRect() function to find out where the candidate window is and position the suggestion UI away from it: var context = document.getElementById("mySearchBox").msGetInputContext(); context.addEventListener("MSCandidateWindowShow", candidateWindowShowHandler); function candidateWindowShowHandler(e) { var imeRect = context.getCandidateWindowClientRect(); var suggestionRect = document.getElementById("mySuggestionList").getBoundingClientRect(); // Check if the two rects intersect, and position them away from each other. } When the IME candidate window changes position or closes, it fires MSCandidateWindowUpdate or MSCandidateWindowHide events. Developers could listen to them and shift the suggestion UI accordingly. See also Microsoft API extensions IME handling guid...
MediaDevices.getSupportedConstraints() - Web APIs
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. ...
... Candidate Recommendation Initial definition. ...
MediaDevices - Web APIs
ring or recording purposes. Returns a promise that resolves to a MediaStream. getUserMedia() With the user's permission through a prompt, turns on a camera and/or a microphone on the system and provides a MediaStream containing a video track and/or an audio track with the input. Example 'use strict'; // Put variables in global scope to make them available to the browser console. ...
...ugh a prompt, turns on a camera and/or a microphone on the system and provides a MediaStream containing a video track and/or an audio track with the input. Example 'use strict'; // Put variables in global scope to make them available to the browser console. ...
MediaList.mediaText - Web APIs
face is a stringifier that returns a DOMString representing the MediaList as text, and also allows you to set a new MediaList. Syntax mediaListInstance.mediaText; mediaListInstance.mediaText = string; Value A DOMString representing the media queries of a stylesheet. Each one is separated by a comma, for example screen and (min-width: 480px), print. If you wish to set new media queries on the document, the string value must have the different queries separated by commas, e.g. screen, print. Note that the MediaList is a live list; updating the list via mediaText will immediately update the behavior of the document. Also note that is you try to set mediaText to null, it will be treated as an empty string, i.e. the value will be set to "". Examples The following would log to the console a text...
..., print. Note that the MediaList is a live list; updating the list via mediaText will immediately update the behavior of the document. Also note that is you try to set mediaText to null, it will be treated as an empty string, i.e. the value will be set to "". Examples The following would log to the console a textual representation of the MediaList of the first stylesheet applied to the current document. const stylesheets = document.styleSheets; let stylesheet = stylesheets[0]; console.log(stylesheet.media.mediaText); Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'mediaText' in that specification. Working Draft ...
MediaList - Web APIs
Web › API › MediaList
Properties MediaList.mediaText A stringifier that returns a DOMString representing the MediaList as text, and also allows you to set a new MediaList. MediaList.length Read only Returns the number of media queries in the MediaList. ...
...m() Adds a media query to the MediaList. MediaList.deleteMedium() Removes a media query from the MediaList. MediaList.item() A getter that returns a CSSOMString representing a media query as text, given the media query's index value inside the MediaList. Examples The following would log to the console a textual representation of the MediaList of the first stylesheet applied to the current document. const stylesheets = document.styleSheets; let stylesheet = stylesheets[0]; console.log(stylesheet.media.mediaText); Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'MediaList' in that specification. Working Draft ...
MediaQueryList.removeListener() - Web APIs
ndard MediaQueryListListener object. In the new implementation the standard event mechanism is used, and the callback is a standard function. Return value Void. ...
... Working Draft Initial definition ...
MediaQueryListEvent.media - Web APIs
ce is a DOMString representing a serialized media query. Syntax var media = MediaQueryListEvent.media; Value A DOMString representing a serialized media query. ...
... Working Draft Initial definition ...
MediaQueryListListener - Web APIs
This makes it possible to observe a document to detect when its media queries change, instead of polling the values periodically, if you need to detect changes to the values of media queries on a document. ...
... This feature is outdated. The MediaQueryList.addListener() callback is now a plain function and called with the standard MediaQueryListEvent object. A MediaQueryList object maintains a list of media queries on a Document, and handles sending notifications to listeners when the media queries on the document change. This makes it possible to observe a document to detect when its media queries change, instead of polling the values periodically, if you need to detect changes to the values of media queries on a document. A MediaQueryListListener is a callback function that gets invoked with a single argument, the MediaQueryList for which the evaluated result changed. Syntax function( mediaQueryList ) { ... } Parameters mediaQueryList The MediaQueryList instance. Specifications ...
MediaSettingsRange - Web APIs
f this settings. MediaSettingsRange.min Returns the minimum value of this setting. MediaSettingsRange.step Returns the minimum difference between consecutive values of this setting. Example The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from getPhotoCapabilities().imageWidth to modify the size of an input range. ...
...etween consecutive values of this setting. Example The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from getPhotoCapabilities().imageWidth to modify the size of an input range. ...
MediaStreamConstraints.audio - Web APIs
g"></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 + ": " + err.message)); }, false); Here w...
...g"></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.srcObject = stream) .catch(err => lo...
MediaStreamConstraints.video - Web APIs
<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 + ": " + err.message)); }, false); Here...
...<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 => videoElement.srcObject = stream) ...
MediaStreamTrack: ended event - Web APIs
data to be sent. The hardware generating the source data has been removed or ejected. A remote peer has permanently stopped sending data; pausing media does not generate an ended event. Examples This example sets up an event handler for the ended event, which changes an on-screen icon to indicate that the track is no longer active. ...
...n event handler for the ended event, which changes an on-screen icon to indicate that the track is no longer active. track.addEventListener('ended', () => { let statusElem = document.getElementById("status-icon"); statusElem.src = "/images/stopped-icon.png"; }) You can also set up the event handler using the MediaStreamTrack.onended property: track.onended = function() { let statusElem = document.getElementById("status-icon"); statusElem.src = "/images/stopped-icon.png"; } Specifications Specification Status Comment Media Capture and StreamsThe definition of 'ended' in that specification. Candidate Recommendation Initial specification. ...
MediaStreamTrack: mute event - Web APIs
e are no events. Bubbles No Cancelable No Interface Event Event handler property onmute Examples In this example, event handlers are established for the mute and unmute events in order to detect when the media is not flowing from the source for the MediaStreamTrack referenced by musicTrack. musicTrack.addEventListener("mute", event => { document.getElementById("timeline-widget").style.backgroundColor = "#aaa"; }, false); musicTrack.addEventListener("unmute", event => { document.getElementById("timeline-widget").style.backgroundColor = "#fff"; }, false); With these event handlers in place, when the track musicTrack enters its muted state, the element with the ID timeline-widget gets its background color changed to #aaa. When the track...
...lor changed to #aaa. When the track exits the muted state--detected by the arrival of an unmute event--the background color is restored to white. You can also use the onmute event handler property to set up a handler for this event; similarly, the onunmute event handler is available for setting up a handler for the unmute event. The following example shows this: musicTrack.onmute = event => { document.getElementById("timeline-widget").style.backgroundColor = "#aaa"; } musicTrack.mute = event = > { document.getElementById("timeline-widget").style.backgroundColor = "#fff"; } Specifications Specification Status Comment Media Capture and StreamsThe definition of 'mute' in that specification. Candidate Recommendation Initial specification. ...
MediaStreamTrack: unmute event - Web APIs
-controllable way to silence a track) is actually managed using the MediaStreamTrack.enabled property, for which there are no events. Examples In this example, event handlers are established for the mute and unmute events in order to detect when the media is not flowing from the source for the MediaStreamTrack stored in the variable musicTrack. musicTrack.addEventListener("mute", event => { document.getElementById("timeline-widget").style.backgroundColor = "#aaa"; }, false); musicTrack.addEventListener("unmute", event => { document.getElementById("timeline-widget").style.backgroundColor = "#fff"; }, false); With these event handlers in place, when the track musicTrack enters its muted state, the element with the ID timeline-widget gets its background color changed to #aaa. When the track...
...olor changed to #aaa. When the track exits the muted state--detected by the arrival of an unmuted event--the background color is restored to white. You can also use the onunmute event handler property to set up a handler for this event; similarly, the onmute event handler is available for setting up a handler for the mute event. The following example shows this: musicTrack.onmute = event => { document.getElementById("timeline-widget").style.backgroundColor = "#aaa"; } musicTrack.mute = event = > { document.getElementById("timeline-widget").style.backgroundColor = "#fff"; } Specifications Specification Status Comment Media Capture and StreamsThe definition of 'unmute' in that specification. Candidate Recommendation Initial specification. ...
MediaStreamTrack - Web APIs
bled to false. The muted property refers to a condition in which there's no media because of a technical issue. MediaStreamTrack.id Read only Returns a DOMString containing a unique identifier (GUID) for the track; it is generated by the browser. MediaStreamTrack.isolated Read only Returns a Boolean value which is true if the track is isolated; that is, the track cannot be accessed by the document that owns the MediaStreamTrack. This happens when the peerIdentity property is set, or if the track comes from a cross-origin source. MediaStreamTrack.kind Read only Returns a DOMString set to "audio" if the track is an audio track and to "video", if it is a video track. It doesn't change if the track is deassociated from its source. MediaStreamTrack.label Read only Returns a DOMString cont...
...e onended event handler property. mute Sent to the MediaStreamTrack when the value of the muted property is changed to true, indicating that the track is unable to provide data temporarily (such as when the network is experiencing a service malfunction). Also available using the onmute event handler property. isolationchange Sent whenever the value of the isolated property changes due to the document gaining or losing permission to access the track. Also available through the onisolationchange event handler property. overconstrained Sent when the constraints specified for the track cause the track to be incompatible and therefore to not be used. Also available through the onoverconstrained event handler property. unmute Sent to the track when data becomes available again, ending the m...
Recording a media element - Web APIs
ft; width: 160px; padding: 0px; } .right { margin-left: 10px; float: left; width: 160px; padding: 0px; } .bottom { clear: both; padding-top: 10px; } JavaScript content Now let's have a look at the JavaScript code; this is where the majority of the action happens, after all! Setting up global variables We start by establishing some global variables we'll need. ...
...rgin-left: 10px; float: left; width: 160px; padding: 0px; } .bottom { clear: both; padding-top: 10px; } JavaScript content Now let's have a look at the JavaScript code; this is where the majority of the action happens, after all! Setting up global variables We start by establishing some global variables we'll need. let preview = document.getElementById("preview"); let recording = document.getElementById("recording"); let startButton = document.getElementById("startButton"); let stopButton = document.getElementById("stopButton"); let downloadButton = document.getElementById("downloadButton"); let logElement = document.getElementById("log"); let recordingTimeMS = 5000; Most of these are references to elements we need to work with. The last, recordingTimeMS, is set to 5000 millise...
MessageChannel() - Web APIs
essageChannel constructor. When the IFrame has loaded, we pass port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. ...
...me has loaded, we pass port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. ...
MessageChannel.port1 - Web APIs
iframe> has loaded, we pass MessageChannel.port2 to the <iframe> using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the <iframe> (using MessagePort.onmessage), putting it into a paragraph. The handleMessage method is associated to the port1 to listen when the message arrives. ...
...el.port2 to the <iframe> using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the <iframe> (using MessagePort.onmessage), putting it into a paragraph. The handleMessage method is associated to the port1 to listen when the message arrives. ...
MessageChannel.port2 - Web APIs
essageChannel constructor. When the IFrame has loaded, we pass port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. ...
...me has loaded, we pass port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. ...
MessageChannel - Web APIs
sageChannel.MessageChannel constructor. When the IFrame has loaded, we register an onmessage handler for MessageChannel.port1 and transfer MessageChannel.port2 to the IFrame using the window.postMessage method along with a message. When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph. ...
...e IFrame has loaded, we register an onmessage handler for MessageChannel.port1 and transfer MessageChannel.port2 to the IFrame using the window.postMessage method along with a message. When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph. ...
MessagePort.onmessage - Web APIs
ageChannel constructor. When the IFrame has loaded, we pass MessageChannel.port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame using onmessage, putting it into a paragraph -- MessageChannel.port1 is listened to, to check when the message arrives. ...
...has loaded, we pass MessageChannel.port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame using onmessage, putting it into a paragraph -- MessageChannel.port1 is listened to, to check when the message arrives. ...
MessagePort.postMessage() - Web APIs
.MessageChannel constructor. When the IFrame has loaded, we pass MessageChannel.port2 to the IFrame using window.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame using onmessage, putting it into a paragraph -- MessageChannel.port1 is listened to, to check when the message arrives. ...
...rame has loaded, we pass MessageChannel.port2 to the IFrame using window.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame using onmessage, putting it into a paragraph -- MessageChannel.port1 is listened to, to check when the message arrives. ...
MessagePort.start() - Web APIs
Web › API › MessagePort › start
tarts the sending of messages queued on the port. This method is only needed when using EventTarget.addEventListener; it is implied when using MessageChannel.onmessage. Note: This feature is available in Web Workers. Syntax port.start() Returns Void. Parameters None. ...
... Living Standard ...
MessagePort - Web APIs
using the MessageChannel() constructor. When the IFrame has loaded, we register an onmessage handler for MessageChannel.port1 and transfer MessageChannel.port2 to the IFrame using the window.postMessage method along with a message. When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph. ...
...he IFrame has loaded, we register an onmessage handler for MessageChannel.port1 and transfer MessageChannel.port2 to the IFrame using the window.postMessage method along with a message. When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph. ...
MouseEvent.altKey - Web APIs
Web › API › MouseEvent › altKey
lso 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 Document Object Model ...
...ener('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 Document Object Model (DOM) Level 2 Events Specification. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'MouseEvent.altkey' in that specification. Obsolete Initial definition. ...
MouseEvent.buttons - Web APIs
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. ...
...owser Forward" button) Example This example logs the buttons property when you trigger a mousedown event. HTML <p>Click anywhere with one or more mouse buttons.</p> <pre id="log">buttons: </pre> JavaScript let log = document.createTextNode('?'); // let log = new Text('?'); function logButtons(e) { log.data = `${e.buttons} (${e.type})`; // log.nodeValue= `${e.buttons} (${e.type})`; } document.addEventListener('mouseup', logButtons); document.addEventListener('mousedown', logButtons); // document.addEventListener('mousemove', logButtons); document.querySelector('#log').appendChild(log) Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.buttons' in that specification. O...
MouseEvent.clientX - Web APIs
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. HTML <p>Move your mouse to see its position.</p> <p id="screen-log"></p> JavaScript let screenLog = document.querySelector('#screen-log'); document.addEventListener('mousemove', logKey); function logKey(e) { screenLog.innerText = ` Screen X/Y: ${e.screenX}, ${e.screenY} Client X/Y: ${e.clientX}, ${e.clientY}`; } Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'clientX' in that specification. Working Draft...
...r('mousemove', logKey); function logKey(e) { screenLog.innerText = ` Screen X/Y: ${e.screenX}, ${e.screenY} Client X/Y: ${e.clientX}, ${e.clientY}`; } Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'clientX' in that specification. Working Draft Redefines MouseEvent from long to double. Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.clientX' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Events Specification. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'MouseEvent.clientX' in that specification. Obsolete Initial definition. ...
MouseEvent.clientY - Web APIs
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. HTML <p>Move your mouse to see its position.</p> <p id="screen-log"></p> JavaScript let screenLog = document.querySelector('#screen-log'); document.addEventListener('mousemove', logKey); function logKey(e) { screenLog.innerText = ` Screen X/Y: ${e.screenX}, ${e.screenY} Client X/Y: ${e.clientX}, ${e.clientY}`; } Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'clientY' in that specification. Working Draft...
...r('mousemove', logKey); function logKey(e) { screenLog.innerText = ` Screen X/Y: ${e.screenX}, ${e.screenY} Client X/Y: ${e.clientX}, ${e.clientY}`; } Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'clientY' in that specification. Working Draft Redefines MouseEvent from long to double. Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.clientY' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Events Specification. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'MouseEvent.clientY' in that specification. Obsolete Initial definition. ...
MouseEvent.ctrlKey - Web APIs
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 Document Object Mod...
...r('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 Document Object Model (DOM) Level 2 Events Specification. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'MouseEvent.ctrlKey' in that specification. Obsolete Initial definition. ...
MouseEvent.getModifierState() - Web APIs
Syntax var active = event.getModifierState(keyArg); Returns A Boolean Parameters keyArg A modifier key value. The value must be one of the KeyboardEvent.key values which represent modifier keys or "Accel". This is case-sensitive. ...
...d), otherwise, false. See the document of KeyboardEvent.getModifierState() for details. Syntax var active = event.getModifierState(keyArg); Returns A Boolean Parameters keyArg A modifier key value. The value must be one of the KeyboardEvent.key values which represent modifier keys or "Accel". This is case-sensitive. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'getModifierState()' in that specification. Obsolete Initial definition. ...
MouseEvent.metaKey - Web APIs
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 Document Object Mod...
...r('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 Document Object Model (DOM) Level 2 Events Specification. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'MouseEvent.metaKey' in that specification. Obsolete Initial definition. ...
MouseEvent.screenY - Web APIs
screenY Return value A double floating point value. Early versions of the spec defined this as an integer referring to the number of pixels. See the "Browser compatibility" section for details. Example This example displays your mouse's coordinates whenever you trigger the mousemove event. HTML <p>Move your mouse to see its position.</p> <p id="screen-log"></p> JavaScript let screenLog = document.querySelector('#screen-log'); document.addEventListener('mousemove', logKey); function logKey(e) { screenLog.innerText = ` Screen X/Y: ${e.screenX}, ${e.screenY} Client X/Y: ${e.clientX}, ${e.clientY}`; } Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'screenY' in that specification. Working Draft...
...r('mousemove', logKey); function logKey(e) { screenLog.innerText = ` Screen X/Y: ${e.screenX}, ${e.screenY} Client X/Y: ${e.clientX}, ${e.clientY}`; } Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'screenY' in that specification. Working Draft Redefines MouseEvent from long to double. Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.screenY' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Events Specification. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'MouseEvent.sceenY' in that specification. Obsolete Initial definition ...
MouseEvent.shiftKey - Web APIs
n mouse event occurs. Syntax var shiftKeyPressed = instanceOfMouseEvent.shiftKey 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 shiftKey property when you trigger a click event. HTML <p>Click anywhere to test the <code>shiftKey</code> property.</p> <p id="log"></p> JavaScript let log = document.querySelector('#log'); document.addEventListener('click', logKey); function logKey(e) { log.textContent = `The shift key is pressed: ${e.shiftKey}`; } Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.shiftKey' in that specification. Obsolete No change from Document Object ...
...click', logKey); function logKey(e) { log.textContent = `The shift key is pressed: ${e.shiftKey}`; } Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.shiftKey' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Events Specification. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'MouseEvent.shiftKey' in that specification. Obsolete Initial definition. ...
msPlayToPreferredSourceUri - Web APIs
ted, instead of streaming content from the Windows machine which must be unprotected content. A forward slash ("/") is appended to the URI string when it is sent over the network to a PlayTo device. This is done to conform to URI standards. ...
...rom the Windows machine which must be unprotected content. A forward slash ("/") is appended to the URI string when it is sent over the network to a PlayTo device. This is done to conform to URI standards. Example <video src="http://www.contoso.com/videos/video.mp4" msPlayToPreferredSourceUri="http://www.contoso.com/catalogid=1234" /> var video = document.createElement('video'); document.body.appendChild(video); video.src = "http://www.contoso.com/videos/video.mp4"; video.msPlayToPreferredSourceUri = "http://www.contoso.com/catalogid=1234"; See also Microsoft PlayReady content access and protection technology is a set of technologies that can be used to distribute audio/video content more securely over a network, and help prevent the unauthorized use of this content. ...
MutationObserver.takeRecords() - Web APIs
n use case for this is to immediately fetch all pending mutation records immediately prior to disconnecting the observer, so that any pending mutations can be processed when stopping down the observer. Syntax const mutationRecords = mutationObserver.takeRecords() Parameters None. ...
...escribing one change applied to the observed portion of the document's DOM tree. Note: The queue of mutations which have occurred, but not been delivered to the observer's callback is left empty after calling takeRecords(). Example In this example, we demonstrate how to handle any undelivered MutationRecords by calling takeRecords() just before disconnecting the observer. const targetNode = document.querySelector("#someElement"); const observerOptions = { childList: true, attributes: true } const observer = new MutationObserver(callback); observer.observe(targetNode, observerOptions); /* ...later, when it's time to stop observing... */ /* handle any still-pending mutations */ let mutations = observer.takeRecords(); observer.disconnect(); if (mutations) { callback(mutations); } ...
Using Navigation Timing - Web APIs
experiences. Collecting timing information Using the API is as simple as obtaining the Performance object using window.performance and looking up what you need within the object returned. For example, to measure the perceived loading time for a page: window.addEventListener("load", function() { let now = new Date().getTime(); let loadingTime = now - performance.timing.navigationStart; document.querySelector(".output").innerText = loadingTime + " ms"; }, false); This code, executed when the load event occurs, subtracts from the current time the time at which the navigation whose timing was recorded began (performance.timing.navigationStart), and outputs that information to the screen by inserting it into an element. HTML <div class="output"> </div> CSS .output { border: ...
...performance.navigation.type indicates what kind of load operation took place: a navigation, a reload, or a shift through the browser's history. We also obtain the number of redirects that were incurred during the navigation from performance.nav...
Navigator.getBattery() - Web APIs
Note: In some browsers access to this feature is controlled by Feature-Policy directive battery. ...
...e name is one of the following: SecurityError The User Agent does not expose battery information to insecure contexts and this method was called from insecure context. Note: Old versions of some User Agents might allow use of this feature in insecure contexts. NotAllowedError Note: No User Agent currently throws this exception, but the specification describes the following behaviors: This document is not allowed to use this feature. For example, it might not be explicitly allowed or restricted via Feature-Policy battery feature. Example This example fetches the current charging state of the battery and establishes a handler for the chargingchange event, so that the charging state is recorded whenever it changes. let batteryIsCharging = false; navigator.getBattery().then(function(batte...
Navigator.getUserMedia() - Web APIs
lities, constraints, and settings. successCallback A function which is invoked when the request for media access is approved. The function is called with one parameter: the MediaStream object that contains the media stream. Your callback can then assign the stream to the desired object (such as an <audio> or <video> element), as shown in the following example: function(stream) { var video = document.querySelector('video'); video.srcObject = stream; video.onloadedmetadata = function(e) { // Do something with the video here. }; } errorCallback When the call fails, the function specified in the errorCallback is invokedwith a MediaStreamError object as its sole argument; this object is is modeled on DOMException. See {anch("Errors")}} below for a list of the errors which can o...
...e the Examples section under the MediaDevices.getUserMedia() for modern examples. ...
Navigator.mediaSession - Web APIs
This information may, in turn, be shared with the device and/or operating system in order to a device's standard media control user experience to describe and control the playback of the media. ...
...ts when the user engages device controls such as either onscreen or physical play, pause, seek, and other similar controls. An internet radio app, for example, can use setActionHandler() to let fhe media controls on a keyboard or elsehwere on the user's device be used to control the app's media playback. Syntax let mediaSession = navigator.mediaSession; Value A MediaSession object the current document can use to share information about media it's playing and its current playback status. This information can include typical metadata such as the title, artist, and album name of the song being played as well as potentially one or more images containing things like album art, artist photos, and so forth. Example In this example, metadata is submitted to the mediaSession object. Note that the cod...
Navigator.sendBeacon() - Web APIs
he data. Can be relative or absolute. data A ArrayBuffer, ArrayBufferView, Blob, DOMString, FormData, or URLSearchParams object containing the data to send. Return values The sendBeacon() method returns true if the user agent successfully queued the data for transfer. Otherwise, it returns false. Description This method is for analytics and diagnostics that send data to a server before the document is unloaded, where sending the data any sooner may miss some possible data collection. For example, which link the user clicked before navigating away and unloading the page. Ensuring that data has been sent during the unloading of a document has traditionally been difficult, because user agents typically ignore asynchronous XMLHttpRequests made in an unload handler. Historically, this was addr...
...page unload long enough to send data to some URL: Submitting the data with a blocking synchronous XMLHttpRequest call in unload or beforeunload event handlers. Creating an <img> element and setting its src in the unload handler. Most user agents will delay the unload to load the image. Creating a no-op loop for several seconds in the unload handler. All of these methods block unloading the document, which slows down the next navigation. There is nothing the next page can do to avoid this, so the new page seems slow, even though it's the previous page's fault. The following example shows theoretical analytics code that attempts to submit data to a server with a synchronous XMLHttpRequest in an unload handler. This results in the next page load to be delayed. window.addEventListener("unload...
Navigator.share() - Web APIs
Web › API › Navigator › share
e data parameter is not correctly specified, and will also reject if the user cancels sharing. Examples In our Web share test (see the source code) there is a button which, when clicked, invokes the Web Share API to share MDN's URL. ...
... also reject if the user cancels sharing. Examples In our Web share test (see the source code) there is a button which, when clicked, invokes the Web Share API to share MDN's URL. The JavaScript looks like this: const shareData = { title: 'MDN', text: 'Learn web development on MDN!', url: 'https://developer.mozilla.org', } const btn = document.querySelector('button'); const resultPara = document.querySelector('.result'); // Must be triggered some kind of "user activation" btn.addEventListener('click', async () => { try { await navigator.share(shareData) resultPara.textContent = 'MDN shared successfully' } catch(err) { resultPara.textContent = 'Error: ' + err } }); Sharing Files To share files, first test for and call navigator.canShare(). Then include an array of fil...
Navigator - Web APIs
Web › API › Navigator
Returns a PluginArray listing the plugins installed in the browser. NavigatorID.product Read only Always returns 'Gecko', on any browser. This property is kept only for compatibility purpose. Navigator.serviceWorker Read only Returns a ServiceWorkerContainer object, which provides access to registration, removal, upgrade, and communication with the ServiceWorker objects for the associated document. NavigatorStorage.storage Read only Returns the singleton StorageManager object used for managing persistence permissions and estimating available storage on a site-by-site/app-by-app basis. NavigatorID.userAgent Read only Returns the user agent string for the current browser. Navigator.xr Read only Returns XR object, which represents the entry point into the WebXR API. Non-standard ...
...nism of the current platform. NavigatorID.taintEnabled() Deprecated since Gecko 1.7.8 Obsolete since Gecko 9.0 Returns false. JavaScript taint/untaint functions removed in JavaScript 1.2. Navigator.vibrate() Causes vibration on devices with support for it. Does nothing if vibration support isn't available. Non-standard Navigator.mozIsLocallyAvailable() Lets code check to see if the document at a given URI is available without using the network. Specifications Specification Status Comment HTML Living StandardThe definition of 'the Navigator object' in that specification. Living Standard ...
NavigatorPlugins.plugins - Web APIs
'Shockwave Flash'); if (typeof flash != 'object') { // flash is not present return undefined; } if(flash.version){ return flash.version; } else { //No version property (e.g. in Chrome) return flash.description.replace(/Shockwave Flash /,""); } } The following example displays information about the installed plugin(s). ...
...cription.replace(/Shockwave Flash /,""); } } The following example displays information about the installed plugin(s). ...
Node.childNodes - Web APIs
Web › API › Node › childNodes
m a node // box is an object reference to an element while (box.firstChild) { //The list is LIVE so it will re-index each call box.removeChild(box.firstChild); } Notes The items in the collection of nodes are objects, not strings. To get data from node objects, use their properties. (For example, to get the name of the first childNode: elementNodeReference.childNodes[1].nodeName.) The document object itself has 2 children: the Doctype declaration and the root element, typically referred to as documentElement. (In (X)HTML documents this is the HTML element.) childNodes includes all child nodes--including non-element nodes like text and comment nodes. To get a collection of only elements, use ParentNode.children instead. Specifications Specification Status Comment ...
...lement. (In (X)HTML documents this is the HTML element.) childNodes includes all child nodes--including non-element nodes like text and comment nodes. To get a collection of only elements, use ParentNode.children instead. Specifications Specification Status Comment DOMThe definition of 'Node.childNodes' in that specification. Living Standard No change Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.childNodes' in that specification. Obsolete No change Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Node.childNodes' in that specification. Obsolete No change Document Object Model (DOM) Level 1 SpecificationThe definition of 'Node.childNodes' in that specification. Obs...
Node.isEqualNode() - Web APIs
Web › API › Node › isEqualNode
en we run some JavaScript to compare the nodes using isEqualNode() and output the results. ...
...ng isEqualNode() and output the results. ...
Node.lastChild - Web APIs
Web › API › Node › lastChild
The Node.lastChild read-only property returns the last child of the node. If its parent is an element, then the child is generally an element node, a text node, or a comment node. It returns null if there are no child elements. Syntax var childNode = node.lastChild; Example var tr = document.getElementById("row1"); var corner_td = tr.lastChild; Specifications Specification Status Comment DOMThe definition of 'Node.lastChild' in that specification. Living Standard No change Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.lastChild' in that specification. Obsolete No change Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Node.lastChild' in that specification. Obsolete No ch...
... DOMThe definition of 'Node.lastChild' in that specification. Living Standard No change Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.lastChild' in that specification. Obsolete No change Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Node.lastChild' in that specification. Obsolete No change Document Object Model (DOM) Level 1 SpecificationThe definition of 'Node.lastChild' in that specification. Obsolete Initial definition ...
Node.nodeValue - Web APIs
Web › API › Node › nodeValue
For text, comment, and CDATA nodes, nodeValue returns the content of the node. For attribute nodes, the value of the attribute is returned. ...
...ocument itself, nodeValue returns null. For text, comment, and CDATA nodes, nodeValue returns the content of the node. For attribute nodes, the value of the attribute is returned. The following table shows the return values for different elements: Node Value of nodeValue CDATASection Content of the CDATA section Comment Content of the comment Document null DocumentFragment null DocumentType null Element null NamedNodeMap null EntityReference null Notation null ProcessingInstruction Entire content excluding the target Text Content of the text node When nodeValue is defined to be null, setting it has no effect. Specifications Spec...
NodeIterator.expandEntityReferences - Web APIs
dicating whether or not the children of entity reference nodes are visible to the NodeIterator. If this value is false, the children of entity reference nodes (as well as all of their descendants) are rejected. This takes precedence over the value of the NodeIterator.whatToShow method and the associated filter. ...
...ren of entity reference nodes are visible to the NodeIterator. If this value is false, the children of entity reference nodes (as well as all of their descendants) are rejected. This takes precedence over the value of the NodeIterator.whatToShow method and the associated filter. Syntax expand = nodeIterator.expandEntityReferences; Example var nodeIterator = document.createNodeIterator( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); expand = nodeIterator.expandEntityReferences; Specifications Specification Status Comment Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'NodeIterator.expandEntityReferences' in that specification. Obsolete ...
NodeIterator.filter - Web APIs
sed in as the third parameter, and the object method acceptNode(node) is called on every single node to determine whether or not to accept it. This function should return the constant NodeFilter.FILTER_ACCEPT for cases when the node should be accepted and NodeFilter.FILTER_REJECT for cases when the node should be rejected. Syntax nodeFilter = nodeIterator.filter; Example const nodeIterator = document.createNodeIterator( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); nodeFilter = nodeIterator.filter; Specifications Specification Status Comment DOMThe definition of 'NodeIterator.filter' in that specification. Living Standard No change from Document Object Model (DOM) Level ...
... Obsolete Initial definition. ...
NodeList.length - Web APIs
Web › API › NodeList › length
s the number of items in a NodeList. Syntax numItems = nodeList.length numItems is an integer value representing the number of items in a NodeList. Example The length property is often useful in DOM programming. It's often used to test the length of a list, to see if it exists at all. It's also commonly used as the iterator in a for loop, as in this example. ...
... in a NodeList. Syntax numItems = nodeList.length numItems is an integer value representing the number of items in a NodeList. Example The length property is often useful in DOM programming. It's often used to test the length of a list, to see if it exists at all. It's also commonly used as the iterator in a for loop, as in this example. // All the paragraphs in the document var items = document.getElementsByTagName("p"); // For each item in the list, // append the entire element as a string of HTML var gross = ""; for (var i = 0; i < items.length; i++) { gross += items[i].innerHTML; } // gross is now all the HTML for the paragraphs Specifications Specification Status Comment DOMThe definition of 'NodeList: length' in that specification. Living Stand...
Notation - Web APIs
Web › API › Notation
Inherits methods and properties from Node. Its nodeName is the notation name. Has no parent. Properties Notation.publicId Read only Is a DOMString. Notation.systemId Read only Is a DOMString. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Notation' in that specification. Obsolete No change Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Notation' in that specification. ...
...hods and properties from Node. Its nodeName is the notation name. Has no parent. Properties Notation.publicId Read only Is a DOMString. Notation.systemId Read only Is a DOMString. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Notation' in that specification. Obsolete No change Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Notation' in that specification. Obsolete No change Document Object Model (DOM) Level 1 SpecificationThe definition of 'Notation' in that specification. Obsolete Initial definition ...
Using the Notifications API - Web APIs
s it's up to the user and user agent. The dismissal may also happen at the operating system level and users should remain in control of this. Old versions of Chrome didn't remove notifications automatically so you can do so after a setTimeout() only for those legacy versions in order to not remove notifications from notification trays on other browsers. var n = new Notification('My Great Song'); document.addEventListener('visibilitychange', function() { if (document.visibilityState === 'visible') { // The tab has become visible so clear the now-stale Notification. n.close(); } }); Note: This API shouldn't be used just to have the notification removed from the screen after a fixed delay (on modern browsers) since this method will also remove the notification from any notification tr...
... ...
OffscreenCanvas - Web APIs
nvas, will display the ImageBitmap on the canvas and transfer its ownership to the canvas. A single OffscreenCanvas may transfer frames into an arbitrary number of other ImageBitmapRenderingContext objects. Given these two <canvas> elements <canvas id="one"></canvas> <canvas id="two"></canvas> the following code will provide the rendering using an OffscreenCanvas as described above. var one = document.getElementById("one").getContext("bitmaprenderer"); var two = document.getElementById("two").getContext("bitmaprenderer"); var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext('webgl'); // ... some drawing for the first canvas using the gl context ... // Commit rendering to the first canvas var bitmapOne = offscreen.transferToImageBitmap(); one.transferFromImageBitmap(b...
... by an OffscreenCanvas Another way to use the OffscreenCanvas API, is to call transferControlToOffscreen() on a <canvas> element, either on a worker or the main thread, which will return an OffscreenCanvas object from an HTMLCanvasElement object from the main thread. Calling getContext() will then obtain a RenderingContext from that OffscreenCanvas. main.js (main thread code): var htmlCanvas = document.getElementById("canvas"); var offscreen = htmlCanvas.transferControlToOffscreen(); var worker = new Worker("offscreencanvas.js"); worker.postMessage({canvas: offscreen}, [offscreen]); offscreencanvas.js (worker code): onmessage = function(evt) { var canvas = evt.data.canvas; var gl = canvas.getContext("webgl"); // ... some drawing using the gl context ... }; You can also use requestA...
PageTransitionEvent - Web APIs
The PageTransitionEvent event object is available inside handler functions for the pageshow and pagehide events, fired when a document is being loaded or unloaded. <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" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/Event" target="_top"><rect x="1" y="1" width="75" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="38.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Event</text></a><polyline points="76,25 86,20 86,30 ...
.../><text x="211" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#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 ...
ParentNode.childElementCount - Web APIs
n, one at those that are children, they have been moved into two separate pure interfaces, ParentNode and ChildNode. In this case, childElementCount moved to ParentNode. This is a fairly technical change that shouldn't affect compatibility. Syntax var count = node.childElementCount; count The return value, which is an unsigned long (simply an integer) type. node An object representing a Document, DocumentFragment, or Element. Example var foo = document.getElementById('foo'); if (foo.childElementCount > 0) { // Do something } Polyfill for IE8 & IE9 & Safari This property is completely unsupported prior to IE9. In IE9 and Safari, it is unsupported in the Document and DocumentFragment objects. ;(function(constructor) { if (constructor && constructor.prototype && const...
...node.nodeType === 1) count++; } return count; } }); } })(window.Node || window.Element); Specification Specification Status Comment DOMThe definition of 'ParentNode.childElementCount' in that specification. Living Standard Split the ElementTraversal interface in ChildNode and ParentNode. This method is now defined on the latter. The Document and DocumentFragment implemented the new interfaces. Element Traversal SpecificationThe definition of 'ElementTraversal.childElementCount' in that specification. Obsolete Added its initial definition to the ElementTraversal pure interface and use it on Element. ...
ParentNode.firstElementChild - Web APIs
at those that are children, they have been moved into two separate pure interfaces, ParentNode and ChildNode. In this case, firstElementChild moved to ParentNode. This is a fairly technical change that shouldn't affect compatibility. Syntax var element = node.firstElementChild; Example <ul id="foo"> <li>First (1)</li> <li>Second (2)</li> <li>Third (3)</li> </ul> <script> var foo = document.getElementById('foo'); // yields: First (1) console.log(foo.firstElementChild.textContent); </script> Polyfill for IE8, IE9 and Safari // Overwrites native 'firstElementChild' prototype. // Adds Document & DocumentFragment support for IE9 & Safari. ;(function(constructor) { if (constructor && constructor.prototype && constructor.prototype.firstElementChild == null) { ...
... } } return null; } }); } })(window.Node || window.Element); Specification Specification Status Comment DOMThe definition of 'ParentNode.firstElementChild' in that specification. Living Standard Split the ElementTraversal interface in ChildNode and ParentNode. This method is now defined on the latter. The Document and DocumentFragment implemented the new interfaces. Element Traversal SpecificationThe definition of 'ElementTraversal.firstElementChild' in that specification. Obsolete Added its initial definition to the ElementTraversal pure interface and use it on Element. ...
ParentNode.querySelector() - Web APIs
The ParentNode mixin defines the querySelector() method as returning an Element representing the first element matching the specified group of selectors which are descendants of the object on which the method was called. If you need all the elements matching the selector list, use querySelectorAll() instead. Note: This method is implemented as Document.querySelector(), DocumentFragment.querySelector() and Element.querySelector(). Syntax element = parentNode.querySelector(selectors); Parameters selectors A DOMString containing one or more selectors to match against. This string must 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...
...MThe definition of 'ParentNode.querySelector()' in that specification. Living Standard Living standard Selectors API Level 2The definition of 'ParentNode.querySelector()' in that specification. Obsolete No change DOM4The definition of 'ParentNode.querySelector()' in that specification. Obsolete Initial definition Selectors API Level 1The definition of 'document.querySelector()' in that specification. Obsolete Original definition ...
Path2D() - Web APIs
Web › API › Path2D › Path2D
; new Path2D(path); new Path2D(d); Parameters path Optional When invoked with another Path2D object, a copy of the path argument is created. d Optional When invoked with a string consisting of SVG path data, a new path is created from that description. Examples Creating and copying paths This example creates and copies a Path2D path. <canvas id="canvas"></canvas> const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let path1 = new Path2D(); path1.rect(10, 10, 100,100); let path2 = new Path2D(path1); path2.moveTo(220, 60); path2.arc(170, 60, 50, 0, 2 * Math.PI); ctx.stroke(path2); Using SVG paths This example creates a Path2D path using SVG path data. The path will move to point (M10 10) and then move horizontally 80 points to the right (...
...path2.moveTo(220, 60); path2.arc(170, 60, 50, 0, 2 * Math.PI); ctx.stroke(path2); Using SVG paths This example creates a Path2D path using SVG path data. The path will move to point (M10 10) and then move horizontally 80 points to the right (h 80), then 80 points down (v 80), then 80 points to the left (h -80), and then back to the start (Z). <canvas id="canvas"></canvas> const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let p = new Path2D('M10 10 h 80 v 80 h -80 Z'); ctx.fill(p); Specification Specification Status Comment HTML Living StandardThe definition of 'Path2D()' in that specification. Living Standard Initial definition. ...
PaymentRequest: merchantvalidation event - Web APIs
vent handler property onmerchantvalidation Examples In this example, an event handler is established for the merchantvalidation event. It uses the fetch() to send a request to its own server with an argument of the payment method's validation URL, obtained from the event's validationURL property. The merchant server should access the validation URL in accordance with the payment method documention. Typically, a client should not access the validation URL. request.addEventListener("merchantvalidation", event => { event.complete(async () => { const merchantServerUrl = window.location.origin + '/validate?url=' + encodeURIComponent(event.validationURL); // get validation data, and complete validation; return await fetch(merchantServerUrl).then(response => response.tex...
...The content delivered by the validation server is forwarded to the merchant server and is then returned from the fetch() call's fulfillment handler to the complete() method on the event. This response lets the payment handler know if the merchant is validated. You can also use the onmerchantvalidation event handler property to set up the handler for this event: request.onmerchantvalidatio...
performance.now() - Web APIs
Web › API › Performance › now
ith `privacy.resistFingerprinting` enabled performance.now(); // 8865400 // 8866200 // 8866700 // ... In Firefox, you can also enable privacy.resistFingerprinting -- this changes the precision to 100ms or the value of privacy.resistFingerprinting.reduceTimerPrecision.microseconds, whichever is larger. ...
...the value of privacy.resistFingerprinting.reduceTimerPrecision.microseconds, whichever is larger. Starting with Firefox 79, high resolution timers can be used if you cross-origin isolate your document using the Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers: Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp These headers ensure a top-level document does not share a browsing context group with cross-origin documents. COOP process-isolates your document and potential attackers can't access to your global object if they were opening it in a popup, preventing a set of cross-origin attacks dubbed XS-Leaks. Specifications Specification Status Comment High Resolution Time Level 2The definition of 'performance.now()' in th...
Using the Performance API - Web APIs
(); do_task(); endTime = performance.now(); return (endTime - startTime); } Serializing the Performance object JSON serialization of the Performance object is done via the toJSON() method. In the following example, JSON serialization for the Performance, Performance.timing and Performance.navigation objects is printed in the object element. ...
... ...
Using Performance Timeline - Web APIs
application's performance bottlenecks. Performance extensions Performance Timeline extends the Performance object with three methods that provide different mechanisms to get a set of performance records (metrics), depending on the specified filter criteria. The following example show the usage of these methods getEntries(), getEntriesByName() and getEntriesByType(). ...
... "; startTime: " + pe.startTime + "; duration: " + pe.duration); } The performance observer entry list interface has the same three getEntries*() methods as the Performance interface and these methods are used to retrieve observed performance entries within the observer callback. These methods have been used in the above stated example. Specifications The interfaces described in this document are defined in the Performance Timeline standard which has two levels: Performance Timeline Level 2; Editors Draft; Work In Progress. This version introduces performance observers (and the PerformanceObserver and PerformanceObserverEntryList interfaces). Performance Timeline; W3C Recommendation 12 December 2013 See Also Performance Timeline (Overview) A Primer for Web Performance Timing...
PhotoCapabilities - Web APIs
of available fill light options. Options may include auto, off, or flash. Example The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from getPhotoCapabilities() to modify the size of an input range. This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
...ure / Photo Resolution Sample, uses the results from getPhotoCapabilities() to modify the size of an input range. This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
PopStateEvent - Web APIs
PopStateEvent is an event handler for the popstate event on the window. A popstate event is dispatched to the window every time the active history entry changes between two history entries for the same document. If the history entry being activated was created by a 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: Br...
...me. 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 function. ...
RTCDTMFSender: tonechange event - Web APIs
the event's tone property. Examples This example establishes a handler for the tonechange event which updates an element to display the currently playing tone in its content, or, if all tones have played, the string "<none>". ...
... Candidate Recommendation Definition for the WebRTC API ...
RTCDataChannel.onmessage - Web APIs
wser will call to handle the message event. The function receives as its sole input parameter a MessageEvent object describing the event. Example This code snippet creates a peer connection, adds a data channel to it, and starts creating new <p> (paragraph) elements each time a message arrives, with the message's contents displayed inside it. The new elements are then attached to the end of the document. ...
...ing the event. Example This code snippet creates a peer connection, adds a data channel to it, and starts creating new <p> (paragraph) elements each time a message arrives, with the message's contents displayed inside it. The new elements are then attached to the end of the document. let pc = new RTCPeerConnection(); let dc = pc.createDataChannel(); dc.onmessage = function(event) { var el = document.createElement("p"); var txtNode = document.createTextNode(event.data); el.appendChild(txtNode); receiveBox.appendChild(el); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.onmessage' in that specification. Candidate Recommendation Initial specification. ...
RTCIceCandidatePair - Web APIs
on of the local end of the connection. remote The RTCIceCandidate describing the configuration of the remote end of the connection. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
...didate describing the configuration of the remote end of the connection. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
RTCIceTransport.getSelectedCandidatePair() - Web APIs
Note: It's possible for one of the configurations in the selected candidate pair to remain unchanged when a new pairing is chosen. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
...elected candidate pair to remain unchanged when a new pairing is chosen. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
RTCIceTransport.onselectedcandidatepairchange - Web APIs
didatePair.global properties specify RTCIceCandidate objects describing the local and remote candidates that are currently being used. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
...describing the local and remote candidates that are currently being used. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
RTCPeerConnection.getStats() - Web APIs
r whose track matches the specified selector, or selector matches more than one sender or receiver. Obsolete syntax Previously, getStats() used success and failure callbacks to report the results to you, instead of using a promise. This version of getStats() is obsolete; in addition, the data it returns is entirely different from the current specification, and the form of that data was never documented. This form of getStats() has been or will soon be removed from most browsers; you should not use it, and should update existing code to use the new promise-based version. Check the Browser compatibility table to verify the state of this method. promise = rtcPeerConnection.getStats(selector, successCallback, failureCallback) Parameters selector Optional A MediaStreamTrack for which to ga...
...A section is created for each report with a header and all of the statistics below, with the type, ID, and timestamp handled specially to place them at the top of the list. Once the HTML for ...
RTCPeerConnection: iceconnectionstatechange event - Web APIs
CPeerConnection. In this example, a handler for iceconnectionstatechange is set up to update a call state indicator by using the value of iceConnectionState to create a string which corresponds to the name of a CSS class that we can assign to the status indicator to cause it to reflect the current state of the connection. ...
...the name of a CSS class that we can assign to the status indicator to cause it to reflect the current state of the connection. pc.addEventListener("iceconnectionstatechange", ev => { let stateElem = document.querySelector("#call-state"); stateElem.className = `${pc.iceConnectionState}-state`; }, false); This can also be written as: pc.oniceconnectionstatechange = ev => { let stateElem = document.querySelector("#call-state"); stateElem.className = `${pc.iceConnectionState}-state`; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'iceconnectionstatechange' in that specification. Candidate Recommendation ...
RTCPeerConnection.setRemoteDescription() - Web APIs
rrors which might occur, and simplifies the processing you need to do when you receive an offer, by eliminating the need to handle the offer/answer process differently depending on whether the local peer is the caller or callee. Note: Earlier implementations of WebRTC would throw an exception if an offer was set outside a stable or have-remote-offer state. Deprecated syntax In older code and documentation, you may see a callback-based version of this function used. 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, success...
... from the example and tutorial in the article Signaling and video calling; take a look at that for more details and a more in-depth explanation of what's going on. ...
RTCPeerConnection - Web APIs
s not yet begun (new), has begun gathering candidates (gathering), or has completed (complete). Also available using the onicegatheringstatechange event handler property. isolationchange Sent to the RTCPeerConnection when the isolated property on one of the MediaStreamTrack objects associated with the connection changes value. A track is isolated if its content cannot be accessed by the owning document due to lack of authentication or if the track comes from a cross-origin source. Also available through the onisolationchange event handler property. negotiationneeded Sent to the RTCPeerConnection when negotiation or renegotiation of the ICE connection needs to be performed; this can happen both when first opening a connection as well as when it's neccessary to adapt to changing network condit...
...ng", "checking", "failed", or "disconnected", or all of the connection's transports are in the "closed" state. "connecting" One or more of the ICE transports are currently in the process of establishing a connection; that is, their RTCIceConnectionState is either "checking" or "connected", and no transports are in the "failed" state. <<< Make this a link once I know where that will be documented "connected" Every ICE transport used by the connection is either in use (state "connected" or "completed") or is closed (state "closed"); in addition, at least one transport is either "connected" or "completed". "disconnected" At least one of the ICE transports for the connection is in the "disconnected" state and none of the other transports are in the state "failed", "...
Range() - Web APIs
Web › API › Range › Range
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(). ...
... 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.compareBoundaryPoints() - Web APIs
t boundary-point of sourceRange to the end boundary-point of Range. Range.START_TO_START compares the start boundary-point of sourceRange to the start boundary-point of Range. If the value of the parameter is invalid, a DOMException with a NotSupportedError code is thrown. sourceRange A Range to compare boundary points with the range. Example var range, sourceRange, compare; range = document.createRange(); range.selectNode(document.getElementsByTagName("div")[0]); sourceRange = document.createRange(); sourceRange.selectNode(document.getElementsByTagName("div")[1]); compare = range.compareBoundaryPoints(Range.START_TO_END, sourceRange); Specifications Specification Status Comment DOMThe definition of 'Range.compareBoundaryPoints()' in that specification. ...
... Obsolete Initial specification. ...
Range.insertNode() - Web APIs
Web › API › Range › insertNode
The Range.insertNode() method inserts a node at the start of the Range. The new node is inserted at the start boundary point of the Range. If the new node is to be added to a text Node, that Node is split at the insertion point, and the insertion occurs between the two text nodes. If the new node is a document fragment, the children of the document fragment are inserted instead. Syntax range.insertNode(newNode); Parameters newNode The Node to insert at the start of the range. ...
... boundary point of the Range. If the new node is to be added to a text Node, that Node is split at the insertion point, and the insertion occurs between the two text nodes. If the new node is a document fragment, the children of the document fragment are inserted instead. Syntax range.insertNode(newNode); Parameters newNode The Node to insert at the start of the range. Example range = document.createRange(); newNode = document.createElement("p"); newNode.appendChild(document.createTextNode("New Node Inserted Here")); range.selectNode(document.getElementsByTagName("div").item(0)); range.insertNode(newNode); Specifications Specification Status Comment DOMThe definition of 'Range.insertNode()' in that specification. Living Standard No change Docum...
Range.toString() - Web APIs
Web › API › Range › toString
.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. ...
... Obsolete Initial specification. ...
Request() - Web APIs
Web › API › Request › Request
word@example.com. Example In our Fetch Request example (see Fetch Request live) we create a new Request object using the constructor, then fetch it using a GlobalFetch.fetch call. Since we are fetching an image, we run Body.blob on the response to give it the proper MIME type so it will be handled properly, then create an Object URL of it and display it in an <img> element. ...
...}); Note that you could also pass the init object into the fetch...
Response.clone() - Web APIs
Web › API › Response › clone
(see Fetch Response clone live) we create a new Request object using the Request() constructor, passing it a JPG path. We then fetch this request using fetch(). When the fetch resolves successfully, we clone it, extract a blob from both responses using two Body.blob calls, create object URLs out of the blobs using URL.createObjectURL, and display them in two separate <img> elements. ...
...w Request object using the Request() constructor, passing it a JPG path. We then fetch this request using fetch(). When the fetch resolves successfully, we clone it, extract a blob from both responses using two Body.blob calls, create object URLs out of the blobs using URL.createObjectURL, and display them in two separate <img> elements. ...
SVGAnimationElement: endEvent event - Web APIs
00px"> <title>SVG SMIL Animate with Path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animateMotion path="M 0 0 H 300 Z" dur="5s" repeatCount="indefinite" /> </circle> </svg> <hr> <button>Stop animation</button> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgElem = document.querySelector('svg'); let animateElem = document.querySelector('animateMotion'); let list = document.querySelector('ul'); let btn = document.querySelector('button'); animateElem.addEventListener('beginEvent', () => { let listItem = document.createElement('li'); listItem.textContent = 'beginEvent fired'; list.appendChild(listItem); }) animateElem.addEventListener('endEvent', () => { let ...
...tor('svg'); let animateElem = document.querySelector('animateMotion'); let list = document.querySelector('ul'); let btn = document.querySelector('button'); animateElem.addEventListener('beginEvent', () => { let listItem = document.createElement('li'); listItem.textContent = 'beginEvent fired'; list.appendChild(listItem); }) animateElem.addEventListener('endEvent', () => { let listItem = document.createElement('li'); listItem.textContent = 'endEvent fired'; list.appendChild(listItem); }) animateElem.addEventListener('repeatEvent', (e) => { let listItem = document.createElement('li'); let msg = 'repeatEvent fired'; if(e.detail) { msg += '; repeat number: ' + e.detail; } listItem.textContent = msg; list.appendChild(listItem); }) btn.addEventListener('click', () => { ...
SVGGraphicsElement: copy event - Web APIs
...
... Clipboard API and events Working Draft Initial definition ...
SVGGraphicsElement: cut event - Web APIs
owser's user interface. If the user attempts a cut action on uneditable content, the cut event still fires but the event object contains no data. Bubbles Yes Cancelable Yes Interface ClipboardEvent Event handler property oncut The event's default action is to copy the current selection (if any) to the system clipboard and remove it from the document. A handler for this event can modify the clipboard contents by calling setData(format, data) on the event's ClipboardEvent.clipboardData property, and cancelling the default action using event.preventDefault(). Note though that cancelling the default action will also prevent the document from being updated. So an event handler which wants to emulate the default action for "cut" while modifying...
... calling setData(format, data) on the event's ClipboardEvent.clipboardData property, and cancelling the default action using event.preventDefault(). Note though that cancelling the default action will also prevent the document from being updated. So an event handler which wants to emulate the default action for "cut" while modifying the clipboard must also manually remove the selection from the document. The handler cannot read the clipboard data. It's possible to construct and dispatch a synthetic cut event, but this will not affect the system clipboard or the document's contents. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2 Candidate Recommendation Definition that the clipboard events apply to SVG elements. Clipboard AP...
Selection.collapse() - Web APIs
The Selection.collapse() method collapses the current selection to a single point. The document is not modified. If the content is focused and editable, the caret will blink there. Syntax sel.collapse(node, offset); Parameters node The caret location will be within this node. This value can also be set to null -- if null is specified, the method will behave like Selection.removeAllRanges(), i.e. all ranges will be removed from the selection. offset Optional The offset in node to which the selection will be collapsed. If not specified, the default value 0 is used. Examples /* Place the caret at the beginning of an HTML document's body. ...
... this node. This value can also be set to null -- if null is specified, the method will behave like Selection.removeAllRanges(), i.e. all ranges will be removed from the selection. offset Optional The offset in node to which the selection will be collapsed. If not specified, the default value 0 is used. Examples /* Place the caret at the beginning of an HTML document's body. */ var body = document.getElementsByTagName("body")[0]; window.getSelection().collapse(body,0); Specifications Specification Status Comment Selection APIThe definition of 'Selection.collapse()' in that specification. Working Draft ...
Selection.modify() - Web APIs
Web › API › Selection › modify
forward" or "backward" to adjust in the appropriate direction based on the language at the selection point. If you want to adjust in a specific direction, you can specify "left" or "right". granularity The distance to adjust the current selection or cursor position. You can move by "character", "word", "sentence", "line", "paragraph", "lineboundary", "sentenceboundary", "paragraphboundary", or "documentboundary". Note: Gecko does not implement "sentence", "paragraph", "sentenceboundary", "paragraphboundary", or "documentboundary". WebKit and Blink do. Note: Starting in Gecko 5.0, the "word" granularity no longer includes the following space, regardless of the default platform behavior. This makes the behavior more consistent, as well as making it work the same way WebKit used to work, but un...
...value="character">Character</option> <option value="word">Word</option> <option value="sentence">Sentence</option> <option value="line">Line</option> <option value="paragraph">Paragraph</option> <option value="lineboundary">Line Boundary</option> <option value="sentenceboundary">Sentence Boundary</option> <option value="paragraphboundary">Paragraph Boundary</option> <option value="documentboundary">Document Boundary</option> </select> <br><br> <button>Extend selection</button> JavaScript let select = document.querySelector('select'); let button = document.querySelector('button'); button.addEventListener('click', modify); function modify() { let selection = window.getSelection(); selection.modify('extend', 'forward', select.value); } Result Specifications This method ...
Selection.setBaseAndExtent() - Web APIs
child node is included. And so on. focusNode The node at the end of the selection. focusOffset The number of child nodes from the start of the focus node that should be included in the selection. So for example, if the value is 0 the whole node is excluded. If the value is 1, the first child node is included. And so on. Note: If the focus position appears before the anchor position in the document, the direction of the selection is reversed -- the caret is placed at the beginning of the text rather the end, which matters for any keyboard command that might follow. For example, Shift + ? would cause the selection to narrow from the beginning rather than grow at the end. Return Value Void. Exceptions If anchorOffset is larger than the number of child nodes inside anchorNode, or if focus...
...<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(); selection.setBaseAndExtent(one, aOff...
Using server-sent events - Web APIs
th the URL and an options dictionary. For example, assuming the client script is on example.com: const evtSource = new EventSource("//api.example.com/ssedemo.php", { withCredentials: true } ); Once you've instantiated your event source, you can begin listening for messages from the server by attaching a handler for the message event: evtSource.onmessage = function(event) { const newElement = document.createElement("li"); const eventList = document.getElementById("list"); newElement.innerHTML = "message: " + event.data; eventList.appendChild(newElement); } This code listens for incoming messages (that is, notices from the server that do not have an event field on them) and appends the message text to a list in the document's HTML. You can also listen for events with addEventListener(...
...newElement.innerHTML = "message: " + event.data; eventList.appendChild(newElement); } This code listens for incoming messages (that is, notices from the server that do not have an event field on them) and appends the message text to a list in the document's HTML. You can also listen for events with addEventListener(): evtSource.addEventListener("ping", function(event) { const newElement = document.createElement("li"); const time = JSON.parse(event.data).time; newElement.innerHTML = "ping at " + time; eventList.appendChild(newElement); }); This code is similar, except that it will be called automatically whenever the server sends a message with the event field set to "ping"; it then parses the JSON in the data field and outputs that information. When not used over HTTP/2, SSE suff...
ServiceWorkerContainer.getRegistration() - Web APIs
The getRegistration() method of the ServiceWorkerContainer interface gets a ServiceWorkerRegistration object whose scope URL matches the provided document URL. The method returns a Promise that resolves to a ServiceWorkerRegistration or undefined. Syntax serviceWorkerContainer.getRegistration(scope).then(function(serviceWorkerRegistration) { ... }); Parameters scope Optional A unique identifier for a service worker registration -- the scope URL of the registration object you want to return. This is usually a relative URL. Return value A Promise that resolves to a ServiceWorkerRegistration object or undefined. ...
...ion) { ... }); Parameters scope Optional A unique identifier for a service worker registration -- the scope URL of the registration object you want to return. This is usually a relative URL. Return value A Promise that resolves to a ServiceWorkerRegistration object or undefined. Example navigator.serviceWorker.getRegistration('/app').then(function(registration) { if(registration){ document.querySelector('#status').textContent = 'ServiceWorkerRegistration found.'; } }); Specifications Specification Status Comment Service WorkersThe definition of 'ServiceWorkerContainer: getRegistration' in that specification. Working Draft Initial definition. ...
ServiceWorkerContainer - Web APIs
ead only Provides a way of delaying code execution until a service worker is active. It returns a Promise that will never reject, and which waits indefinitely until the ServiceWorkerRegistration associated with the current page has an ServiceWorkerRegistration.active worker. Once that condition is met, it resolves with the ServiceWorkerRegistration. Events controllerchange Occurs when the document's associated ServiceWorkerRegistration acquires a new active worker. Also available via the ServiceWorkerContainer.oncontrollerchange property. error Fired whenever an error occurs in the associated service workers. Also available via the ServiceWorkerContainer.onerror property. message Occurs when incoming messages are received by the ServiceWorkerContainer object (e.g. via a MessagePort.p...
... are received by the ServiceWorkerContainer object (e.g. via a MessagePort.postMessage() call.) Also available via the ServiceWorkerContainer.onmessage property. Methods ServiceWorkerContainer.register() Creates or updates a ServiceWorkerRegistration for the given scriptURL. ServiceWorkerContainer.getRegistration() Gets a ServiceWorkerRegistration object whose scope matches the provided document URL. The method returns a Promise that resolves to a ServiceWorkerRegistration or undefined. ServiceWorkerContainer.getRegistrations() Returns all ServiceWorkerRegistration objects associated with a ServiceWorkerContainer in an array. The method returns a Promise that resolves to an array of ServiceWorkerRegistration. ServiceWorkerContainer.startMessages() explicitly starts the flow of me...
Slottable: assignedSlot - Web APIs
if the associated shadow root was attached with its mode set to closed (see Element.attachShadow for further details). Examples In our simple-template example (see it live), we create a trivial custom element example called <my-paragraph> in which a shadow root 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. l...
...ulated 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. Living Standard Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to con...
SpeechSynthesis.getVoices() - Web APIs
rray) 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. ...
... var voices = speechSynthesis.getVoices(); for(var i = 0; i < voices.length; i++) { var option = document.createElement('option'); option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textContent += ' -- DEFAULT'; } option.setAttribute('data-lang', voices[i].lang); option.setAttribute('data-name', voices[i].name); document.getElementById("voiceSelect").appendChild(option); } } populateVoiceList(); if (typeof speechSynthesis !== 'undefined' && speechSynthesis.onvoiceschanged !== undefined) { speechSynthesis.onvoiceschanged = populateVoiceList; } HTML <select id="voiceSelect"></select> Specifications Specification Status Comment Web Speech APIThe definition of 'getVoices()' in that...
SpeechSynthesis: voiceschanged event - Web APIs
property onvoiceschanged Examples This could be used to repopulate a list of voices that the user can choose between when the event fires. ...
...ption.textContent = voices[i].name + ' (' + voices[i].lang + ')'; option.setAttribute('data-lang', voices[i].lang); option.setAttribute('data-name', voices[i].name); voiceSelect.appendChild(option); } }); Or use the onvoiceschanged event handler property: synth.onvoiceschanged = function() { var voices = synth.getVoices(); for(i = 0; i < voices.length ; i++) { var option = document.createElement('option'); option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; option.setAttribute('data-lang', voices[i].lang); option.setAttribute('data-name', voices[i].name); voiceSelect.appendChild(option); } } Specifications Specification Status Comment Web Speech APIThe definition of 'speech synthesis events' in that specification. ...
Using readable streams - Web APIs
on called readStream() is invoked to read the data back out of the stream again. We also close the stream, as we've stopped enqueuing chunks to it. ...
...ion processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = result; return; } charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Read ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild(listItem); result += chunk; // Read some more, and call this function again return reader.read().then(processText); }); } Closing and cancelling streams We've already shown examples of using ReadableStreamDefaultController.close() to clo...
StyleSheet - Web APIs
.disabled Is a Boolean representing whether the current stylesheet has been applied or not. StyleSheet.href Read only Returns a DOMString representing the location of the stylesheet. StyleSheet.media Read only Returns a MediaList representing the intended destination medium for style information. StyleSheet.ownerNode Read only Returns a Node associating this style sheet with the current document. StyleSheet.parentStyleSheet Read only Returns a StyleSheet including this one, if any; returns null if there aren't any. StyleSheet.title Read only Returns a DOMString representing the advisory title of the current style sheet. StyleSheet.typeRead only Returns a DOMString representing the style sheet language for this style sheet. Specifications Specification Status Co...
...tyleSheet.title Read only Returns a DOMString representing the advisory title of the current style sheet. StyleSheet.typeRead only Returns a DOMString representing the style sheet language for this style sheet. Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'StyleSheet' in that specification. Working Draft No change from Document Object Model (DOM) Level 2 Style Specification. Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'StyleSheet' in that specification. Obsolete Initial definition. ...
SubmitEvent() - Web APIs
Syntax let submitEvent = new SubmitEvent(type,eventInitDict); Parameters type A DOMString indicating the event which occurred. For SubmitEvent, this is always submit. eventInitDict Optional An optional dictionary of initial values for the event's properties. Return value A SubmitEvent object configured using the given inputs. ...
...g the given inputs. Examples This code snippet locates a form in the current document, and then an HTML <button> within the form with the class submit on it. Next, a new SubmitEvent is created, configured with its submitter set to the identified button (or null if the button wasn't found). Then the event is sent to the form, telling the form that it's been submitted by the button. const form = document.querySelector("form"); const formTrigger = form.querySelector("button.submit"); const submitEvent = new SubmitEvent("submit", { submitter: formTrigger }); form.dispatchEvent(submitEvent); This is a somewhat contrived example, as you can do nearly all of this much more easily, but this gives you deep control over the process that can be useful. Specifications Specification Status ...
SubtleCrypto.deriveKey() - Web APIs
nd Bob's public key. let alicesSecretKey = await deriveSecretKey(alicesKeyPair.privateKey, bobsKeyPair.publicKey); // Bob generates the same secret key using his private key and Alice's public key. let bobsSecretKey = await deriveSecretKey(bobsKeyPair.privateKey, alicesKeyPair.publicKey); // Alice can then use her copy of the secret key to encrypt a message to Bob. ...
... bobsSecretKey = await deriveSecretKey(bobsKeyPair.privateKey, alicesKeyPair.publicKey); // Alice can then use her copy of the secret key to encrypt a message to Bob. let encryptButton = document.querySelector(".ecdh .encrypt-button"); encryptButton.addEventListener("click", () => { encrypt(alicesSecretKey); }); // Bob can use his copy to decrypt the message. let decryptButton = document.querySelector(".ecdh .decrypt-button"); decryptButton.addEventListener("click", () => { decrypt(bobsSecretKey); }); } PBKDF2 In this example we ask the user for a password, then use it to derive an AES key using PBKDF2, then use the AES key to encrypt a message. See the complete code on GitHub. /* Get some key material to use as input to the deriveKey method. The key material is a pass...
Text.isElementContentWhitespace - Web APIs
ould do the same work just like the three example above. The Text.isElementContentWhitespace read-only property returns a Boolean flag indicating whether or not the text node's content consists solely of whitespace. ...
...f whitespace. Syntax b = textnode.isElementContentWhitespace; Example In the example below, we create a node with mixed display and whitespace characters and the attribute is false. ...
Text.wholeText - Web APIs
Web › API › Text › wholeText
This allows to specify any text node and obtain all adjacent text as a single string. ...
...ML; that's fine and probably clearer in most circumstances. If you have to work with mixed content within an element, as seen here, wholeText and replaceWholeText() may be useful. replaceWholeText() is obsolete. Specifications Specification Status Comment DOMThe definition of 'Text.wholeText' in that specification. Living Standard No significant change. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Text.wholeText' in that specification. Obsolete Initial definition. ...
TextEncoder.prototype.encodeInto() - Web APIs
r encoder = new TextEncoder; function encodeIntoWithSentinel(string, u8array, position) { var stats = encoder.encodeInto(string, position ? ...
...ntinel(string, u8array, position) { var stats = encoder.encodeInto(string, position ? ...
TextMetrics - Web APIs
ingContext2D.textBaseline property to the ideographic baseline of the line box, in CSS pixels. Examples Baselines illustrated This example demonstrates the baselines the TextMetrics object holds. The default baseline is the alphabeticBaseline. See also the CanvasRenderingContext2D.textBaseline property. ...
...asuring the x-direction of a piece of text, the sum of actualBoundingBoxLeft and actualBoundingBoxRight can be wider than the width of the inline box (width), due to slanted/italic fonts where characters overhang their advance width. ...
TextTrack: cuechange event - Web APIs
rlying TextTrack, indicated by the track property, receives a cuechange event every time the currently-presented cue is changed. This happens even if the track isn't associated with a media element. If the track is associated with a media element, using the <track> element as a child of the <audio> or <video> element, the cuechange event is also sent to the HTMLTrackElement. ...
...ted with a media element, using the <track> element as a child of the <audio> or <video> element, the cuechange event is also sent to the HTMLTrackElement. let textTrackElem = document.getElementById("texttrack"); textTrackElem.addEventListener("cuechange", (event) => { let cues = event.target.track.activeCues; }); In addition, you can use the oncuechange event handler: let textTrackElem = document.getElementById("texttrack"); textTrackElem.oncuechange = (event) => { let cues = event.target.track.activeCues; }); Specifications Specification Status HTML Living StandardThe definition of 'cuechange' in that specification. Living Standard ...
TextTrackList: removeTrack event - Web APIs
The removetrack event is fired when a track is removed from a TextTrackList. ...
... Living Standard ...
Touch - Web APIs
Web › API › Touch
ntX Read only Returns the X coordinate of the touch point relative to the left edge of the browser viewport, not including any scroll offset. Touch.clientY Read only Returns the Y coordinate of the touch point relative to the top edge of the browser viewport, not including any scroll offset. Touch.pageX Read only Returns the X coordinate of the touch point relative to the left edge of the document. Unlike clientX, this value includes the horizontal scroll offset, if any. Touch.pageY Read only Returns the Y coordinate of the touch point relative to the top of the document. Unlike clientY, this value includes the vertical scroll offset, if any. Touch.target Read only Returns the Element on which the touch point started when it was first placed on the surface, even if the touch point ha...
... Touch area Touch.radiusX Read only Returns the X radius of the ellipse that most closely circumscribes the area of contact with the screen. The value is in pixels of the same scale as screenX. ...
Using Touch Events - Web APIs
t the browser from processing emulated mouse events. // touchmove handler function process_touchmove(ev) { // Set call preventDefault() ev.preventDefault(); } Best practices Here are some best practices to consider when using touch events: Minimize the amount of work that is done in the touch handlers. Add the touch point handlers to the specific target element (rather than the entire document or nodes higher up in the document tree). Add touchmove, touchend and touchcancel event handlers within the touchstart. The target touch element or node should be large enough to accommodate a finger touch. If the target area is too small, touching it could result in firing other events for adjacent elements. Implementation and deployment status The touch events browser compatibility data in...
...sents input from any input device. Additionally, the pointer event types are very similar to mouse event types (for example, pointerdown pointerup) thus code to handle pointer events closely matches mouse handling code. The implementation status of pointer events in browsers is relatively high with Chrome, Firefox, IE11 and Edge having complete implementations. Examples and demos The following documents describe how to use touch events and include example code: Touch Events Overview Implement Custom Gestures Introduction to Touch events in JavaScript Add touch screen support to your website (The easy way) Touch event demonstrations: Paint Program (by Rick Byers) Touch/pointer tests and demos (by Patrick H. Lauke) Community Touch Events Community Group Mail list W3C #toucheven...
TrackEvent - Web APIs
t null, this is always an object of one of the media track types: AudioTrack, VideoTrack, or TextTrack). Methods TrackEvent has no methods of its own; however, it is based on Event, so it provides the methods available on Event objects. Example This example sets up a function, handleTrackEvent(), which is callled for any addtrack or removetrack event on the first <video> element found in the document. ...
...bject of one of the media track types: AudioTrack, VideoTrack, or TextTrack). Methods TrackEvent has no methods of its own; however, it is based on Event, so it provides the methods available on Event objects. Example This example sets up a function, handleTrackEvent(), which is callled for any addtrack or removetrack event on the first <video> element found in the document. ...
TreeWalker.filter - Web APIs
Web › API › TreeWalker › filter
The TreeWalker.filter read-only property returns a NodeFilter that is the filtering object associated with the TreeWalker. When creating the TreeWalker, the filter object is passed in as the third parameter, and its method NodeFilter.acceptNode() is called on every single node to determine whether or not to accept it. Syntax nodeFilter = treeWalker.filter; Example var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); nodeFilter = treeWalker.filter; // document.body in this case Specifications Specification Status Comment DOMThe definition of 'TreeWalker.filter' in that specification. Living Standard No change from Document Object Model ...
... Obsolete Initial definition. ...
TreeWalker.firstChild() - Web APIs
The TreeWalker.firstChild() method moves the current Node to the first visible child of the current node, and returns the found child. It also moves the current node to this child. If no such child exists, returns null and the current node is not changed. Syntax node = treeWalker.firstChild; Example var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); var node = treeWalker.firstChild(); // returns the first child of the root element, or null if none Specifications Specification Status Comment DOMThe definition of 'TreeWalker.firstChild' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 Traversal a...
... Obsolete Initial definition. ...
TreeWalker.lastChild() - Web APIs
The TreeWalker.lastChild() method moves the current Node to the last visible child of the current node, and returns the found child. It also moves the current node to this child. If no such child exists, returns null and the current node is not changed. Syntax node = treeWalker.lastChild(); Example var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); var node = treeWalker.lastChild(); // returns the last visible child of the root element Specifications Specification Status Comment DOMThe definition of 'TreeWalker.lastChild' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Spec...
... Obsolete Initial definition. ...
TreeWalker.nextNode() - Web APIs
The TreeWalker.nextNode() method moves the current Node to the next visible node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists, returns null and the current node is not changed. Syntax node = treeWalker.nextNode(); Example var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); var node = treeWalker.nextNode(); // returns the first child of root, as it is the next node in document order Specifications Specification Status Comment DOMThe definition of 'TreeWalker.nextNode' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 Travers...
... Obsolete Initial definition. ...
TreeWalker.nextSibling() - Web APIs
The TreeWalker.nextSibling() method moves the current Node to its next sibling, if any, and returns the found sibling. If there is no such node, return null and the current node is not changed. Syntax node = treeWalker.nextSibling(); Example var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); treeWalker.firstChild(); var node = treeWalker.nextSibling(); // returns null if the first child of the root element has no sibling Specifications Specification Status Comment DOMThe definition of 'TreeWalker.nextSibling' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Specification ...
... Obsolete Initial definition. ...
TreeWalker.parentNode() - Web APIs
The TreeWalker.parentNode() method moves the current Node to the first visible ancestor node in the document order, and returns the found node. If no such node exists, or if it is above the TreeWalker's root node, returns null and the current node is not changed. Syntax node = treeWalker.parentNode(); Example var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); var node = treeWalker.parentNode(); // returns null as there is no parent Specifications Specification Status Comment DOMThe definition of 'TreeWalker.parentNode' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Specif...
... Obsolete Initial definition. ...
TypeInfo - Web APIs
Web › API › TypeInfo
Properties TypeInfo.typeName Read only Returns a DOMString indicating the type's name. TypeInfo.typeNamespace Read only Returns a DOMString indicating the type's namespace within the schema. Methods TypeInfo.isDerivedFrom() Returns a Boolean. ...
...e Read only Returns a DOMString indicating the type's namespace within the schema. Methods TypeInfo.isDerivedFrom() Returns a Boolean. Constants Constant Value DERIVATION_RESTRICTION 1 DERIVATION_EXTENSION 2 DERIVATION_UNION 4 DERIVATION_LIST 8 Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'TypeInfo' in that specification. Obsolete Initial definition ...
UIEvent.pageX - Web APIs
Web › API › UIEvent › pageX
The non-standard, read-only UIEvent property pageX returns the horizontal coordinate of the event relative to the whole document. This property was never part of any standard, and was only implemented across a subset of browsers, and only for a limited number of versions. A standardized version of pageX was added to the MouseEvent interface, however, and is well-supported. You should not expect to find pageX on any non-mouse events. Do not look for pageX on any non-mouse events in new code and update existing code as soon as possible. ...
... is well-supported. You should not expect to find pageX on any non-mouse events. Do not look for pageX on any non-mouse events in new code and update existing code as soon as possible. Syntax var pos = event.pageX Value An integer value, in pixels, indicating the X coordinate at which the mouse pointer was located when the event occurred. This value is relative to the left edge of the entire document, regardless of the current horizontal scrolling offset of the document. Examples For an example, see the documentation for the standard MouseEvent.pageX property, which you should use instead. Specifications This property is not part of any specification. See MouseEvent.pageX instead. ...
UIEvent - Web APIs
Web › API › UIEvent
only Returns a Boolean indicating whether the event produced a key character or not. UIEvent.layerX Read only Returns the horizontal coordinate of the event relative to the current layer. UIEvent.layerY Read only Returns the vertical coordinate of the event relative to the current layer. UIEvent.pageX Read only Returns the horizontal coordinate of the event relative to the whole document. UIEvent.pageY Read only Returns the vertical coordinate of the event relative to the whole document. UIEvent.sourceCapabilities Read only Returns an instance of the InputDeviceCapabilities interface, which provides information about the physical device responsible for generating a touch event. UIEvent.viewRead only Returns a WindowProxy that contains the view that generated the even...
... Methods This interface also inherits methods of its parent, Event. UIEvent.initUIEvent() Initializes a UIEvent object. If the event has already being dispatched, this method does nothing. Specifications Specification Status Comment InputDeviceCapabilities Draft Added sourceCapabilities property. UI Events Working Draft Extend DOM3 Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'UIEvent' in that specification. Obsolete Added the UIEvent() constructor, deprecated the initUIEvent() method and changed the type of view from AbstractView to WindowProxy. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'UIEvent' in that specification. Obsolete Initial definition ...
URL.createObjectURL() - Web APIs
The new object URL represents the specified File object or Blob object. To release an object URL, call revokeObjectURL(). Note: This feature is available in Web Workers. Note: This feature is not available in Service Workers due to its potential to create memory leaks. Syntax const objectURL = URL.createObjectURL(object) Parameters object A File, Blob, or MediaSource object to create an object URL for. ...
...ents of the specified source object. Examples See Using object URLs to display images. Usage notes Memory management Each time you call createObjectURL(), a new object URL is created, even if you've already created one for the same object. Each of these must be released by calling URL.revokeObjectURL() when you no longer need them. Browsers will release object URLs automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so. Using object URLs for media streams In older versions of the Media Source specification, attaching a stream to a <video> element required creating an object URL for the MediaStream. This is no longer necessary, and browsers are removing support for doing...
URL API - Web APIs
Web › API › URL API
) function below takes as input a HTMLTableElement object representing a <table>. Rows are added to the table, one for each key found in the parameters, with the first column containing the key's name, and the second column having the value. Note the call to URLSearchParams.sort() to sort the parameter list before generating the table. ...
...mn containing the key's name, and the second column having the value. Note the call to URLSearchParams.sort() to sort the parameter list before generating the table. function fillTableWithParameters(tbl) { let url = new URL(document.location.href); url.searchParams.sort(); let keys = url.searchParams.keys(); for (let key of keys) { let val = url.searchParams.get(key); let row = document.createElement("tr"); let cell = document.createElement("td"); cell.innerText = key; row.appendChild(cell); cell = document.createElement("td"); cell.innerText = val; row.appendChild(cell); tbl.appendChild(row); }; } A working version of this example can be found on Glitch. Just add parameters to the URL when loading the page to see them in the table. For instance, t...
VideoPlaybackQuality.droppedVideoFrames - Web APIs
typically dropped either before or after decoding them, when it's determined that it will not be possible to draw them to the screen at the correct time. Example This example calls getVideoPlaybackQuality() to obtain a VideoPlaybackQuality object, then determines what percentage of frames have been dropped. That value is then presented in an element for the user's reference. ...
...em, when it's determined that it will not be possible to draw them to the screen at the correct time. Example This example calls getVideoPlaybackQuality() to obtain a VideoPlaybackQuality object, then determines what percentage of frames have been dropped. That value is then presented in an element for the user's reference. var videoElem = document.getElementById("my_vid"); var percentElem = document.getElementById("percent"); var quality = videoElem.getVideoPlaybackQuality(); var dropPercent = (quality.droppedVideoFrames/quality.totalVideoFrames)*100; percentElem.innerText = Math.trunc(dropPercent).toString(10); Specifications Specification Status Comment Media Playback QualityThe definition of 'VideoPlaybackQuality.droppedVideoFrames' in that specification. Ed...
WebGLRenderingContext - Web APIs
The WebGLRenderingContext interface provides an interface to the OpenGL ES 2.0 graphics rendering context for the drawing surface of an HTML <canvas> element. To get an access to a WebGL context for 2D and/or 3D graphics rendering, call getContext() on a <canvas> element, supplying "webgl" as the argument: var canvas = document.getElementById('myCanvas'); var gl = canvas.getContext('webgl'); Once you have the WebGL rendering context for a canvas, you can render within it. The WebGL tutorial has more information, examples, and resources on how to get started with WebGL. If you require a WebGL 2.0 context, see WebGL2RenderingContext; this supplies access to an implementation of OpenGL ES 3.0 graphics. Constants See the WebGL constants page. The WebGL context The following properties and ...
...ur browser does not seem to support HTML5 canvas.</canvas> <canvas>Your browser does not seem to support HTML5 canvas.</canvas> body { text-align : center; } canvas { display : inline-block; width : 120px; height : 80px; margin : auto; padding : 0; border : none; background-color : black; } window.addEventListener("load", function() { "use strict" var firstCanvas = document.getElementsByTagName("canvas")[0], secondCanvas = document.getElementsByTagName("canvas")[1]; firstCanvas.width = firstCanvas.clientWidth; firstCanvas.height = firstCanvas.clientHeight; [firstCanvas, secondCanvas].forEach(function(canvas) { var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { document.querySelector("p").innerHTML...
Basic scissoring - Web APIs
canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl")...
... canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { paragraph.innerHTML = "Fa...
Color masking - Web APIs
f; font-size : inherit; font-weight : 900; color : white; margin : auto; padding : 0.6em 1.2em; } #red-toggle { background-color : red; } #green-toggle { background-color : green; } #blue-toggle { background-color : blue; } window.addEventListener("load", function setupAnimation (evt) { "use strict" window.removeEventListener(evt.type, setupAnimation, false); var canvas = document.querySelector("canvas"); var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { document.querySelector("p").innerHTML = "Failed to get WebGL context." + "Your browser or device may not support WebGL."; return; } gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); var timer = setInterval(drawAnimation, 1000)...
...("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { document.querySelector("p").innerHTML = "Failed to get WebGL context." + "Your browser or device may not support WebGL."; return; } gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); var timer = setInterval(drawAnimation, 1000); var mask = [true, true, true]; var redtoggle = document.querySelector("#red-toggle"), greentoggle = document.querySelector("#green-toggle"), bluetoggle = document.querySelector("#blue-toggle"); redtoggle.addEventListener("click", setColorMask, false); greentoggle.addEventListener("click", setColorMask, false); bluetoggle.addEventListener("click", setColorMask, false); function setColorMask(evt) { var index = evt.target === g...
Raining rectangles - Web APIs
function(){ "use strict" window.addEventListener("load", setupAnimation, false); var gl, timer, rainingRect, scoreDisplay, missesDisplay; function setupAnimation (evt) { window.removeEventListener(evt.type, setupAnimation, false); if (!(gl = getRenderingContext())) return; gl.enable(gl.SCISSOR_TEST); rainingRect = new Rectangle(); timer = setTimeout(drawAnimation, 17); document.querySelector("canvas") .addEventListener("click", playerClick, false); var displays = document.querySelectorAll("strong"); scoreDisplay = displays[0]; missesDisplay = displays[1]; } var score = 0, misses = 0; function drawAnimation () { gl.scissor(rainingRect.position[0], rainingRect.position[1], rainingRect.size[0] , rainingRect.size[1]); gl.clear(gl.COLOR_BUFFER_BIT); ...
...; rect.position = [ randNums[2]*(gl.drawingBufferWidth - rect.size[0]), gl.drawingBufferHeight ]; rect.velocity = 1.0 + 6.0*Math.random(); rect.color = getRandomVector(); gl.clearColor(rect.color[0], rect.color[1], rect.color[2], 1.0); function getRandomVector() { return [Math.random(), Math.random(), Math.random()]; } } function getRenderingContext() { var canvas = document.querySelector("canvas"); canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { var paragraph = document.querySelector("p"); paragraph.innerHTML = "Failed to get WebGL context." + "Your browser or device may not support WebGL."; return null; } gl.viewport(0...
Simple color animation - Web APIs
order : none; background-color : black; } button { display : inline-block; font-size : inherit; margin : auto; padding : 0.6em; } window.addEventListener("load", function setupAnimation (evt) { "use strict" window.removeEventListener(evt.type, setupAnimation, false); // A variable to hold a timer that drives the animation. var timer; // Click event handlers. var button = document.querySelector("#animation-onoff"); var verb = document.querySelector("strong"); function startAnimation(evt) { button.removeEventListener(evt.type, startAnimation, false); button.addEventListener("click", stopAnimation, false); verb.innerHTML="stop"; // Setup animation loop by redrawing every second. timer = setInterval(drawAnimation, 1000); // Give immediate feedback ...
...vt.type, stopAnimation, false); button.addEventListener("click", startAnimation, false); verb.innerHTML="start"; // Stop animation by clearing the timer. clearInterval(timer); } // Call stopAnimation() once to setup the initial event // handlers for canvas and button. ...
Web Video Text Tracks Format (WebVTT) - Web APIs
characters). Example 19 - Ruby text tag <ruby>WWW<rt>World Wide Web</rt>oui<rt>yes</rt></ruby> Voice tag (<v></v>) Similar to class tag, also used to style the contained text using CSS. Example 20 - Voice tag <v Bob>text</v> Interfaces There are two interfaces or APIs used in WebVTT which are: VTTCue interface It is used for providing an interface in Document Object Model API, where different attributes supported by it can be used to prepare and alter the cues in number of ways. Constructor is the first point for starting the Cue which is defined using the default constructor VTTCue(startTime, endTime, text) where starting time, ending time and text for cue can be adjusted. After that we can set the region for that particular cue to which this cue be...
... The new keyword can be used for defining a new VTTRegion object which can then be used for containing the multiple cues. There are several properties of VTTRegion which are width, lines, regionAnchorX, RegionAnchorY, viewportAnchorX, viewportAnchorY and scroll that can be used to specify the look and fe...
Inputs and input sources - Web APIs
it into a series of events. Do not presume these events will happen with any particular amount of time between them. For example, if the hardware that causes the primary action to occur is a button, you would receive selectstart when the user presses the button, then select and selectend when the user releases it. There are a number of examples showing how to handle select events throughout the documentation, such as in the section on Targeting and the targeting ray elsewhere in this article. Primary squeeze action A primary squeeze action is a platform-specific action which sends the XRSession squeezestart, squeezeend, and squeeze events. This is typically generated by the user squeezing the controller, making a hand gesture that mimes grabbing something, or using (squeezing) a trigger. The ...
... the avatar's point of view). To accomplish that, we include in the avatar object a posDelta property, of type DOMPoint, which includes the offsets to apply to all three axes in order to adjust the avatar's position (the viewer pose's reference space's origin) to include movement and rotation from the keyboard and mouse. ...
Web Animations API Concepts - Web APIs
Timing and Animation The Web Animations API runs on top of two models, one that handles time--Timing--and one that handles visual change over time--Animation. The Timing Model keeps track of how far along a set timeline we've come. The Animation Model determines what the animated object should look like at any given time. Timing The Timing Model is the backbone of working with the WAAPI. Each document has a master timeline, Document.timeline, which stretches from the moment the page is loaded to infinity -- or until the window is closed. Spread along that timeline according to their durations are our animations. Each animation is anchored to a point in the timeline by its startTime, representing the moment along the document's timeline when the animation starts playing. All the animation's pl...
...p along the duration of the animation. Core Concepts Web animations consist of Timeline Objects, Animation Objects, and Animation Effect Objects working together. By assembling these disparate objects, we can create animations of our own. Timeline Timeline objects provide the useful property currentTime, which lets us see how long the page has been opened for: it's the "current time" of the document's timeline, which started when the page was opened. As of this writing, there's only one kind of timeline object: the one based on the active document's timeline. In the future we may see timeline objects that correspond to the length of the page, perhaps a ScrollTimeline, or other things entirely. Animation Animation objects can be imagined as DVD players: they're used for controlling media pl...
Web Animations API - Web APIs
meline for an animation node or source. Can take an object created with the KeyframeEffect() constructor. KeyframeEffect Describes sets of animatable properties and values, called keyframes and their timing options. These can then be played using the Animation() constructor. AnimationTimeline Represents the timeline of animation. This interface exists to define timeline features (inherited by DocumentTimeline and future timeline objects) and is not itself accessed by developers. AnimationEvent Actually part of CSS Animations. DocumentTimeline Represents animation timelines, including the default document timeline (accessed using the Document.timeline property). EffectTiming Element.animate(), KeyframeEffectReadOnly.KeyframeEffectReadOnly(), and KeyframeEffect.KeyframeEffect() all accept ...
...mentTimeline Represents animation timelines, including the default document timeline (accessed using the Document.timeline property). EffectTiming Element.animate(), KeyframeEffectReadOnly.KeyframeEffectReadOnly(), and KeyframeEffect.KeyframeEffect() all accept an optional dictionary object of timing properties. Extensions to other interfaces The Web Animations API adds some new features to document and element. Extensions to the Document interface document.timeline The DocumentTimeline object representing the default document timeline. document.getAnimations() Returns an Array of Animation objects currently in effect on elements in the document. Extensions to the Element interface Element.animate() A shortcut method for creating and playing an animation on an element. It retur...
Web Audio API best practices - Web APIs
ve. But how do we handle this? When you create an audio context (either offline or online) it is created with a state, which can be suspended, running, or closed. When working with an AudioContext, if you create the audio context from inside a click event the state should automatically be set to running. Here is a simple example of creating the context from inside a click event: const button = document.querySelector('button'); button.addEventListener('click', function() { const audioCtx = new AudioContext(); }, false); If however, you create the context outside of a user gesture, its state will be set to suspended and it will need to be started after user interaction. We can use the same click event example here, test for the state of the context and start it, if it is suspended, using th...
... const audioCtx = new AudioContext(); }, false); If however, you create the context outside of a user gesture, its state will be set to suspended and it will need to be started after user interaction. We can use the same click event example here, test for the state of the context and start it, if it is suspended, using the resume() method. const audioCtx = new AudioContext(); const button = document.querySelector('button'); button.addEventListener('click', function() { // check if context is in suspended state (autoplay policy) if (audioCtx.state === 'suspended') { audioCtx.resume(); } }, false); You might instead be working with an OfflineAudioContext, in which case you can resume the suspended audio context with the startRendering() method. User control If your w...
Controlling multiple parameters with ConstantSourceNode - Web APIs
nd gainNode3 together. playing A Boolean that we'll use to keep track of whether or not we're currently playing the tones. Now let's look at the setup() function, which is our handler for the window's load event; it handles all the initialization tasks that require the DOM to be in place. ...
... to keep track of whether or not we're currently playing the tones. Now let's look at the setup() function, which is our handler for the window's load event; it handles all the initialization tasks that require the DOM to be in place. ...
Using IIR filters - Web APIs
og approach, so let's fill our array with frequency values that get larger further on in the array items. Now let's get our response data: iirFilter.getFrequencyResponse(myFrequencyArray, magResponseOutput, phaseResponseOutput); We can use this data to draw a filter frequency plot. We'll do so on a 2d canvas context. ...
... that get larger further on in the array items. Now let's get our response data: iirFilter.getFrequencyResponse(myFrequencyArray, magResponseOutput, phaseResponseOutput); We can use this data to draw a filter frequency plot. We'll do so on a 2d canvas context. ...
Web audio spatialization basics - Web APIs
k when the boombox is rotated 180 degrees and facing away from us. We need to set up a few things for the interface. First, we'll get references to the elements we want to move, then we'll store references to the values we'll change when we set up CSS transforms to actually do the movement. ...
... a few things for the interface. First, we'll get references to the elements we want to move, then we'll store references to the values we'll change when we set up CSS transforms to actually do the movement. ...
Window: DOMContentLoaded event - Web APIs
Bubbles Yes Cancelable Yes (although specified as a simple event that isn't cancelable) Interface Event Event handler property None The original target for this event is the Document that has loaded. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Document: DOMContentLoaded event. A different event, load, should be used only to detect a fully-loaded page. ...
... A different event, load, should be used only to detect a fully-loaded page. It is a common mistake to use load where DOMContentLoaded would be more appropriate. ...
Window: beforeunload event - Web APIs
Bubbles No Cancelable Yes Interface Event Event handler property onbeforeunload This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser navigates to the new page, otherwise it cancels the navigation. According to the specification, to show the confirmation dialog an event handler should call preventDefault() on the event. ...
...ing in the confirmation dialog, enabling the event handler to display a custom message to the user. However, this is deprecated and no longer supported in most browsers. To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all. Attaching an event handler/listener to window or document's beforeunload event prevents browsers from using in-memory page navigation caches, like Firefox's Back-Forward cache or WebKit's Page Cache. The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML specification for more details. Examples The HTML specification states that authors should use the Ev...
Window.content - Web APIs
Web › API › Window › content
only available to chrome (privileged) code, and not available to the web anymore. Returns a Window object for the primary content window. This is useful in XUL windows that have a <browser> (or tabbrowser or <iframe>) with type="content-primary" attribute on it -- the most famous example is Firefox main window, browser.xul. In such cases, content returns a reference to the Window object for the document currently displayed in the browser. It is a shortcut for browserRef.contentWindow. In unprivileged content (webpages), content is normally equivalent to top (except in the case of a webpage loaded in a sidebar, content still refers to the Window of the currently selected tab). Note: Some examples use _content instead of content. The former has been deprecated for a long time, and you should us...
... Some examples use _content instead of content. The former has been deprecated for a long time, and you should use content in any new code. Syntax var windowObject = window.content; Example Executing the following code in a chrome XUL window with a <browser type="content-primary"/> element in it draws a red border around the first div on the page currently displayed in the browser: content.document.getElementsByTagName("div")[0].style.border = "solid red 1px"; Specification None. See also Working with windows in chrome code When accessing content documents from privileged code, be aware of XPCNativeWrappers. ...
Window.devicePixelRatio - Web APIs
ays 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(size * scale); canvas.hei...
...reen 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. ...
Window.frames - Web APIs
Web › API › Window › frames
frameList is a list of frame objects. It is similar to an array in that it has a length property and its items can be accessed using the [i] notation. frameList === window evaluates to true. ...
...)frame DOM element (i.e., window.frames[0] is the same thing as document.getElementsByTagName("iframe")[0].contentWindow). For more details about the returned value, refer to this thread on mozilla.dev.platform. Example var frames = window.frames; // or // var frames = window.parent.frames; for (var i = 0; i < frames.length; i++) { // do something with each subframe as frames[i] frames[i].document.body.style.background = "red"; } Specifications Specification Status Comment HTML Living StandardThe definition of 'Window.frames' in that specification. Living Standard HTML5The definition of 'Window.frames' in that specification. Recommendation ...
Window.scrollBy() - Web APIs
Web › API › Window › scrollBy
See also window.scrollByLines() and window.scrollByPages(). ...
... by. - or - options is a ScrollToOptions dictionary. Examples To scroll down one page: window.scrollBy(0, window.innerHeight); To scroll up: window.scrollBy(0, -window.innerHeight); Using options: window.scrollBy({ top: 100, left: 100, behavior: 'smooth' }); Notes window.scrollBy() scrolls by a particular amount, whereas window.scroll() scrolls to an absolute position in the document. See also window.scrollByLines() and window.scrollByPages(). Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'window.scrollBy()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table in this page is generated from structured data. If you'd like to contribut...
WindowEventHandlers.onhashchange - Web APIs
following properties: Field Type Description newURL DOMString The new URL to which the window is navigating. oldURL DOMString The previous URL from which the window was navigated. ...
...t.newURL and event.oldURL // Let this snippet run before your hashchange event binding code if (!window.HashChangeEvent)(function(){ var lastURL = document.URL; window.addEventListener("hashchange", function(event){ Object.defineProperty(event, "oldURL", {enumerable:true,configurable:true,value:lastURL}); Object.defineProperty(event, "newURL", {enumerable:true,configurable:true,value:document.URL}); lastURL = document.URL; }); }()); Specifications Specification Status Comment HTML Living StandardThe definition of 'onhashchange' in that specification. Living Standard HTML 5.1The definition of 'GlobalEventHandlers' in that specification. Recommendation HTML5The definition of 'GlobalEventHandlers' in that specificatio...
WindowEventHandlers.onpopstate - Web APIs
The onpopstate property of the WindowEventHandlers mixin is the EventHandler for processing popstate events on the window. A popstate event is dispatched to the window each time the active history entry changes between two history entries for the same document. If the activated history entry was created by a 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...
...cking 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. ...
WindowOrWorkerGlobalScope.fetch() - Web APIs
horization header. Examples In our Fetch Request example (see Fetch Request live) we create a new Request object using the relevant constructor, then fetch it using a fetch() call. Since we are fetching an image, we run Body.blob() on the response to give it the proper MIME type so it will be handled properly, then create an Object URL of it and display it in an <img> element. ...
...}); You could also pass the init object in with the Request constructor to get the same effect:...
Worker - Web APIs
Web › API › Worker
ts parent, EventTarget, and implements properties from AbstractWorker. Event handlers AbstractWorker.onerror An EventListener called whenever an ErrorEvent of type error bubbles through to the worker. This is inherited from AbstractWorker. Worker.onmessage An EventListener called whenever a MessageEvent of type message bubbles through the worker -- i.e. when a message is sent to the parent document 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 Jav...
...able through the onrejectionhandled event handler property. unhandledrejection Fires when a Promise rejects with no handler to catch the rejection. Also available using the onunhandledrejection event handler property. Example The following code snippet creates a Worker object using the Worker() constructor, then uses the worker object: var myWorker = new Worker('/worker.js'); var first = document.querySelector('input#number1'); var second = document.querySelector('input#number2'); first.onchange = function() { myWorker.postMessage([first.value, second.value]); console.log('Message posted to worker'); } For a full example, see ourBasic dedicated worker example (run dedicated worker). Specifications Specification Status Comment HTML Living StandardThe definit...
WorkerGlobalScope.location - Web APIs
The location read-only property of the WorkerGlobalScope interface returns the WorkerLocation associated with the worker. It is a specific location object, mostly a subset of the Location for browsing scopes, but adapted to workers. Syntax var locationObj = self.location; Value A WorkerLocation object. ...
... Note: Firefox has a bug with using console.log inside shared/service workers (see bug 1058644), which may return strange results, but this should be fixed soon. Specifications Specification Status Comment HTML Living StandardThe definition of 'location' in that specification. Living Standard ...
WritableStream.WritableStream() - Web APIs
called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
... queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink error:", err); } }, queuingStrategy...
WritableStream.getWriter() - Web APIs
called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
... queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink error:", err); } }, queuingStrategy...
WritableStream - Web APIs
called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
... queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink error:", err); } }, queuingStrategy...
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
... queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink error:", err); } }, queuingStrategy...
WritableStreamDefaultWriter.close() - Web APIs
called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
... queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink error:", err); } }, queuingStrategy...
WritableStreamDefaultWriter.write() - Web APIs
called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
... queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink error:", err); } }, queuingStrategy...
WritableStreamDefaultWriter - Web APIs
ed sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...rategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink error:", err); } }, ...
Sending and Receiving Binary Data - Web APIs
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. ...
... Receiving binary data using JavaScript typed arrays The responseType property of the XMLHttpRequest object can be set to change the expected response type from the server. 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. var oReq = new XMLHttpRequest(); oReq.open("GET", "/myfile.png", true); oReq.responseType = "arraybuffer"; ...
XMLHttpRequest.multipart - Web APIs
for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. Obsolete since Gecko 22 This Gecko-only feature was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or responseText from progress events instead. This boolean indicates if the response is expected to be a stream of possibly multiple XML documents. If set to true, the content type of the initial response must be multipart/x-mixed-replace or an error will occur. All requests must be asynchronous. This enables support for server push; for each XML document that's written to this request, a new XML DOM document is created and the onload handler is called between documents. Note: When this is set, the onload handler and other event handler...
... of the initial response must be multipart/x-mixed-replace or an error will occur. All requests must be asynchronous. This enables support for server push; for each XML document that's written to this request, a new XML DOM document is created and the onload handler is called between documents. Note: When this is set, the onload handler and other event handlers are not reset after the first XMLdocument is loaded, and the onload handler is called after each part of the response is received. ...
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. ...
...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. 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 in a DOMString object. ms-stream The response is part of a streaming d...
XMLHttpRequest.responseType - Web APIs
ver 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. 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 in a DOMString object. ms-stream The response is part of a streaming d...
... to help ensure that synchronous operations aren't used for large transactions that block the browser's main thread, thereby bogging down the user experience. XMLHttpRequests are asynchronous by default; they are only placed in synchronous mode by passing false as the value of the optional async parameter when calling open(). Restrictions in Workers Attempts to set the value of responseType to document are ignored in a Worker. Specifications Specification Status Comment XMLHttpRequest Living Standard WHATWG living standard ...
XMLHttpRequest.responseXML - Web APIs
Note: The name responseXML is an artifact of this property's history; it works for both HTML and XML. Usually, the response is parsed as "text/xml". If the responseType is set to "document" and the request was made asynchronously, instead the response is parsed as "text/html". responseXML is null for any other types of data, as well as for data: URLs. If the server doesn't specify the Content-Type as "text/xml" or "application/xml", you can use XMLHttpRequest.overrideMimeType() to parse it as XML anyway. ...
...e asynchronously, instead the response is parsed as "text/html". responseXML is null for any other types of data, as well as for data: URLs. If the server doesn't specify the Content-Type as "text/xml" or "application/xml", you can use XMLHttpRequest.overrideMimeType() to parse it as XML anyway. This property isn't available to workers. Syntax var data = XMLHttpRequest.responseXML; Value A Document from parsing the XML or HTML received using XMLHttpRequest, or null if no data was received or if the data is not XML/HTML. Exceptions InvalidStateError The responseType isn't either "document" or an empty string. Example var xhr = new XMLHttpRequest; xhr.open('GET', '/server'); // If specified, responseType must be empty string or "document" xhr.responseType = 'document'; // Force the ...
XPathEvaluator.createNSResolver() - Web APIs
This adapter works like the DOM Level 3 method Node.lookupNamespaceURI() in resolving the namespace URI from a given prefix using the current information available in the node's hierarchy at the time the method is called, also correctly resolving the implicit xml prefix. Syntax XPathNSResolver XPathEvaluator.createNSResolver(nodeResolver); Parameters nodeResolver A Node to be used as a context for namespace resolution. ...
...ctly resolving the implicit xml prefix. Syntax XPathNSResolver XPathEvaluator.createNSResolver(nodeResolver); Parameters nodeResolver A Node to be used as a context for namespace resolution. Return value An XPathNSResolver object which resolves namespaces with respect to the definitions in scope for a specified node. Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathEvaluator.createNSResolver()' in that specification. Recommendation Initial definition ...
XPathEvaluator - Web APIs
Methods XPathEvaluator.createExpression() Creates a parsed XPath expression with resolved namespaces. XPathEvaluator.createNSResolver() Adapts any DOM node to resolve namespaces allowing the XPath expression to be evaluated relative to the context of the node where it appeared within the document. XPathEvaluator.evaluate() Evaluates an XPath expression string and returns a result of the specified type if possible. Example The following example shows the use of the XPathEvaluator interface. ...
... expression string and returns a result of the specified type if possible. Example The following example shows the use of the XPathEvaluator interface. HTML <div>XPath example</div> <div>Number of &lt;div&gt;s: <output></output></div> JavaScript var xpath = "//div"; var evaluator = new XPathEvaluator(); var expression = evaluator.createExpression("//div"); var result = expression.evaluate(document, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE); document.querySelector("output").textContent = result.snapshotLength; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathEvaluator' in that specification. Recommendation Initial definition ...
XPathResult.booleanValue - Web APIs
Exceptions TYPE_ERR In case XPathResult.resultType is not BOOLEAN_TYPE, an XPathException of type TYPE_ERR is thrown. ...
...he XPathResult returned by Document.evaluate(). Exceptions TYPE_ERR In case XPathResult.resultType is not BOOLEAN_TYPE, an XPathException of type TYPE_ERR is thrown. Example The following example shows the use of the booleanValue property. HTML <div>XPath example</div> <p>Text is 'XPath example': <output></output></p> JavaScript var xpath = "//div/text() = 'XPath example'"; var result = document.evaluate(xpath, document, null, XPathResult.BOOLEAN_TYPE, null); document.querySelector("output").textContent = result.booleanValue; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathResult.booleanValue' in that specification. Recommendation Initial definition ...
XPathResult.numberValue - Web APIs
Exceptions TYPE_ERR In case XPathResult.resultType is not NUMBER_TYPE, an XPathException of type TYPE_ERR is thrown. ...
...umeric value of the XPathResult returned by Document.evaluate(). Exceptions TYPE_ERR In case XPathResult.resultType is not NUMBER_TYPE, an XPathException of type TYPE_ERR is thrown. Example The following example shows the use of the numberValue property. HTML <div>XPath example</div> <div>Number of &lt;div&gt;s: <output></output></div> JavaScript var xpath = "count(//div)"; var result = document.evaluate(xpath, document, null, XPathResult.NUMBER_TYPE, null); document.querySelector("output").textContent = result.numberValue; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathResult.numberValue' in that specification. Recommendation Initial definition ...
XPathResult.singleNodeValue - Web APIs
The read-only singleNodeValue property of the XPathResult interface returns a Node value or null in case no node was matched of a result with XPathResult.resultType being ANY_UNORDERED_NODE_TYPE or FIRST_ORDERED_NODE_TYPE. Note: This feature is available in Web Workers. Syntax var value = result.singleNodeValue; Return value The return value is the Node value of the XPathResult returned by Document.evaluate(). Exceptions TYPE_ERR In case XPathResult.resultType is not ANY_UNORDERED_NODE_TYPE or FIRST_ORDERED_NODE_TYPE, an XPathException of type TYPE_ERR is thrown. Example The following example shows the use of the singleNodeValue property. HTML <div>XPath example</div> <div>Tag name of the element having the text content 'XPath example': <output></output></div> JavaScript var xpath...
...thResult.resultType is not ANY_UNORDERED_NODE_TYPE or FIRST_ORDERED_NODE_TYPE, an XPathException of type TYPE_ERR is thrown. Example The following example shows the use of the singleNodeValue property. HTML <div>XPath example</div> <div>Tag name of the element having the text content 'XPath example': <output></output></div> JavaScript var xpath = "//*[text()='XPath example']"; var result = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); document.querySelector("output").textContent = result.singleNodeValue.localName; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathResult.singleNodeValue' in that specification. Recommendation Initial defini...
XPathResult.stringValue - Web APIs
Exceptions TYPE_ERR In case XPathResult.resultType is not STRING_TYPE, an XPathException of type TYPE_ERR is thrown. ...
... the XPathResult returned by Document.evaluate(). Exceptions TYPE_ERR In case XPathResult.resultType is not STRING_TYPE, an XPathException of type TYPE_ERR is thrown. Example The following example shows the use of the stringValue property. HTML <div>XPath example</div> <div>Text content of the &lt;div&gt; above: <output></output></div> JavaScript var xpath = "//div/text()"; var result = document.evaluate(xpath, document, null, XPathResult.STRING_TYPE, null); document.querySelector("output").textContent = result.stringValue; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathResult.stringValue' in that specification. Recommendation Initial definition ...
XRSession.visibilityState - Web APIs
the session is not currently visible at all. In order to optimize resource utilization, the user agent may be handling the session's requestAnimationFrame() callbacks at a throttled rate. Input controllers are not being processed for the session. ...
...llbacks at a throttled rate. Input controllers are not being processed for the session. Usage notes It's important to keep in mind that because an immersive WebXR session is potentially being shown using a different display than the HTML document in which it's running (such as when being shown on a headset), the value of a session's visibilityState may not necessarily be the same as the owning document's visibilityState. For instance, if the viewer is using a headset tethered to a computer and the immersive scene is obscured by a configuration UI, the user could peek out from behind the headset and still be able to see the document itself on their computer's monitor. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSession.visibility...
XRSystem: isSessionSupported() - Web APIs
the browser doesn't have permission to use the XR device, the promise is rejected with an appropriate DOMException. Syntax var isSupportedPromise = xr.isSessionSupported(xrSessionMode) Parameters xrSessionMode A DOMString specifying the WebXR session mode for which support is to be checked. This string must be one of inline (to present the WebXR content inline within the context of an HTML document) or immersive-vr for a fully-immersive virtual experience. Return value A Promise that resolves to true if the specified session mode is supported; otherwise the promise resolves to false. Exceptions Rather than throwing true exceptions, isSessionSupported() rejects the returned promise, passing to the rejection handler a DOMException whose name is one of the following strings. SecurityEr...
...rsive-vr for a fully-immersive virtual experience. Return value A Promise that resolves to true if the specified session mode is supported; otherwise the promise resolves to false. Exceptions Rather than throwing true exceptions, isSessionSupported() rejects the returned promise, passing to the rejection handler a DOMException whose name is one of the following strings. SecurityError The document's origin does not have permission to use the xr-spatial-tracking feature policy. Examples In this example, we see isSessionSupported() used to detect whether or not the device supports VR mode by checking to see if an immersive-vr session is supported. If it is, we set up a button to read "Enter XR", to call a method onButtonClicked(), and enable the button. If no session is already underway,...
Using the aria-activedescendant attribute - Accessibility
It makes do with the overhead of having all or more than one child focusable. As the name specifies, it helps in managing the current active child of the composite widget. ...
...and assistive technology The user agent, which is any software that retrieves, renders and facilitates end user interaction with Web content, uses the aria-activedescendant property to inform the assistive technology about the active child which has focus. This active child using the aria-activedescendant property must always be visible on screen and must be a descendant of the container in the Document Object Model. Note: Opinions may differ on how assistive technology should handle this technique. The information provided below is one of those opinions and therefore not normative. Examples Example 1: Code Working Examples: Notes ARIA attributes used Related ARIA techniques Compatibility TBD: Add support information for common UA and AT product combinations Additional resour...
Using the aria-describedby attribute - Accessibility
r. <div role="application" aria-labelledby="calendar" aria-describedby="info"> <h1 id="calendar">Calendar</h1> <p id="info"> This calendar shows the game schedule for the Boston Red Sox. </p> <div role="grid"> ... </div> </div> Example 2: A Close Button In the example below, a link that functions as a 'close' button on a dialog is described elsewhere in the document. The aria-describedby attribute is used to associate the description with the link. <button aria-label="Close" aria-describedby="descriptionClose" onclick="myDialog.close()">X</button> ... <div id="descriptionClose">Closing this window will discard any information entered and return you back to the main page</div> Working Examples: Checkbox example uses aria-describedby Tooltip examp...
... Used by ARIA roles all elements of the base markup Related ARIA techniques Using the aria-labelledby attribute Compatibility TBD: Add support information for common UA and AT product combinations Additional resources WAI-ARIA specification for aria-describedby ...
Using the aria-invalid attribute - Accessibility
ry to validate the fields immediately on blur; the application could wait until the form is submitted (though this is not necessarily recommended). ...
...entById(aID); var invalid = (elem.value.indexOf(aSearchTerm) < 0); if (invalid) { elem.setAttribute("aria-invalid", "true"); updateAlert(aMsg); } else { elem.setAttribute("aria-invalid", "false"); updateAlert(); } } The snippet below shows the alert functions, which add (or remove) the error message: function updateAlert(msg) { var oldAlert = document.getElementById("alert"); if (oldAlert) { document.body.removeChild(oldAlert); } if (msg) { var newAlert = document.createElement("div"); newAlert.setAttribute("role", "alert"); newAlert.setAttribute("id", "alert"); var content = document.createTextNode(msg); newAlert.appendChild(content); document.body.appendChild(newAlert); ...
Using the article role - Accessibility
Examples of an article include web log posts, newspaper or magazine articles and use-submitted comments. It is independent in that its contents could stand alone, for example in syndication. Articles can be nested; for example, a web log entry on a site that accepts user-submitted comments could represent the comments as articles nested within the article for the web log entry. The ARIA article role is similar to the HTML5 article element; however the article element should still be given the ARIA role of article, since not all assistive technologies support HTML5 yet. ...
...rticle role is similar to the HTML5 article element; however the article element should still be given the ARIA role of article, since not all assistive technologies support HTML5 yet. Possible effects on user agents and assistive technology When the user navigates an element assigned the role of article, assistive technologies that typically intercept standard keyboard events SHOULD switch to document browsing mode, as opposed to passing keyboard events through to the web application. Assistive technologies MAY provide a feature allowing the user to navigate the hierarchy of any nested article elements. Note: Opinions may differ on how assistive technology should handle this technique. The information provided above is one of those opinions and therefore not normative. Examples <article ro...
Using the slider role - Accessibility
ponse to user input. <label for="fader">Volume</label> <input type="range" id="fader" min="1" max="100" value="50" step="1" aria-valuemin="1" aria-valuemax="100" aria-valuenow="50" oninput="outputUpdate(value)"> <output for="fader" id="volume">50</output> The following code snippet allows you to return the output as it is updated by user input: function outputUpdate(vol) { document.querySelector('#volume').value = vol; } Example 2: Text Values Sometimes, a slider is used to choose a value that is not, semantically, a number. In these cases, the aria-valuetext attribute is used to provide the appropriate text name for the currently selected value. In the example below, the slider is used to select a day of the week. <label id="day-label">Days</label> <div class="day-slid...
... aria-valuemin="1" aria-valuemax="7" aria-valuenow="2" aria-valuetext="Monday"> </div> </div> The code snippet below shows a function that responds to user input and updates the aria-valuenow and aria-valuetext attributes: var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var updateSlider = function (newValue) { var handle = document.getElementById("day-handle"); handle.setAttribute("aria-valuenow", newValue.toString()); handle.setAttribute("aria-valuetext", dayNames[newValue]); }; Working Examples: Slider example Notes ARIA attributes used aria-valuemin aria-valuemax aria-valuenow aria-valuetext aria-orientation Related ARIA techniques Compatibility TBD: Add support information for common U...
Using ARIA: Roles, states, and properties - Accessibility
slider spinbutton switch tab tabpanel textbox treeitem Composite roles The techniques below describe each composite role as well as their required and optional child roles. ...
...es below describe each composite role as well as their required and optional child roles. ...
ARIA: Comment role - Accessibility
The commented section is marked up using <span role="mark">. The related comment is marked up using an HTML structure wrapped with a <div> containing role="comment". ...
...></p> <div role="comment" data-author="marcus"> <h3>Marcus replied</h3> <p class="comment-text">I don't know about that. I think the cowbell could distract from the solo.</p> <p><time datetime="2019-03-30T21:02">March 30 2019, 21:02</time></p> </div> </div> Accessibility concerns Landmark roles are intended to be used sparingly, to identify larger overall sections of the document. Using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. Specifications Will be part of WAI-ARIA 1.3, which is still being drafted. Screen reader support TBD ...
ARIA: Mark role - Accessibility
The commented section is marked up using <span role="mark">. ...
... marked up using an HTML structure wrapped with a <div> containing role="comment". To associate the comment with the text being commented, we need to wrap the commented text with an element containing the aria-details attribute, the value of which should be the ID of the comment. Accessibility concerns Landmark roles are intended to be used sparingly, to identify larger overall sections of the document. Using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. Best practices Prefer HTML Using the <mark> element will automatically communicate a section has a role of mark. If at all possible, prefer using it instead. Specifications Will be part of WAI-ARIA 1.3, which is still being drafted. Screen reader support TB...
ARIA: Suggestion role - Accessibility
This should be used on an element that wraps an element with an insertion role, and one with a deletion role. Examples When you've got a content change that involves an insertion and a deletion, there is no way for a screenreader user to work out if the two are related or not. This is the job of role="suggestion", which should be set on an element wrapping both of them like so: <p>Freida's pet is a <span role="suggestion"> <span role="deletion">black Cat called Luna</span> <span role="insertion">purple Tyrannosaurus Rex called Tiny</span> </span>. ...
...iny</span> </span>. </p> <div id="comment-source">Suggested by Chris, <time datetime="2019-03-30T19:29">March 30 2019, 19:29</time></div> Browsers tend to provide a default black strikethrough for deletions, and a black underline for insertions, but you'll probably want to use Accessibility concerns Landmark roles are intended to be used sparingly, to identify larger overall sections of the document. Using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. Best practices Prefer HTML Using the <ins> and <del> element will automatically communicate a section has a role of insertion or deletion. If at all possible, prefer using the HTML elements. Specifications Will be part of WAI-ARIA 1.3, which is still being dr...
ARIA: tab role - Accessibility
the parent element and sets it to false, then sets the triggering element's aria-selected to true. After that, we find all tabpanel elements in the grandparent element, make them all hidden, and finally select the element whose id is equal to the triggering tab's aria-controls and removes the hidden attribute, making it visible. ...
...ering element's aria-selected to true. After that, we find all tabpanel elements in the grandparent element, make them all hidden, and finally select the element whose id is equal to the triggering tab's aria-controls and removes the hidden attribute, making it visible. ...
ARIA: heading role - Accessibility
ke a heading. In addition, the level tells assistive technologies which part of the page structure this heading represents. A level 1 heading usually indicates the main heading of a page, a level 2 heading the first subsection, a level 3 is a subsection of that, and so on. Associated WAI-ARIA 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 dynam...
...igation. 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 to indicate that this text is a heading, and what part of the structure it represents. Examples The following shows a typical page structure. <div id="container"> <div role="heading" aria-level="1">The main page heading</div> <p>This article is about s...
Basic form hints - Accessibility
For more guidance on using ARIA for forms accessi...
... ...
ARIA - Accessibility
aluemax 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", "progressbar"); progressBar.setAttribute("aria-valuemin", 0); progressBar.setAttribute("aria-valuemax", 100); // Create a function that can be called at any time to update // the value of the progress bar. function updateProgress(...
...A quick summary of live regions, by the makers of JAWS screen reader software. Live regions are also supported by NVDA with Firefox, and VoiceOver with Safari. References ARIA Roles Reference pages covering all the WAI-ARIA roles discussed on MDN. Standardization Efforts WAI-ARIA Specification The W3C specification itself. WAI-ARIA Authoring Practices The official best practices documents how best to ARIA-ify common widgets and interactions. An excellent resource. Videos Following talks are a great way to understand ARIA: ARIA, Accessibility APIs and coding like you give a damn! - Leonie Watson Filing Bugs File ARIA bugs on browsers, screen readers, and JavaScript libraries. Related topics Accessibility, AJAX, JavaScript ...
Understandable - Accessibility
web page should be detectable via code. This is essential for purposes like making sure the reader has arrived at a page written in a language suitable for them. The simplest way to achieve this is to set the lang attribute on the page's <html> element, giving it a value equal to the language code that best represents the language the page is written in. See Setting the primary language of the document. 3.1.2 Language of Parts (AA) In cases where the content of a page includes words or phrases that are in a different language to the primary language, use the lang attribute on an element wrapped around the term in question (e.g. a <span> if no semantic element is available) to set an appropriate language for it. You don't need to set a different language for words or phrase...
...round 11-14 years old), provide supplementary explainer material to help people who can't read it, or provide an alternative version that is written at lower secondary level. This doesn't mean that all subject matter should be understood by everyone, but that the style of writing should be accessible by everyone. It is better to just write all content at lower secondary level, even technical documentation like programming tutorials, unless there is a good reason not to (e.g. an alternative style for poetic effect), or they have to be written in a strict style (e.g. W3C specs). 3.1.6 Pronunciation (AAA) A mechanism should be provided to give users access to pronounciation of words where they are is needed to understand the content fully. The HTML5 <audio> element ...
Accessibility
stood by assistive technologies and their users. This article shows how. Mobile accessibility With web access on mobile devices being so popular, and popular platforms such as iOS and Android having fully-fledged accessibility tools, it is important to consider the accessibility of your web content on these platforms. This article looks at mobile-specific accessibility considerations. Other documentation Understanding the Web Content Accessibility Guidelines This set of articles provides quick explanations to help you understand the steps that need to be taken to conform to the recommendations outlined in the W3C Web Content Accessibility Guidelines 2.0 (WCAG 2.0 or just WCAG, for the purposes of this writing). Keyboard-navigable JavaScript widgets Until now, web developers who wan...
...AG, 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 collection of articles intended for AT developers Mobile accessibility checklist This document provides a concise checklist of accessibility requirements for mobile app developers. Cognitive accessibility When creating web content, be aware of how you can ensure that it is accessible to people cognitive impairments. Accessibility fo...
-moz-image-rect - CSS: Cascading Style Sheets
v> </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. ...
...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 var curStyle = window.getComputedStyle(document.getElementById(curId), null).getPropertyValue("background-image"); document.getElementById(curId).style.backgroundImage = prevStyle; prevStyle = curStyle; } } This uses window.getComputedStyle() to fetch the style of each element, shifting it to the following element. Notice that before it begins doing so it saves a copy of the last box's style since it will be overwritten by the third...
:defined - CSS: Cascading Style Sheets
Web › CSS › :defined
lement */ simple-custom:defined { display: block; } Syntax :defined Examples Hiding elements until they are defined The following snippets are taken from our defined-pseudo-class demo (see it live also). ...
...e define a very simple trivial custom element: customElements.define('simple-custom', class extends HTMLElement { constructor() { super(); let divElem = document.createElement('div'); divElem.textContent = this.getAttribute('text'); let shadowRoot = this.attachShadow({mode: 'open'}) .appendChild(divElem); } }) Then insert a copy of this element into the document, along with a standard <p>: <simple-custom text="Custom element example text"></simple-custom> <p>Standard paragraph example text</p> In the CSS we first include the following rules: // Give the two elements distinctive backgrounds p { background: yellow; } simple-custom { background: cyan; } // Both the custom and the built-in element are given italic text :defined { font-style: ital...
:dir() - CSS: Cascading Style Sheets
Web › CSS › :dir
It doesn't account for styling directionality, i.e., the directionality set by CSS properties such as direction. ...
...ent to the [dir=...] attribute selectors. The latter match the HTML dir attribute, and ignore elements that lack it -- even if they inherit a direction from their parent. (Similarly, [dir=rtl] and [dir=ltr] won't match the auto value.) In contrast, :dir() will match the value calculated by the user agent, even if inherited. Note: In HTML, the direction is determined by the dir attribute. Other document types may have different methods. Syntax The :dir() pseudo-class requires one parameter, representing the text directionality you want to target. Parameters ltr Target left-to-right elements. rtl Target right-to-left elements. Formal syntax :dir( ltr | rtl ) Examples HTML <div dir="rtl"> <span>test1</span> <div dir="ltr">test2 <div dir="auto">?????</div> </div> </div> ...
:first - CSS: Cascading Style Sheets
Web › CSS › :first
The :first CSS pseudo-class, used with the @page at-rule, represents the first page of a printed document. (See :first-child for general first element of a node.) /* Selects the first page when printing */ @page :first { margin-left: 50%; margin-top: 50%; } Note: You can't change all CSS properties with this pseudo-class. 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. ...
...The words on the first page should be somewhere around the center, while other pages will have their contents at the default position. ...
:has() - CSS: Cascading Style Sheets
Web › CSS › :has
The :has() CSS pseudo-class represents an element if any of the selectors passed as parameters (relative to the :scope of the given element) match at least one element. ...
...ing-token> | <ident-token> ] <attr-modifier>? ']'where <attr-matcher> = [ '~' | | | '^' | '$' | '*' ]? '='<attr-modifier> = i | s Description The :has() pseudo-class takes a relative selector list as an argument. In earlier revisions of the CSS Selectors Level 4 specification, :has had a limitation that it couldn't be used within stylesheets. Instead, it could only be used with functions like document.querySelector(); this was due to performance concerns. This limitation has been removed because no browser implemented it that way. Instead, browsers currently only support the use of :has() within stylesheets. Examples Matching <a> elements that directly contain an <img> The following selector matches only <a> elements that directly contain an <img> child: a:has(> img) Matching <h1> elemen...
:lang() - CSS: Cascading Style Sheets
Web › CSS › :lang
The :lang() CSS pseudo-class matches elements based on the language they are determined to be in. /* Selects any <p> in English (en) */ p:lang(en) { quotes: '\201C' '\201D' '\2018' '\2019'; } Note: In HTML, the language is determined by a combination of the lang attribute, the <meta> element, and possibly by information from the protocol (such as HTTP headers). For other document types there may be other document methods for determining the language. Syntax Formal syntax :lang( <language-code> ) Parameter <language-code> A <string> representing the language you want to target. Acceptable values are specified in the HTML spec. Examples In this example, the :lang() pseudo-class is used to match the parents of quote elements (<q>) using child combinators. Note that this doesn't illu...
...anguage-code> ) Parameter <language-code> A <string> representing the language you want to target. Acceptable values are specified in the HTML spec. Examples In this example, the :lang() pseudo-class is used to match the parents of quote elements (<q>) using child combinators. Note that this doesn't illustrate the only way to do this, and that the best method to use depends on the type of document. Also note that Unicode values are used to specify some of the special quote characters. HTML <div lang="en"><q>This English quote has a <q>nested</q> quote inside.</q></div> <div lang="fr"><q>This French quote has a <q>nested</q> quote inside.</q></div> <div lang="de"><q>This German quote has a <q>nested</q> quote inside.</q></div> CSS :lang(en) > q { quotes: '\201C' '\201D' '\2018' '\2019'...
:root - CSS: Cascading Style Sheets
Web › CSS › :root
Working Draft No change. ...
... Working Draft No change. ...
scripting - CSS: Cascading Style Sheets
Web › CSS › @media › scripting
Examples HTML <p class="script-none">You do not have scripting available. ...
... Examples HTML <p class="script-none">You do not have scripting available. ...
@media - CSS: Cascading Style Sheets
Web › CSS › @media
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. ...
...900px) { article { display: flex; } } } For a discussion of media query syntax, please see Using media queries. Description Media types Media types describe the general category of a device. Except when using the not or only logical operators, the media type is optional and the all type will be implied. all Suitable for all devices. print Intended for paged material and documents viewed on a screen in print preview mode. (Please see paged media for information about formatting issues that are specific to these formats.) screen Intended primarily for screens. speech Intended for speech synthesizers. Deprecated media types: CSS2.1 and Media Queries 3 defined several additional media types (tty, tv, projection, handheld, braille, embossed, and aural), but they were de...
@namespace - CSS: Cascading Style Sheets
espace */ @namespace url(XML-namespace-URL); @namespace "XML-namespace-URL"; /* Prefixed namespace */ @namespace prefix url(XML-namespace-URL); @namespace prefix "XML-namespace-URL"; Description The defined namespaces can be used to restrict the universal, type, and attribute selectors to only select elements within that namespace. The @namespace rule is generally only useful when dealing with documents containing multiple namespaces--such as HTML5 with inline SVG or MathML, or XML that mixes multiple vocabularies. Any @namespace rules must follow all @charset and @import rules, and precede all other at-rules and style declarations in a style sheet. @namespace can be used to define the default namespace for the style sheet. When a default namespace is defined, all universal and type selectors...
...pe, or attribute selector is prefixed with a namespace prefix, then that selector only matches if the namespace and name of the element or attribute matches. In HTML5, known foreign elements will automatically be assigned namespaces. This means that HTML elements will act as though they are in the XHTML namespace (http://www.w3.org/1999/xhtml), even if there is no xmlns attribute anywhere in the document, and the <svg> and <math> elements will be assigned their proper namespaces (http://www.w3.org/2000/svg and http://www.w3.org/1998/Math/MathML). Note: In XML, unless a prefix is defined directly on an attribute (e.g., xlink:href), that attribute has no namespace. In other words, attributes do not inherit the namespace of the element they're on. To match this behaviour, the default namespace in ...
max-zoom - CSS: Cascading Style Sheets
<number> A non-negative number limiting the maximum value of the zoom factor. <percentage> A non-negative percentage limiting the maximum value of the zoom factor. ...
... browser will not zoom in any further than this, whether automatically or at the user's request. A zoom factor of 1.0 or 100% corresponds to no zooming. Larger values are zoomed in. Smaller values are zoomed out. Syntax /* Keyword value */ max-zoom: auto; /* <number> values */ max-zoom: 0.8; max-zoom: 2.0; /* <percentage> value */ max-zoom: 150%; Values auto The user agent will set the document's upper zoom factor limit. <number> A non-negative number limiting the maximum value of the zoom factor. <percentage> A non-negative percentage limiting the maximum value of the zoom factor. Formal definition Related at-rule@viewportInitial valueautoPercentagesthe zoom factor itselfComputed valueauto, or a non-negative number or percentage as specified Formal syntax auto | <number> | <pe...
min-zoom - CSS: Cascading Style Sheets
<number> A non-negative number limiting the minimum value of the zoom factor. <percentage> A non-negative percentage limiting the minimum value of the zoom factor. ...
...browser will not zoom out any further than this, whether automatically or at the user's request. A zoom factor of 1.0 or 100% corresponds to no zooming. Larger values are zoomed in. Smaller values are zoomed out. Syntax /* Keyword value */ min-zoom: auto; /* <number> values */ min-zoom: 0.8; min-zoom: 2.0; /* <percentage> value */ min-zoom: 150%; Values auto The user agent will set the document's lower zoom factor limit. <number> A non-negative number limiting the minimum value of the zoom factor. <percentage> A non-negative percentage limiting the minimum value of the zoom factor. Formal definition Related at-rule@viewportInitial valueautoPercentagesthe zoom factor itselfComputed valueauto, or a non-negative number or percentage as specified Formal syntax auto | <number> | <pe...
At-rules - CSS: Cascading Style Sheets
Web › CSS › At-rule
et of nested statements, which can be used as a statement of a style sheet as well as inside of conditional group rules: @media -- A conditional group rule that will apply its content if the device meets the criteria of the condition defined using a media query. @supports -- A conditional group rule that will apply its content if the browser meets the criteria of the given condition. @document -- A conditional group rule that will apply its content if the document in which the style sheet is applied meets the criteria of the given condition. (deferred to Level 4 of CSS Spec) @page -- Describes the aspect of layout changes that will be applied when printing the document. @font-face -- Describes the aspect of an external font to be downloaded. @keyframes -- Describes the aspec...
...e nested statements--either rulesets or nested at-rules. Furthermore, they all convey a common semantic meaning--they all link some type of condition, which at any time evaluates to either true or false. If the condition evaluates to true, then all of the statements within the group will be applied. Conditional group rules are defined in CSS Conditionals Level 3 and are: @media, @supports, @document. (deferred to Level 4 of CSS Spec) Since each conditional group may also contain nested statements, there may be an unspecified amount of nesting. Specifications Specification Status Comment CSS Conditional Rules Module Level 3 Candidate Recommendation Initial definition Compatibility StandardThe definition of 'CSS At-rules' in that specification. Li...
CSS Conditional Rules - CSS: Cascading Style Sheets
CSS Conditional Rules is a CSS module that allows to define a set of rules that will only apply based on the capabilities of the processor or the document the style sheet is being applied to. ...
... CSS Conditional Rules is a CSS module that allows to define a set of rules that will only apply based on the capabilities of the processor or the document the style sheet is being applied to. ...
CSS Containment - CSS: Cascading Style Sheets
The aim of the CSS Containment specification is to improve performance of web pages by allowing developers to isolate a subtree of the page from the rest of the page. If the browser knows that a part of the page is independent, rendering can be optimized and performance improved. The specification defines a single CSS property contain. This document describes the basic aims of the specification. Basic example Many webpages contain a number of sections which are independent of each other. For example a listing of article headlines and content, as in the mark-up below. <h1>My blog</h1> <article> <h2>Heading of a nice article</h2> <p>Content here.</p> </article> <article> <h2>Another heading of another article</h2> <p>More content here.</p> </article> Each article has the contai...
...explain to the browser this fact, and allow it to make performance optimizations based on that knowledge. Key concepts and terminology This specification defines only one property, the contain property. The values for this property indicate the type of containment that you want to apply to that element. Layout containment article { contain: layout; } Layout is normally scoped to the entire document, which means that if you move one element the entire document needs to be treated as if things could have moved anywhere. By using contain: layout you can tell the browser it only needs to check this element -- everything inside the element is scoped to that element and does not affect the rest of the page, and the containing box establishes an independent formatting context. In addition: flo...
Basic concepts of flexbox - CSS: Cascading Style Sheets
ain axis is column or column-reverse then the cross axis runs along the rows. Understanding which axis is which is important when we start to look at aligning and justifying flex items; flexbox features properties that align and justify content along one axis or the other. Start and end lines Another vital area of understanding is how flexbox makes no assumption about the writing mode of the document. In the past, CSS was heavily weighted towards horizontal and left-to-right writing modes. Modern layout methods encompass the range of writing modes and so we no longer assume that a line of text will start at the top left of a document and run towards the right hand side, with new lines appearing one under the other. You can read more about the relationship between flexbox and the Writing Mode...
...ases the start edge of the cross axis is at the top of the flex container and the end edge at the bottom, as both languages have a horizontal writing mode. After a while, thinking about start and end rather than left and right becomes natural, and will be useful to you when dealing with other layout methods such as CSS Grid Layout which follow the same patterns. The flex container An area of a document laid out using flexbox is called a flex container. To create a flex container, we set the value of the area's container's display property to flex or inline-flex. As soon as we do this the direct children of that container become flex items. As with all properties in CSS, some initial values are defined, so when creating a flex container all of the contained flex items will behave in the followin...
Flow Layout and Writing Modes - CSS: Cascading Style Sheets
The CSS 2.1 specification, which details how normal flow behaves, assumes a horizontal writing mode. Layout properties should work in the same way in vertical writing modes. In this guide, we look at how flow layout behaves when used with different document writing modes. This is not a comprehensive guide to the use of writing modes in CSS, the aim here is to document the areas where flow layout interacts with writing modes in possibly unanticipated ways. The external resources and see also sections of this document link to more writing modes resources. The Writing Modes Specification The CSS Writing Modes Level 3 Specification defines the impact a change the document writing mode has on flow layout. In the writing modes introduction, the specification says, "A writing mode in CSS is ...
...ize will always mean the size in the inline direction. The CSS Logical Properties and Values specification includes logical versions of the properties that control margins, padding and borders as well as other mappings for things that we have typically used physical directions to specify. Summary In most cases, flow layout works as you would expect it to when changing the writing mode of the document or parts of the document. This can be used to properly typeset vertical languages or for creative reasons. CSS is making this easier by way of introducing logical properties and values so that when working in a vertical writing mode sizing can be based on element's inline and block size. This will be useful when creating components which can work in different writing-modes. See Also Writing M...
In Flow and Out of Flow - CSS: Cascading Style Sheets
re in-flow apart from: floated items items with position: absolute (including position: fixed which acts in the same way) the root element (html) Out of flow items create a new Block Formatting Context (BFC) and therefore everything inside them can be seen as a mini layout, separate from the rest of the page. The root element therefore is out of flow, as the container for everything in our document, and establishes the Block Formatting Context for the document. Floated Items In this example I have a div, and then two paragraphs. I've added a background colour to the paragraphs, and then floated the div left. The div is now out of flow. As a float it is first laid out according to where it would be in normal flow, then taken out of flow and moved to the left as far as possible. You can...
...t. You cannot apply anything to the following in-flow content to achieve that. Absolute Positioning Giving an item position: absolute or position: fixed removes it from flow, and any space that it would have taken up is removed. In the next example I have three paragraph elements, the second element has position absolute, with offset values of top: 30px and right: 30px. It has been removed from document flow. Using position: fixed also removes the item from flow, however the offsets are based on the viewport rather than the containing block. When taking an item out of flow with positioning, you will need to manage the possibility of content overlapping. Out of flow essentially means that the other elements on your page no longer know that element exists so will not respond to it. Relative P...
Introduction to formatting contexts - CSS: Cascading Style Sheets
tting context, or an area which has been defined to lay out content in a particular way. A block formatting context (BFC) will lay child elements out according to block layout rules, a flex formatting context will lay its children out as flex items, etc. Each formatting context has specific rules about how layout behaves when in that context. Block formatting contexts The outermost element in a document that uses block layout rules establishes the first, or initial block formatting context. This means that every element inside the <html> element's block is laid out according to normal flow following the rules for block and inline layout. Elements participating in a BFC use the rules outlined by the CSS Box Model, which defines how an element's margins, borders, and padding interact with other bl...
...A BFC contains everything inside it, float and clear only apply to items inside the same formatting context, and margins only collapse between elements in the same formatting context. BFC creation examples Let's have a look at a couple of these in order to see the effect creating a new BFC. In the example below, we have a floated element...
Basic Concepts of grid layout - CSS: Cascading Style Sheets
is makes me taller than 100 pixels.</p> </div> <div>Three</div> <div>Four</div> <div>Five</div> </div> Grid lines It should be noted that when we define a grid we define the grid tracks, not the lines. Grid then gives us numbered lines to use when positioning items. In our three column, two row grid we have four column lines. Lines are numbered according to the writing mode of the document. In a left-to-right language, line 1 is on the left-hand side of the grid. In a right-to-left language, it is on the right-hand side of the grid. Lines can also be named, and we will look at how to do this in a later guide in this series. Positioning items against lines We will be exploring line based placement in full detail in a later article. The following example demonstrates doing this in ...
.... In terms of line-based positioning, the gap acts like a fat line. Nesting grids A grid item can become a grid container. In the following example, I have the three-column grid that I created earlier, with our two positioned items. In this case the first item has some sub-items. As these items are not direct children of the grid they do not participate in grid layout and so display in a normal document flow. <div class="wrapper"> <div class="box box1"> <div class="nested">a</div> <div class="nested">b</div> <div class="nested">c</div> </div> <div class="box box2">Two</div> <div class="box box3">Three</div> <div class="box box4">Four</div> <div class="box box5">Five</div> </div> If I set box1 to display: grid I can give it a track definition and it too will become a...
Consistent list indentation - CSS: Cascading Style Sheets
>. This is why, in every browser except Internet Explorer for Windows, markers are placed outside any border set for an <li> element, assuming the value of list-style-position is outside. If it's changed to inside, then the markers are brought inside the <li>'s content, as though they're an inline box placed at the very beginning of the <li>. Indenting It Twice So how will all this appear in a document? At the moment, we have a situation analogous to these styles: ul, li {margin-left: 0; padding-left: 0;} If we dropped this list into a document as-is, there would be no apparent indentation and the markers would be in danger of falling off the left edge of the browser window. In order to avoid this and get some indentation, there are really only three options available to browser implementors...
...article is right or wrong about how they lay out lists. They use different default styles, and that's where the problems creep in. By making sure you style both the left padding and left margin of lists, you can find much greater cross-browser consistency in your list indentation. Recommendations When altering the indentation of lists, make sure to set both the padding and margin. Original Document Information Author(s): Eric A. Meyer, Netscape Communications Last Updated Date: Published 30 Aug 2002 Copyright Information: Copyright (C) 2001-2003 Netscape. All rights reserved. Note: This reprinted article was originally part of the DevEdge site. ...
Using media queries - CSS: Cascading Style Sheets
ve 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 computes to true when the media type (if specified) matches the device on which a document is being displayed and all media feature expressions compute as true. Queries involving unknown media types are always false. Note: A style sheet with a media query attached to its <link> tag will still download even if the query returns false. Nevertheless, its contents will not apply unless and until the result of the query changes to true. Media types Media types describe the general cate...
...download even if the query returns false. Nevertheless, its contents will not apply unless and until the result of the query changes to true. Media types Media types describe the general category of a device. Except when using the not or only logical operators, the media type is optional and the all type will be implied. all Suitable for all devices. print Intended for paged material and documents viewed on a screen in print preview mode. (Please see paged media for information about formatting issues that are specific to these formats.) screen Intended primarily for screens. speech Intended for speech synthesizers. Deprecated media types: CSS2.1 and Media Queries 3 defined several additional media types (tty, tv, projection, handheld, braille, embossed, and aural), but they were de...
Mozilla CSS extensions - CSS: Cascading Style Sheets
e Gecko 62 -moz-grid-groupObsolete since Gecko 62 -moz-grid-lineObsolete since Gecko 62 -moz-groupbox -moz-deckObsolete since Gecko 62 -moz-popupObsolete since Gecko 62 -moz-stackObsolete since Gecko 62 -moz-markerObsolete since Gecko 62 empty-cells -moz-show-background (default value in quirks mode) font -moz-button -moz-info -moz-desktop -moz-dialog (also a color) -moz-document -moz-workspace -moz-window -moz-list -moz-pull-down-menu -moz-field (also a color) font-family -moz-fixed image-rendering -moz-crisp-edges <length> -moz-calc list-style-type -moz-arabic-indic -moz-bengali -moz-cjk-earthly-branch -moz-cjk-heavenly-stem -moz-devanagari -moz-ethiopic-halehame -moz-ethiopic-halehame-am -moz-ethiopic-halehame-ti-er -moz-ethiopi...
...checkbox :-moz-tree-column :-moz-tree-drop-feedback :-moz-tree-image :-moz-tree-indentation :-moz-tree-line :-moz-tree-progressmeter :-moz-tree-row :-moz-tree-row(hover) :-moz-tree-separator :-moz-tree-twisty U - X :-moz-ui-invalid :-moz-ui-valid :-moz-user-disabled ::-moz-viewport ::-moz-viewport-scroll :-moz-window-inactive ::-moz-xul-anonymous-block At-rules @-moz-document Media features -moz-mac-graphite-theme -moz-maemo-classic -moz-device-pixel-ratio -moz-os-version -moz-scrollbar-end-backward -moz-scrollbar-end-forward -moz-scrollbar-start-backward -moz-scrollbar-start-forward -moz-scrollbar-thumb-proportional -moz-touch-enabled -moz-windows-accent-color-in-titlebar -moz-windows-classic -moz-windows-compositor -moz-windows-default-theme -mo...
background-clip - CSS: Cascading Style Sheets
-color, this property will only have a visual effect when the border has transparent regions or partially opaque regions (due to border-style or border-image); otherwise, the border masks the difference. Note: Because the root element has a different background painting area, the background-clip property has no effect when specified on it. See "The backgrounds of special elements." Note: For documents whose root element is an HTML element: if the computed value of background-image on the root element is none and its background-color is transparent, user agents must instead propagate the computed values of the background properties from that element's first HTML <body> child element. The used values of that <body> element's background properties are their initial values, and the propagated val...
... is none and its background-color is transparent, user agents must instead propagate the computed values of the background properties from that element's first HTML <body> child element. The used values of that <body> element's background properties are their initial values, and the propagated values are treated as if they were specified on the root element. It is recommended that authors of HTML documents specify the canvas background for the <body> element rather than the HTML element. Syntax /* Keyword values */ background-clip: border-box; background-clip: padding-box; background-clip: content-box; background-clip: text; /* Global values */ background-clip: inherit; background-clip: initial; background-clip: unset; Values border-box The background extends to the outside edge of the b...
<blend-mode> - CSS: Cascading Style Sheets
Candidate Recommendation Initial definitio...
... Candidate Recommendation Initial definition. ...
border-image-repeat - CSS: Cascading Style Sheets
Candidate Recommendation Initi...
... Candidate Recommendation Initial definition ...
border-width - CSS: Cascading Style Sheets
er medium A medium border thick A thick border Note: Because the specification doesn't define the exact thickness denoted by each keyword, the precise result when using one of them is implementation-specific. Nevertheless, they always follow the pattern thin <= medium <= thick, and the values are constant within a single document. Formal definition Initial valueas each of the properties of the shorthand:border-top-width: mediumborder-right-width: mediumborder-bottom-width: mediumborder-left-width: mediumApplies toall elements. It also applies to ::first-letter.InheritednoComputed valueas each of the properties of the shorthand:border-bottom-width: the absolute length or 0 if border-bottom-style is none or hiddenbor...
... CSS Backgrounds and Borders Module Level 3The definition of 'border-width' in that specification. Candidate Recommendation No direct change; the <length> CSS data type extension has an effect on this property. CSS Level 2 (Revision 1)The definition of 'border-width' in that specification. Recommendation Added the constraint that values' meaning must be constant inside a document. CSS Level 1The definition of 'border-width' in that specification. Recommendation Initial definition. ...
clip-path - CSS: Cascading Style Sheets
Web › CSS › clip-path
Candidate Recommendation Extends its application to HTML elements...
... Candidate Recommendation Extends its application to HTML elements. The clip-path property replaces the deprecated clip property. Scalable Vector Graphics ...
content - CSS: Cascading Style Sheets
Web › CSS › content
t is the value of all counters with the given name in scope at the given pseudo-element, from outermost to innermost, separated by the specified string. The counters are rendered in the indicated style (decimal by default). attr(x) The value of the element's attribute x as a string. If there is no attribute x, an empty string is returned. The case-sensitivity of attribute names depends on the document language. open-quote | close-quote These values are replaced by the appropriate string from the quotes property. no-open-quote | no-close-quote Introduces no content, but increments (decrements) the level of nesting for quotes. Accessibility concerns CSS-generated content is not included in the DOM. Because of this, it will not be represented in the accessibility tree and certain assistiv...
...ts (decrements) the level of nesting for quotes. Accessibility concerns CSS-generated content is not included in the DOM. Because of this, it will not be represented in the accessibility tree and certain assistive technology/browser combinations will not announce it. If the content conveys information that is critical to understanding the page's purpose, it is better to include it in the main document. Accessibility support for CSS generated content - Tink Explanation of WCAG, Guideline 1.3 - MDN Understanding Success Criterion 1.3.1 | W3C Understanding WCAG 2.0 Formal definition Initial valuenormalApplies to::before and ::after pseudo-elementsInheritednoComputed valueOn elements, always computes to normal. On ::before and ::after, if normal is specified, computes to none. Otherwise, f...
direction - CSS: Cascading Style Sheets
Web › CSS › direction
to left (like Hebrew or Arabic), and ltr for those written from left to right (like English and most other languages). 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 that text direction is usually defined within a document (e.g., with HTML's dir attribute) rather than through direct use of the direction property. The property sets the base text direction of block-level elements and the direction of embeddings created by the unicode-bidi property. It also sets the default alignment of text, block-level elements, and the direction that cells flow within a table row. Unlike the dir attribute in HTML, the direction p...
...e property sets the base text direction of block-level elements and the direction of embeddings created by the unicode-bidi property. It also sets the default alignment of text, block-level elements, and the direction that cells flow within a table row. Unlike the dir attribute in HTML, the direction property is not inherited from table columns into table cells, since CSS inheritance follows the document tree, and table cells are inside of rows but not inside of columns. The direction and unicode-bidi properties are the two only properties which are not affected by the all shorthand property. Syntax /* Keyword values */ direction: ltr; direction: rtl; /* Global values */ direction: inherit; direction: initial; direction: unset; Values ltr Text and other elements go from left to right. T...
element() - CSS: Cascading Style Sheets
Web › CSS › element
SS function defines an <image> value generated from an arbitrary HTML element. This image is live, meaning that if the HTML element is changed, the CSS properties using the resulting value are automatically updated. A particularly useful scenario for using this would be to render an image in an HTML <canvas> element, then use that as a background. On Gecko browsers, you can use the non-standard document.mozSetImageElement() method to change the element being used as the background for a given CSS background element. Syntax element(id) where: id The ID of an element to use as the background, specified using the HTML attribute #id on the element. Examples These examples can be viewed live in builds of Firefox that support -moz-element(). A somewhat realistic example This example uses a...
... No support No supportExperimental. Expect behavior to change in the future.Experimental. Expect behavior to change in the future.See implementation notes.See implementation notes.Requires a vendor prefix or different name for use.Requires a vendor prefix or different name for use. See also image() image-set() <image> <gradient> element() cross-fade() document.mozSetImageElement() ...
image-orientation - CSS: Cascading Style Sheets
Candidate Recommendation Initial definitio...
... Candidate Recommendation Initial definition. ...
image() - CSS: Cascading Style Sheets
s. Accessibility concerns Browsers do not provide any special information on background images to assistive technology. This is important primarily for screen readers, as a screen reader will not announce its presence and therefore convey nothing to its users. If the image contains information critical to understanding the page's overall purpose, it is better to describe it semantically in the document. MDN Understanding WCAG, Guideline 1.1 explanations Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 This feature can help improve accessibility by providing a fallback color when an image fails to load. While this can and should be done by including a background-color on every background image, the CSS image() function allows adding allows only including background colors...
...ist-style-image: image(ltr 'https://mdn.mozillademos.org/files/16412/rightarrow.png'); } In the left-to-right list items -- those with dir="ltr" set on the element itself or inheriting the directionality from an ancestor or default value for the page -- the image will be used as-is. List items with dir="rtl" set on the <li> or inheriting the right-to-left directionality from an ancestor, such as documents set to Arabic or Hebrew, will have the bullet display on the right, horizontally flippled, as if transform: scalex(-1) had been set. The text will also be displayed left-to-right. Displaying a section of the background image <div class="box">Hover over me. What cursor do you see?</div> .box:hover { cursor: image("https://mdn.mozillademos.org/files/16411/sprite.png#xywh=32,64,16,16"); } ...
justify-content - CSS: Cascading Style Sheets
Working Draft Adds the [ first | ...
... Working Draft Adds the [ first | last ]? baseline, self-start, self-end, start, end, left, right, unsafe | safe values. CSS Flex...
<length> - CSS: Cascading Style Sheets
Web › CSS › length
al to the computed value of the line-height property on the root element (typically <html>), converted to an absolute length. When used on the font-size or line-height properties of the root element, it refers to the properties' initial value. Viewport-percentage lengths Viewport-percentage lengths define the <length> value relative to the size of the viewport, i.e., the visible portion of the document. Viewport lengths are invalid in @page declaration blocks. vh Equal to 1% of the height of the viewport's initial containing block. vw Equal to 1% of the width of the viewport's initial containing block. vi Equal to 1% of the size of the initial containing block, in the direction of the root element's inline axis. vb Equal to 1% of the size of the initial containing block, in the di...
... 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: ${inputElem.value}</code>...
mask-clip - CSS: Cascading Style Sheets
Web › CSS › mask-clip
Candidate Recommendation Initial definition ...
... Candidate Recommendation Initial definition ...
mask-composite - CSS: Cascading Style Sheets
Candidate Recommendation Initial definition ...
... Candidate Recommendation Initial definition ...
mask-mode - CSS: Cascading Style Sheets
Web › CSS › mask-mode
Candidate Recommendation Initial definition ...
... Candidate Recommendation Initial definition ...
mask-origin - CSS: Cascading Style Sheets
Candidate Recommendation Initial definition ...
... Candidate Recommendation Initial definition ...
mask-position - CSS: Cascading Style Sheets
Candidate Recommendation Initial definition ...
... Candidate Recommendation Initial definition ...
mask-size - CSS: Cascading Style Sheets
Web › CSS › mask-size
Candidate Recommendation Initial definition ...
... Candidate Recommendation Initial definition ...
overflow-anchor - CSS: Cascading Style Sheets
The overflow-anchor CSS property provides a way to opt out of the browser's scroll anchoring behavior, which adjusts scroll position to minimize content shifts. Scroll anchoring behavior is enabled by default in any browser that supports it. Therefore, changing the value of this property is typically only required if you are experiencing problems with scroll anchoring in a document or part of a document and need to turn the behavior off. Syntax /* Keyword values */ overflow-anchor: auto; overflow-anchor: none; /* Global values */ overflow-anchor: inherit; overflow-anchor: initial; overflow-anchor: unset; Values auto The element becomes a potential anchor when adjusting scroll position. none The element won't be selected as a potential anchor. Formal definition Initial valueautoAppl...
...initial; overflow-anchor: unset; Values auto The element becomes a potential anchor when adjusting scroll position. none The element won't be selected as a potential anchor. Formal definition Initial valueautoApplies toall elementsInheritednoComputed valueas specifiedAnimation typediscrete Formal syntax auto | none Examples Prevent scroll anchoring To prevent scroll anchoring in a document, use the overflow-anchor property. body { overflow-anchor: none; } Specifications Specification Status Comment CSS Scroll Anchoring Module Level 1The definition of 'overflow-anchor' in that specification. Editor's Draft Initial definition. ...
place-content - CSS: Cascading Style Sheets
ected>center</option> <option value="start">start</option> <option value="end">end</option> <option value="flex-start">flex-start</option> <option value="flex-end">flex-end</option> <option value="left">left</option> <option value="right">right</option> <option value="safe">safe</option> <option value="unsafe">unsafe</option> </select><code>;</code> var update = function () { document.getElementById("container").style.placeContent = document.getElementById("alignContentAlignment").value + " " + document.getElementById("justifyContentAlignment").value; } var alignContentAlignment = document.getElementById("alignContentAlignment"); alignContentAlignment.addEventListener("change", update); var justifyContentAlignment = document.getElementById("justifyContentAlignment"); justif...
...yId("alignContentAlignment").value + " " + document.getElementById("justifyContentAlignment").value; } var alignContentAlignment = document.getElementById("alignContentAlignment"); alignContentAlignment.addEventListener("change", update); var justifyContentAlignment = document.getElementById("justifyContentAlignment"); justifyContentAlignment.addEventListener("change", update); var writingM = document.getElementById("writingMode"); writingM.addEventListener("change", function (evt) { document.getElementById("container").style.writingMode = evt.target.value; }); var direction = document.getElementById("direction"); direction.addEventListener("change", function (evt) { document.getElementById("container").style.direction = evt.target.value; }); CSS #container { display: flex; heigh...
transition-timing-function - CSS: Cascading Style Sheets
margin-bottom: 4px; background-color: black; border: 1px solid red; color: white; transition-property: all; transition-duration: 7s; } .parent > div.box1{ width: 90vw; min-width: 24em; background-color: magenta; color: yellow; border: 1px solid orange; transition-property: all; transition-duration: 2s; } function updateTransition() { var els = document.querySelectorAll(".parent > div[class]"); for(var c = els.length, i = 0; i < c; i++) { els[i].classList.toggle("box1"); } } var intervalID = window.setInterval(updateTransition, 10000); .ease { transition-timing-function: ease; } .easein { transition-timing-function: ease-in; } .easeout { transition-timing-function: ease-out; } .easeinout { transition-timing-function: eas...
... margin-bottom: 4px; background-color: black; border: 1px solid red; color: white; transition-property: all; transition-duration:7s; } .parent > div.box1{ width: 90vw; min-width: 24em; background-color: magenta; color: yellow; border: 1px solid orange; transition-property: all; transition-duration:2s; } function updateTransition() { var els = document.querySelectorAll(".parent > div[class]"); for(var c = els.length, i = 0; i < c; i++) { els[i].classList.toggle("box1"); } } var intervalID = window.setInterval(updateTransition, 10000); .jump-start { transition-timing-function: steps(5, jump-start); } .jump-end { transition-timing-function: steps(5, jump-end); } .jump-none { transition-timing-function: steps(5, jump-none); }...
unicode-bidi - CSS: Cascading Style Sheets
For example, if a block of content contains both left-to-right and right-to-left text, the user-agent uses a complex Unicode algorithm to decide how to display the text. The unicode-bidi property overrides this algorithm and allows the developer to control the text embedding. The unicode-bidi and direction properties are the only properties that are not affected by the all shorthand. Note: This property is intended for Document Type Definition (DTD) designers. Web designers and similar authors should not override it. ...
...f content contains both left-to-right and right-to-left text, the user-agent uses a complex Unicode algorithm to decide how to display the text. The unicode-bidi property overrides this algorithm and allows the developer to control the text embedding. The unicode-bidi and direction properties are the only properties that are not affected by the all shorthand. Note: This property is intended for Document Type Definition (DTD) designers. Web designers and similar authors should not override it. /* Keyword values */ unicode-bidi: normal; unicode-bidi: embed; unicode-bidi: isolate; unicode-bidi: bidi-override; unicode-bidi: isolate-override; unicode-bidi: plaintext; /* Global values */ unicode-bidi: inherit; unicode-bidi: initial; unicode-bidi: unset; Syntax Values normal The element does not...
white-space - CSS: Cascading Style Sheets
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...
...Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure ...
WAI ARIA Live Regions/API Support - Developer guides
These notes are for developers of screen readers. Developers should use the ARIA live regions developer documentation. Firefox 3 contains important improvements to the way the Mozilla engine exposes live changes in a document. These features will help screen reader developers improve the quality and performance of live region support, both for pages that are marked up with ARIA live region markup, and for pages where the author did not add any additional markup. Please read the ARIA spec or the live region report to learn about ARIA live region markup. As always, we're open to questions and suggestions for changes in community forums. ...
...ormance of live region support, both for pages that are marked up with ARIA live region markup, and for pages where the author did not add any additional markup. Please read the ARIA spec or the live region report to learn about ARIA live region markup. As always, we're open to questions and suggestions for changes in community forums. ...
Media events - Developer guides
Event name Description abort Sent when playback is aborted; for example, if the media is playing and is restarted from the beginning, this event is sent. canplay Sent when enough data is available that the media can be played, at least for a couple of frames. This corresponds to the HAVE_FUTURE_DATA readyState. ...
...urrentTime attribute has changed. volumechange Sent when the audio volume changes (both when the volume is set and when the muted attribute is changed). waiting Sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek). You can easily watch for these events, using code such as the following: var v = document.getElementsByTagName("video")[0]; v.addEventListener("seeked", function() { v.play(); }, true); v.currentTime = 10.0; This example fetches the first video element in the document and attaches an event listener to it, watching for the seeked event, which is sent whenever a seek operation completes. The listener simply calls the element's play() method, which starts playback. Then, in line 3, t...
Using device orientation with 3D transforms - Developer guides
lue should be alpha - 180 The Y axis of the screen coordinate system is inverted, such that translateY(100px) moves an element 100px down, so the rotateY value should be -gamma Finally, the order of the three different rotations is very important to accurately convert an orientation to a 3D rotation: rotateZ, then rotateX and then rotateY. ...
... property elem.style.transform = "rotateZ(" + ( e.alpha - 180 ) + "deg) " + "rotateX(" + e.beta + "deg) " + "rotateY(" + ( -e.gamma ) + "deg)"; }); Orientation compensation Compensating the orientation of the device can be useful to create parallax effects or augmented reality. ...
Event developer guide - Developer guides
Web › Guide › Events
t, mouse events, mouse gesture events, and both touch events and the earlier mozilla experimental touch events, now deprecated. The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach. The media streams embedded in the HTML documents might trigger some events, as explained in the media events page. The network requests made by a web page might trigger some events. There are many other sources of events defined by web browsers for which pages are not yet available in this guide. Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everythi...
...and dispatch DOM events. Such events are commonly called synthetic events, as opposed to the events fired by the browser itself.DOM on-event handlersThe Web platform provides several ways to get notified of DOM events. Two common styles are: the generalized addEventListener() and a set of specific on-event handlers.Media eventsVarious events are sent when handling media that are embedded in HTML documents using the <audio> and <video> elements; this section lists them and provides some helpful information about using them.Mouse gesture eventsGecko 1.9.1 added support for several Mozilla-specific DOM events used to handle mouse gestures. These are special movements that can be made with a mouse or trackpad and can be interpreted to perform specific tasks.Mutation eventsMutation events provide a me...
Introduction to HTML5 - Developer guides
ension, Firefox, has very good support for HTML5, and work continues toward supporting more of its features. Gecko began supporting some HTML5 features in version 1.8.1. You can find a list of all of the HTML5 features that Gecko currently supports on the main HTML5 page. For detailed information about multiple browsers' support of HTML5 features, refer to the CanIUse website. Declaring that the document contains HTML5 mark-up with the HTML5 doctype The doctype for HTML5 is very simple. To indicate that your HTML content uses HTML5, simply use: <!DOCTYPE html> Doing so will cause even browsers that don't presently support HTML5 to enter into standards mode, which means that they'll interpret the long-established parts of HTML in an HTML5-compliant way while ignoring the new features of HTML5 ...
...ing the amount of bytes that must be downloaded. Declaring the character set with the <meta charset> The first thing done on a page is usually indicating the character set that is used. In previous versions of HTML, it was done using a very complex <meta> element. Now, it is very simple: <meta charset="UTF-8"> Place this right after your <head>, as some browsers restart the parsing of an HTML document if the declared character set is different from what they had anticipated. Also, if you are not currently using UTF-8, it's recommended that you switch to it in your web pages, as it simplifies character handling in documents using different scripts. Note that HTML5 restricts character sets to those compatible with ASCII and using at least 8 bits. This was done to tighten security and prevent so...
Introduction to Web development - Developer guides
Whether you're just getting started with Web development, or are just expanding your horizons into new realms of Web awesomeness, the links here should help you get started. For another (overlapping) set of links to learning resources, see the MDN Learning pages. Note: The recommended resources on this page are subject to change. Documentation topics HTML The basics of Hypertext Mark-up Langage (HTML) -- what exactly is HTML? Basic structure of a web page -- the doctype and document 'tree' Fundamental HTML elements -- structural, head, list, form elements and more, explained by category. HTML beginners tutorial -- a tutorial and exercise that recap and take you through the basics you've learned above. HTML elements reference guide -- a c...
...vaScript object model. Christian Heilmann's JavaScript best practices -- learn about some of the obvious and (not so) obvious best practices when writing JavaScript. Advanced Learning advanced JavaScript -- John Resig's guide to advanced JavaScript Crockford on Advanced JavaScript -- a three part video series on advanced JavaScript concepts JavaScript Garden -- Documentation of the most quirky parts of JavaScript. Resources W3C Web Education Community Group Wiki Covers web design, HTML and HTML5, CSS, JavaScript and accessibility. This is a good starting point for beginners wishing to learn web development fundamentals across a number of areas. SitePoint A reliable reference site for learning HTML, CSS and JavaScript wh...
Writing forward-compatible websites - Developer guides
lowing 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 markup: <div onclick="alert(ownerDocument)">Click me</div> then clicking on the text alerts the ownerDocument of the div. This happens even if there is a var ownerDocument declared in global scope. What this means is that any time you access a global variable in an event handler content att...
...ick me</div> then clicking on the text alerts the ownerDocument of the div. This happens even if there is a var ownerDocument declared in global scope. What this means is that any time you access a global variable in an event handler content attribute, including calling any function declared globally, you can end up with a name collision if a specification adds a new DOM property to elements or documents which has the same name as your function or variable, and a browser implements it. If that happens, then suddenly your function stops being called. This has happened multiple times to various sites already during the evolution of HTML5. To avoid this, fully qualify global variable access using "window.", like so: <script> function localName() { alert('Function localName has been called')...
Block-level elements - HTML: Hypertext Markup Language
ts The following is a complete list of all HTML "block-level" elements (although "block-level" is not technically defined for elements that are new in HTML5). <address> Contact information. <article> Article content. <aside> Aside content. <blockquote> Long ("block") quotation. <details> Disclosure widget. <dialog> Dialog box. <dd> Describes a term in a description list. <div> Document division. <dl> Description list. <dt> Description list term. <fieldset> Field set label. <figcaption> Figure caption. <figure> Groups media content with a caption (see <figcaption>). <footer> Section or page footer. <form> Input form. <h1>, <h2>, <h3>, <h4>, <h5>, <h6> Heading levels 1-6. <header> Section or page header. <hgroup> Groups header information. <hr> Horizontal ru...
...bel. <figcaption> Figure caption. <figure> Groups media content with a caption (see <figcaption>). <footer> Section or page footer. <form> Input form. <h1>, <h2>, <h3>, <h4>, <h5>, <h6> Heading levels 1-6. <header> Section or page header. <hgroup> Groups header information. <hr> Horizontal rule (dividing line). <li> List item. <main> Contains the central content unique to this document. <nav> Contains navigation links. <ol> Ordered list. <p> Paragraph. <pre> Preformatted text. <section> Section of a web page. <table> Table. <ul> Unordered list. See also Inline elements display Block and Inline Layout in Normal Flow ...
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
listener is added for the load event being fired on the image element, which means the image data has been received. Finally, the image's src attribute is set to the URL of the image to download; this triggers the download to begin. ...
...he downloaded data is all available. It begins by creating a new <canvas> element that we'll use to convert the image into a data URL, and by getting access to the canvas's 2D drawing context (CanvasRenderingContext2D) in the variable context. The canvas's size is adjusted to match the received image, then the image is drawn into the canvas using drawImage(). The canvas is then inserted into the document so the image is visible. Now it's time to actually save the image locally. To do this, we use the Web Storage API's local storage mechanism, which is accessed through the localStorage global. The canvas method toDataURL() is used to convert the image into a data:// URL representing a PNG image, which is then saved into local storage using setItem(). You can try out or remix this example on Glit...
<a>: The Anchor element - HTML: Hypertext Markup Language
Web › HTML › Element › a
th save link HTML <p>Paint by holding down the mouse button and moving it. ...
...See Referer header: privacy and security concerns for information. Using target="_blank" without rel="noreferrer" and rel="noopener" makes the website vulnerable to window.opener API exploitation at...
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
Web › HTML › Element › abbr
rs; providing a title for one does not automatically attach the same expansion text to others with the same content text. Usage notes Typical use cases It's certainly not required that all abbreviations be marked up using <abbr>. There are, though, a few cases where it's helpful to do so: When an abbreviation is used and you want to provide an expansion or definition outside the flow of the document's content, use <abbr> with an appropriate title. To define an abbreviation which may be unfamiliar to the reader, present the term using <abbr> and either a title attribute or inline text providing the definition. When an abbreviation's presence in the text needs to be semantically noted, the <abbr> element is useful. This can be used, in turn, for styling or scripting purposes. You can use <a...
...g time.</p> Result Defining an abbreviation You can use <abbr> in tandem with <dfn> to more formally define an abbreviation, as shown here. HTML <p><dfn id="html"><abbr title="HyperText Markup Language">HTML</abbr> </dfn> is a markup language used to create the semantics and structure of a web page.</p> <p>A <dfn id="spec">Specification</dfn> (<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 lightwe...
<applet>: The Embed Java Applet element - HTML: Hypertext Markup Language
Web › HTML › Element › applet
Use of Java applets on the Web is deprecated; most browsers no longer support use of plug-ins, including the Java plug-in. Content categories Flow content, phrasing content, embedded content, interactive content, palpable content. Permitted content Zero or more <param> elements, then transparent. ...
...t is bound to the <param> elements associated with the applet. height This attribute specifies the height, in pixels, that the applet needs. hspace This attribute specifies additional horizontal space, in pixels, to be reserved on either side of the applet. mayscript In the Netscape implementation, this attribute allows access to an applet by programs in a scripting language embedded in the document. name This attribute assigns a name to the applet so that it can be identified by other resources; particularly scripts. object This attribute specifies the URL of a serialized representation of an applet. src As defined for Internet Explorer 4 and higher, this attribute specifies a URL for an associated file for the applet. The meaning and use is unclear and not part of the HTML standard. ...
<article>: The Article Contents element - HTML: Hypertext Markup Language
Web › HTML › Element › article
The HTML <article> element represents a self-contained composition in a document, page, application, or site, which is intended to be independently distributable or reusable (e.g., in syndication). Examples include: a forum post, a magazine or newspaper article, or a blog entry. 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. A given document can have multiple articles in it; for example, on a blog that shows the text of each article one after another as the reader scrolls, each post would be contained in an <article> element, possibly with one or more <section>s within. Content categories Flow content, se...
...ent, sectioning content, palpable content Permitted content Flow content. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts flow content. Note that an <article> element must not be a descendant of an <address> element. Implicit ARIA role article Permitted ARIA roles application, document, feed, main, none, presentation, region DOM interface HTMLElement Attributes This element only includes the global attributes. Usage notes Each <article> should be identified, typically by including a heading (<h1>-<h6> element) as a child of the <article> element. When an <article> element is nested, the inner element represents an article related to the outer element. F...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
Web › HTML › Element › audio
It may contain one or more audio sources, represented using the src attribute or the <source> element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a MediaStream. 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. The above example shows simple usage of the <audio> element. ...
...er to this TextTrackList to be notified when new text tracks are added to the element. Note: Even though it's an <audio> element, it still has video and text track lists, and can in fact be used to present video, although the use interface implications can be odd. ...
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
Web › HTML › Element › canvas
ls 32,767 pixels 472,907,776 pixels (i.e., 22,528 x 20,992) Safari 32,767 pixels 32,767 pixels 268,435,456 pixels (i.e., 16,384 x 16,384) IE 8,192 pixels 8,192 pixels ? 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. ...
...Canvas content is not exposed to accessibility tools as semantic HTML is. ...
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › content
d inside of Shadow DOM as an insertion point, and wasn't meant to be used in ordinary HTML. It has now been replaced by the <slot> element, which creates a point in the DOM at which a shadow DOM can be inserted. Note: Though present in early draft of the specifications and implemented in several browsers, this element has been removed in later versions of the spec, and should not be used. It is documented here to assist in adapting code written during the time it was included in the spec to work with newer versions of the specification. Content categories Transparent content. Permitted content Flow content. Tag omission None, both the starting and ending tag are mandatory. Permitted parent elements Any element that accepts flow content. ...
... It is an HTML file with everything needed in it. Note: For this code to work, the browser you display it in must support Web Components. See Enabling Web Components in Firefox. <html> <head></head> <body> <!-- The original content accessed by <content> --> <div> <h4>My Content Heading</h4> <p>My content text</p> </div> <script> // Get the <div> above. var myContent = document.querySelector('div'); // Create a shadow DOM on the <div> var shadowroot = myContent.createShadowRoot(); // Insert into the shadow DOM a new heading and // part of the original content: the <p> tag. shadowroot.innerHTML = '<h2>Inserted Heading</h2> <content select="p"></content>'; </script> </body> </html> If you display this in a web browser it should look like the following.
<form> - HTML: Hypertext Markup Language
Web › HTML › Element › form
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. It is possible to use the :valid and :invalid CSS pseudo-classes to style a <form> element based on whether or not the elements inside the form are valid. Content categories Flow content, palpable content Permitted content Flow content, but not containing <form> elements Tag omission None, both the starting and ending tag are mandatory. ...
...butes on form elements override it on <form>. Possible values: off: The browser may not automatically complete entries. (Browsers tend to ignore this for suspected login forms; see The autocomplete attribute and login fields.) on: The browser may automatically complete entries. name The name of the form. Deprecated as of HTML 4 (use id instead). It must be unique among the forms in a document and not an empty string as of HTML5. rel Creates a hyperlink or annotation depending on the value, see the rel attribute for details. Attributes for form submission The following attributes control behavior during form submission. action The URL that processes the form submission. This value can be overridden by a formaction attribute on a <button>, <input type="submit">, or <input type=...
<frame> - HTML: Hypertext Markup Language
Web › HTML › Element › frame
name This attribute is used for labeling frames. Without labeling, every link will open in the frame that it's in - the closest parent frame. ...
...played. A frame should be used within a <frameset>. Using the <frame> element is not encouraged because of certain disadvantages such as performance problems and lack of accessibility for users with screen readers. Instead of the <frame> element, <iframe> may be preferred. Attributes Like all other HTML elements, this element supports the global attributes. src This attribute specifies the document that will be displayed by the frame. name This attribute is used for labeling frames. Without labeling, every link will open in the frame that it's in - the closest parent frame. See the target attribute for more information. noresize This attribute prevents resizing of frames by users. scrolling This attribute defines the existence of a scrollbar. If this attribute is not used, the browser...
<input type="email"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › email
valid placeholder An exemplar value to display in the input field whenever it is empty readonly A Boolean attribute indicating whether or not the contents of the input should be read-only size A number indicating how many characters wide the input field should be list The values of the list attribute is the id of a <datalist> element located in the same document. The <datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. maxlength The maximum number of characters (as UTF-16 code units) the use...
... 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 expression is applied and this attribute is ignored completely. Tip: U...
<input type="search"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › search
her or not the contents of the input should be read-only size A number indicating how many characters wide the input field should be spellcheck Controls whether or not to enable spell checking for the input field, or if the default spell checking configuration should be used list The values of the list attribute is the id of a <datalist> element located in the same document. The <datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. maxlength The maximum number of characters (as UTF-16 code units) the use...
...ength. 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 expression is applied and this attribute is ignored completely. Tip: U...
<input type="text"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › text
her or not the contents of the input should be read-only size A number indicating how many characters wide the input field should be spellcheck Controls whether or not to enable spell checking for the input field, or if the default spell checking configuration should be used list The values of the list attribute is the id of a <datalist> element located in the same document. The <datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. maxlength The maximum number of characters (as UTF-16 code units) the use...
...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 expression is applied and this attribute is ignored completely. Tip: U...
<input type="url"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › url
her or not the contents of the input should be read-only size A number indicating how many characters wide the input field should be spellcheck Controls whether or not to enable spell checking for the input field, or if the default spell checking configuration should be used list The values of the list attribute is the id of a <datalist> element located in the same document. The <datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. maxlength The maximum number of characters (as UTF-16 code units) the use...
... 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 expression is applied and this attribute is ignored completely. Tip: U...
<keygen> - HTML: Hypertext Markup Language
Web › HTML › Element › keygen
ent that accepts phrasing content. Permitted ARIA roles None DOM interface HTMLKeygenElement Attributes This element includes the global attributes. autofocus This Boolean attribute lets you specify that the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form element in a document can have the autofocus attribute, which is a Boolean. challenge A challenge string that is submitted along with the public key. Defaults to an empty string if not specified. disabled This Boolean attribute indicates that the form control is not available for interaction. form The form element that this element is associated with (its form owner). The value of the attribute must be an id of ...
...bute, which is a Boolean. challenge A challenge string that is submitted along with the public key. Defaults to an empty string if not specified. disabled This Boolean attribute indicates that the form control is not available for interaction. form The form element that this element is associated with (its form owner). The value of the attribute must be an id of a <form> element in the same document. If this attribute is not specified, this element must be a descendant of a <form> element. This attribute enables you to place <keygen> elements anywhere within a document, not just as descendants of their form elements. keytype The type of key generated. The default value is RSA. name The name of the control, which is submitted with the form data. The element is written as follows: <keyg...
<nav>: The Navigation Section element - HTML: Hypertext Markup Language
Web › HTML › Element › nav
Common examples of navigation sections are menus, tables of contents, and indexes. 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. Content categories Flow content, sectioning content, palpable content. Permitted content Flow content. Tag omission None, both the starting and ending tag are mandatory. ...
... Permitted ARIA roles No role permitted DOM interface HTMLElement Attributes This element only includes the global attributes. Usage notes It's not necessary for all links to be contained in a <nav> element. <nav> is intended only for major block of navigation links; typically the <footer> element often has a list of links that don't need to be in a <nav> element. A document may have several <nav> elements, for example, one for site navigation and one for intra-page navigation. aria-labelledby can be used in such case to promote accessibility, see example. User agents, such as screen readers targeting disabled users, can use this element to determine whether to omit the initial rendering of navigation-only content. Examples In this example, a <nav> block is used ...
<p>: The Paragraph element - HTML: Hypertext Markup Language
Web › HTML › Element › p
cial character: ?, the <i>pilcrow</i>. ...
...Scree...
<select>: The HTML Select element - HTML: Hypertext Markup Language
Web › HTML › Element › select
ent. Attributes This element includes the global attributes. autocomplete A DOMString providing a hint for a user agent's autocomplete feature. See The HTML autocomplete attribute for a complete list of values and details on how to use autocomplete. autofocus This Boolean attribute lets you specify that a form control should have input focus when the page loads. Only one form element in a document can have the autofocus attribute. disabled This Boolean attribute indicates that the user cannot interact with the control. If this attribute is not specified, the control inherits its setting from the containing element, for example <fieldset>; if there is no containing element with the disabled attribute set, then the control is enabled. form The <form> element to associate the <select> wit...
... user cannot interact with the control. If this attribute is not specified, the control inherits its setting from the containing element, for example <fieldset>; if there is no containing element with the disabled attribute set, then the control is enabled. form The <form> element to associate the <select> with (its form owner). The value of this attribute must be the id of a <form> in the same document. (If this attribute is not set, the <select> is associated with its ancestor <form> element, if any.) This attribute lets you associate <select> elements to <form>s anywhere in the document, not just inside a <form>. It can also override an ancestor <form> element. multiple This Boolean attribute indicates that multiple options can be selected in the list. If it is not specified, then only one...
tabindex - HTML: Hypertext Markup Language
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 focusable in sequential keyboard navigation, after any positive tabindex values and its order is defined by the document's source order. A positive value means the element should be focusable in sequential keyboard navigation, with its order defined by the value of the number. That is, tabindex="4" is focused before tabindex="5" and tabindex="0", but after tabindex="3". If multiple elements share the same positive tabindex value, their order relative to each other follows their position in the document source. The...
... If you set the tabindex attribute on a <div>, then its child content cannot be scrolled with the arrow keys unless you set tabindex on the content, too. Check out this fiddle to understand the scrolling effects of tabindex. ...
Browser detection using the user agent - HTTP
ey're using. There are ways to develop your website to progressively enhance itself based on the availability of features rather than by targeting specific browsers. But browsers and standards are not perfect, and there are still some edge cases where detecting the browser is needed. Using the user agent to detect the browser looks simple, but doing it well is, in fact, a very hard problem. This document will guide you in doing this as correctly as possible. It's worth re-iterating: it's very rarely a good idea to use user agent sniffing. You can almost always find a better, more broadly compatible way to solve your problem! Considerations before using browser detection When considering using the user agent string to detect which browser is being used, your first step is to try to avoid it i...
...What you want to do for screen size is not slash off information on smaller screens. That will only annoy people because it will force them to use the desktop version. Rather, try to have fewer c...
Content negotiation - HTTP
In HTTP, content negotiation is the mechanism that is used for serving different representations of a resource at the same URI, so that the user agent can specify which is best suited for the user (for example, which language of a document, which image format, or which content encoding). Note: Some disadvantages of HTTP content negotiation are explained in a wiki page from WHATWG. HTML5 provides alternatives to content negotiation via, for example, the <source> element. Principles of content negotiation A specific document is called a resource. When a client wants to obtain a resource, the client requests it using its URL. The server uses this URL to choose one of the variants it provides - each variant being called a representation - and returns a specific representation to the client. The ...
...t is willing to process. It is comma-separated lists of MIME types, each combined with a quality factor, a parameter indicating the relative degree of preference between the different MIME types. The Accept header is defined by the browser, or any other user-agent, and can vary according to the context, like fetching an HTML page or an image, a video, or a script: It is different when fetching a document entered in the address bar or an element linked via an <img>, <video> or <audio> element. Browsers are free to use the value of the header that they think is the most adequate; an exhaustive list of default values for common browsers is available. The Accept-CH header This is part of an experimental technology called Client Hints. Initial support is in Chrome 46 or later. The Device-Memory v...
Using HTTP cookies - HTTP
Web › HTTP › Cookies
, 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 and Path ...
... 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 JavaScript cannot include t...
CSP: plugin-types - HTTP
Instantiation of an <embed>, <object> or <applet> element will fail if: the element to load does not declare a valid MIME type, the declared type does not match one of specified types in the plugin-types directive, the fetched resource does not match the declared type. CSP version 2 Directive type Document directive default-src fallback No. Not setting this allows anything. ...
...o a document by limiting the types of resources which can be loaded. Instantiation of an <embed>, <object> or <applet> element will fail if: the element to load does not declare a valid MIME type, the declared type does not match one of specified types in the plugin-types directive, the fetched resource does not match the declared type. CSP version 2 Directive type Document directive default-src fallback No. Not setting this allows anything. Syntax One or more MIME types can be set for the plugin-types policy: Content-Security-Policy: plugin-types <type>/<subtype>; Content-Security-Policy: plugin-types <type>/<subtype> <type>/<subtype>; <type>/<subtype> A valid MIME type. Examples Disallowing plugins To disallow all plugins, the object-...
CSP: sandbox - HTTP
The HTTP Content-Security-Policy (CSP) sandbox directive enables a sandbox 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. CSP version 1.1 / 2 Directive type Document directive This directive is not supported in the <meta> element or by the Content-Security-policy-Report-Only header field. Syntax Content-Security-Policy: sandbox; Content-Security-Policy: sandbox <value>; where <value> can optionally be one of the following values: allow-downloads-without-user-activation Allows for downloads to occur without a gesture from the user. allow-forms Allows the page to sub...
...e page to open modal windows. allow-orientation-lock Allows the page to disable the ability to lock the screen orientation. allow-pointer-lock Allows the page to use the Pointer Lock API. allow-popups Allows popups (like from window.open, target="_blank", showModalDialog). If this keyword is not used, that functionality will silently fail. allow-popups-to-escape-sandbox Allows a sandboxed document to open new windows without forcing the sandboxing flags upon them. This will allow, for example, a third-party advertisement to be safely sandboxed without forcing the same restrictions upon a landing page. allow-presentation Allows embedders to have control over whether an iframe can start a presentation session. allow-same-origin Allows the content to be treated as being from its normal or...
CSP: script-src - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
... report. Examples Violation case Given this CSP header: Content-Security-Policy: script-src https://example.com/ the following script is blocked and won't be loaded or executed: <script src="https://not-example.com/js/library.js"></script> Note that inline event handlers are blocked as well: <button id="btn" onclick="doSomething()"> You should replace them with addEventListener calls: document.getElementById("btn").addEventListener('click', doSomething); Unsafe inline script 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 scripts and inline event handlers, 'unsafe-inline', a nonce-source or a hash-source that matches the i...
CSP: style-src - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
...> <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.display = 'none'; These types of manipulations can be prevented by disallow...
Cross-Origin-Embedder-Policy - HTTP
The HTTP Cross-Origin-Embedder-Policy (COEP) response header prevents a document from loading any cross-origin resources that don't explicitly grant the document permission (using CORP or CORS). Header type Response header Forbidden header name no Syntax Cross-Origin-Embedder-Policy: unsafe-none | require-corp Directives unsafe-none This is the default value. Allows the document to fetch cross-origin resources without giving explicit permission through the CORS protocol or the Cross-Origin-Resource-Policy header. require-corp A document can only load resources from the same origin, or resources explicitly marked as loadable from another origin. If a cross origin resource supports CORS, the crossorigin attribute or the Cross-Origin-Resource-Policy header m...
...licitly marked as loadable from another origin. If a cross origin resource supports CORS, the crossorigin attribute or the Cross-Origin-Resource-Policy header must be used to load it without being blocked by COEP. Examples Certain features depend on cross-origin isolation You can only access certain features like SharedArrayBuffer objects or Performance.now() with unthrottled timers, if your document has a COEP header with the value require-corp value set. Cross-Origin-Embedder-Policy: require-corp Cross-Origin-Opener-Policy: same-origin See also the Cross-Origin-Opener-Policy header which you'll need to set as well. To check if cross origin isolation has been successful, you can test against the crossOriginIsolated property available to window and worker contexts: if (crossOriginIsolate...
Feature-Policy: encrypted-media - HTTP
The HTTP Feature-Policy header encrypted-media directive controls whether the current document is allowed to use the Encrypted Media Extensions API (EME). When this policy is enabled, the Promise returned by Navigator.requestMediaKeySystemAccess() will reject with a DOMException. Syntax Feature-Policy: encrypted-media <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the doc...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The allow list is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. Encrypted Media ExtensionsThe definition of 'Feature Policy integration' in that specification. Recommenda...
Feature-Policy: gyroscope - HTTP
The HTTP Feature-Policy header gyroscope directive controls whether the current document is allowed to gather information about the orientation of the device through the Gyroscope interface. Syntax Feature-Policy: gyroscope <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none'...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. The default value is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Feature-Policy: layout-animations - HTTP
The HTTP Feature-Policy header layout-animations directive controls whether the current document is allowed to show layout animations. Syntax Feature-Policy: layout-animations <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': The feature is disabled in top-level and neste...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. The default value is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Feature-Policy: legacy-image-formats - HTTP
The HTTP Feature-Policy header legacy-image-formats directive controls whether the current document is allowed to display images in legacy formats. Syntax Feature-Policy: legacy-image-formats <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': The feature is disabled in top...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. The default value is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Feature-Policy: oversized-images - HTTP
The HTTP Feature-Policy header oversized-images directive controls whether the current document is allowed to download and display large images. Syntax Feature-Policy: oversized-images <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': The feature is disabled in top-level ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default value The default value is '*'. Specification Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Feature-Policy: picture-in-picture - HTTP
The HTTP Feature-Policy header picture-in-picture directive controls whether the current document is allowed to play a video in a Picture-in-Picture mode via the corresponding API. Syntax Feature-Policy: picture-in-picture <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none':...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy As of June 2019, the spec draft and Google Chrome set default allow list to *. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Feature-Policy: sync-xhr - HTTP
The HTTP Feature-Policy header sync-xhr directive controls whether the current document is allowed to make synchronous XMLHttpRequest requests. Syntax Feature-Policy: sync-xhr <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': The feature is disabled in top-level and neste...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy By default the policy is set to *, which means synchronous requests are allowed in all frames. Specification Specification Status Comment Feature Policy Editor's Draft Initial definition. WHATWG Spec Default policy is *. ...
Feature-Policy: unoptimized-images - HTTP
The HTTP Feature-Policy header unoptimized-images directive controls whether the current document is allowed to download and display unoptimized images. Syntax Feature-Policy: unoptimized-images <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': The feature is disabled in ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. The default value is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Feature-Policy: usb - HTTP
The HTTP Feature-Policy header usb directive controls whether the current document is allowed to use the WebUSB API. Syntax Feature-Policy: usb <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': The feature is disabled in top-level and nested browsing contexts. <origin(s)...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. Default policy The default value is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. WebUSBThe definition of 'Feature-Policy integration' in that specification. Draft Default allow list...
Feature-Policy: vibrate - HTTP
The HTTP Feature-Policy header vibrate directive controls whether the current document is allowed to trigger device vibrations via Navigator.vibrate() method of Vibration API. Syntax Feature-Policy: vibrate <allowlist>; <vibrate> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (In an iframe allow attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's src attribute. 'none': The feature is ...
...e used with one or more origins. Features are each defined to have a default allowlist, which is one of: *: The feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': The feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. 'none': The feature is disabled in top-level and nested browsing contexts. The default value is 'self'. Specifications Specification Status Comment Feature Policy Editor's Draft Initial definition. ...
Range - HTTP
Web › HTTP › Headers › Range
The Range HTTP request header indicates the part of a document that the server should return. Several parts can be requested with one Range header at once, and the server may send back these ranges in a multipart document. If the server sends back ranges, it uses the 206 Partial Content for the response. If the ranges are invalid, the server returns the 416 Range Not Satisfiable error. The server can also ignore the Range header and return the whole document with a 200 status code. Header type Request header Forbidden header name no Syntax Range: <unit>=<range-start>- Range: <unit>=<range-start>-<range-end> Range: <unit>=<range-start>-<range-end>, <range-start>-<range-end> Range: <unit>=<range-start>-<range-end>, <range-start>-<range-end>, <range-start>-<range-end...
...-start>-<range-end>, <range-start>-<range-end> Range: <unit>=-<suffix-length> Directives <unit> The unit in which ranges are specified. This is usually bytes. <range-start> An integer in the given unit indicating the beginning of the request range. <range-end> An integer in the given unit indicating the end of the requested range. This value is optional and, if omitted, the end of the document is taken as the end of the range. <suffix-length> An integer in the given unit indicating the number of units at the end of the file to return. Examples Requesting three ranges from the file. Range: bytes=200-1000, 2000-6576, 19000- Requesting the first 500 and last 500 bytes of the file. The request may be rejected by the server if the ranges overlap. Range: bytes=0-499, -500 Specific...
Set-Cookie - HTTP
deadline is relative to the client the cookie is being set on, not the server. Max-Age=<number> Optional Number of seconds until the cookie expires. A zero or negative number will expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence. Domain=<domain-value> Optional Host to which the cookie will be sent. If omitted, defaults to the host of the current document URL, not including subdomains. Contrary to earlier specifications, leading dots in domain names (.example.com) are ignored. Multiple host/domain values are not allowed, but if a domain is specified, then subdomains are always included. Path=<path-value> Optional A path that must exist in the requested URL, or the browser won't send the Cookie header. The forward slash (/) character is ...
...equest 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 requests (that is, requests originating from the same site that...
HTTP Messages - HTTP
Web › HTTP › Messages
quests to be implemented, or its status of whether successful or a failure. This start-line is always a single line. An optional set of HTTP headers specifying the request, or describing the body included in the message. A blank line indicating all meta-information for the request has been sent. An optional body containing data associated with the request (like content of an HTML form), or the document associated with a response. The presence of the body and its size is specified by the start-line and HTTP headers. The start-line and HTTP headers of the HTTP message are collectively known as the head of the requests, whereas its payload is known as the body. HTTP Requests Start line HTTP requests are messages sent by the client to initiate an action on the server. Their start-line contai...
...sages sent by the client to initiate an action on the server. Their start-line contain three elements: An HTTP method, a verb (like GET, PUT or POST) or a noun (like HEAD or OPTIONS), that describes the action to be performed. For example, GET indicates that a resource should be fetched or POST means that data is pushed to the server (creating or modifying a resource, or generating a temporary document to send back). The request target, usually a URL, or the absolute path of the protocol, port, and domain are usually characterized by the request context. The format of this request target varies between different HTTP methods. It can be An absolute path, ultimately followed by a '?' and query string. This is the most common form, known as the origin form, and is used with GET, POST, HEAD,...
Proxy Auto-Configuration (PAC) file - HTTP
hould be saved to a file with a .pac filename extension: proxy.pac And the MIME type should be set to: application/x-ns-proxy-autoconfig Next, you should configure your server to map the .pac filename extension to the MIME type. Notes: The JavaScript function should always be saved to a file by itself but not be embedded in a HTML file or any other file. The examples at the end of this document are complete. There is no additional syntax needed to save it into a file and use it. (Of course, the JavaScripts must be edited to reflect your site's domain name and/or subnets.) Predefined functions and environment These functions can be used in building the PAC file: Hostname based conditions isPlainHostName() dnsDomainIs() localHostOrDomainIs() isResolvable() isInNet...
... balancing/routing based on URL patterns This example is more sophisticated. There are four (4) proxy servers; one of them is a hot stand-by for all of the other ones, so if any of the remaining three goes down the fourth one will take over. Furthermore, the three remaining proxy servers share the load based on URL patterns, which makes their caching more effective (there is only one copy of any document on the three servers - as opposed to one copy on each of them). The load is distributed like this: Proxy Purpose #1 .com domain #2 .edu domain #3 all other domains #4 hot stand-by All local accesses are desired to be direct. All proxy servers run on the port 8080 (they don't need to, you can just change your port but remember to ...
HTTP range requests - HTTP
lso explicitly send "none" as a value, indicating no support. In some apps, download managers disable their pause buttons in that case. curl -I https://www.youtube.com/watch?v=EwTZ2xpQwpA HTTP/1.1 200 OK ... Accept-Ranges: none Requesting a specific range from a server If the server supports range requests, you can issue such a request by using the Range header. It indicates the part(s) of a document that the server should return. Single part ranges We can request a single range from a resource. Again, we can test a request by using cURL. The "-H" option will append a header line to the request, which in this case is the Range header requesting the first 1024 bytes. curl http://i.imgur.com/z4d4kWk.jpg -i -H "Range: bytes=0-1023" The issued request looks like this: GET /z4d4kWk.jpg HTTP/1...
...ial Content Content-Range: bytes 0-1023/146515 Content-Length: 1024 ... (binary content) The Content-Length header now indicates the size of the requested range (and not the full size of the image). The Content-Range response header indicates where in the full resource this partial message belongs. Multipart ranges The Range header also allows you to get multiple ranges at once in a multipart document. The ranges are separated by a comma. curl http://www.example.com -i -H "Range: bytes=0-50, 100-150" The server responses with the 206 Partial Content status and a Content-Type: multipart/byteranges; boundary=3d6b6a416f9b5 header, indicating that a multipart byterange follows. Each part contains its own Content-Type and Content-Range fields and the required boundary parameter specifies the boun...
HTTP
Web › HTTP
It was designed for communication between web browsers and web servers, but it can also be used for other purposes. HTTP follows a classical client-server model, with a client opening a connection to make a request, then waiting until it receives a response. HTTP is a stateless protocol, meaning that the server does not keep any data (state) between two requests. Though often based on a TCP/IP layer, it can be used on any reliable transport layer, that is, a protocol that doesn't lose messages silently like UDP does. RUDP -- the reliable update of UDP -- is a suitable alternative. ...
...lications. HTTP Messages Describes the type and structure of the different kind of messages of HTTP/1.x and HTTP/2. A typical HTTP session Shows and explains the flow of a usual HTTP session. Connection management in HTTP/1.x Describes the three connection management models available in HTTP/1.x, their strengths, and their weaknesses. Reference Browse through detailed HTTP reference documentation. HTTP Headers HTTP message headers are used to describe a resource, or the behavior of the server or the client. Custom proprietary headers can be added using the X- prefix; others in an IANA registry, whose original content was defined in RFC 4229. IANA also maintains a registry of proposed new HTTP message headers. HTTP Request Methods The different operations that can be done with H...
A re-introduction to JavaScript (JS tutorial) - JavaScript
this loop type is not recommended for arrays. Another way of iterating over an array that was added with ECMAScript 5 is forEach(): ['dog', 'cat', 'hen'].forEach(function(currentValue, index, array) { // Do something with currentValue or array[index] }); If you want to append an item to an array simply do it like this: a.push(item); Arrays come with a number of methods. See also the full documentation for array methods. Method name Description a.toString() Returns a string with the toString() of each element separated by commas. a.toLocaleString() Returns a string with the toLocaleString() of each element separated by commas. a.concat(item1[, item2[, ...[, itemN]]]) Returns a new array with the items added on to it. a.join(sep)...
...ave a name? JavaScript lets you name function expressions for this. You can use named IIFEs (Immediately Invoked Function Expressions) as shown below: var charsInBody = (function counter(elm) { if (elm.nodeType == 3) { // TEXT_NODE return elm.nodeValue.length; } var count = 0; for (var i = 0, child; child = elm.childNodes[i]; i++) { count += counter(child); } return count; })(document.body); The name provided to a function expression as above is only available to the function's own scope. This allows more optimizations to be done by the engine and results in more readable code. The name also shows up in the debugger and some stack traces, which can save you time when debugging. Note that JavaScript functions are themselves objects -- like everything else in JavaScript -- an...
Equality comparisons and sameness - JavaScript
rison. Its behavior is equivalent to +A (the unary + operator). ToPrimitive(A) attempts to convert its object argument to a primitive value, by attempting to invoke varying sequences of A.toString and A.valueOf methods on A. Traditionally, and according to ECMAScript, all objects are loosely unequal to undefined and null. But most browsers permit a very narrow class of objects (specifically, the document.all object for any page), in some contexts, to act as if they emulate the value undefined. Loose equality is one such context: null == A and undefined == A evaluate to true if, and only if, A is an object that emulates undefined. In all other cases an object is never loosely equal to undefined or null. var num = 0; var obj = new String('0'); var str = '0'; console.log(num == num); // true conso...
...a -0 is introduced at that place and propogates out into stoppingForce. Math.atan2 Math.ceil Math.pow Math.round In some cases,it's possible for a -0 to be introduced into an expression as a return value of these methods even when no -0 exists as one of the parameters. For example, using Math.pow to raise -Infinity to the power of any negative, odd exponent evaluates to -0. Refer to the documentation for the individual methods. Math.floor Math.max Math.min Math.sin Math.sqrt Math.tan It's possible to get a -0 return value out of these methods in some cases where a -0 exists as one of the parameters. E.g., Math.min(-0, +0) evaluates to -0. Refer to the documentation for the individual methods. ~ << >> Each of these operators uses the ToInt32 algorithm internally. Since th...
Grammar and types - JavaScript
ontext. var a; a + 2; // Evaluates to NaN When you evaluate a null variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example: var n = null; console.log(n * 32); // Will log 0 to the console Variable scope When you declare a variable outside of any function, it is called a global variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within that function. JavaScript before ECMAScript 2015 does not have block statement scope. Rather, a variable declared within a block is local to the function (or global scope) that the block resides within. For example, the following code will log 5, because the scope of x is the globa...
...bles Global variables are in fact properties of the global object. In web pages, the global object is window, so you can set and access global variables using the window.variable syntax. Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called phoneNumber is declared in a document, you can refer to this variable from an iframe as parent.phoneNumber. Constants You can create a read-only, named constant with the const keyword. The syntax of a constant identifier is the same as any variable identifier: it must start with a letter, underscore, or dollar sign ($), and can contain alphabetic, numeric, or underscore characters. const PI = 3.14; A constant cannot change valu...
Loops and iteration - JavaScript
A do...while statement looks as follows: do statement while (condition); statement is always executed once before the condit...
... A do...while statement looks as follows: do statement while (condition); statement is always executed once before the condition is checked. (To execute multiple statements, use a block statement ({ ... }) to group those statements.) If condition i...
Memory Management - JavaScript
null, 'abra']; function f(a) { return a + 2; } // allocates a function (which is a callable object) // function expressions also allocate an object someElement.addEventListener('click', function() { someElement.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 ...
...ommon cause of memory leaks. function f() { var x = {}; var y = {}; x.a = y; // x references y y.a = x; // y references x return 'azerty'; } f(); Real-life example Internet Explorer 6 and 7 are known to have reference-counting garbage collectors for DOM objects. Cycles are a common mistake that can generate memory leaks: var div; window.onload = function() { div = document.getElementById('myDivElement'); div.circularReference = div; div.lotsOfData = new Array(10000).join('*'); }; In the above example, the DOM element "myDivElement" has a circular reference to itself in the "circularReference" property. If the property is not explicitly removed or nulled, a reference-counting garbage collector will always have at least one reference intact and will keep the DO...
TypeError: can't access dead object - JavaScript
The JavaScript exception "can't access dead object" occurs when Firefox disallows add-ons to keep strong references to DOM objects after their parent document has been destroyed to improve in memory usage and to prevent memory leaks. Message TypeError: can't access dead object Error type TypeError What went wrong? ...
...irefox disallows add-ons to keep strong references to DOM objects after their parent document has been destroyed to improve in memory usage and to prevent memory leaks. Message TypeError: can't access dead object Error type TypeError What went wrong? To improve in memory usage and to prevent memory leaks, Firefox disallows add-ons to keep strong references to DOM objects after their parent document has been destroyed. A dead object, is holding a strong (keep alive) reference to a DOM element that persists even after it was destroyed in the DOM. To avoid these issues, references to DOM nodes in foreign document should instead be stored in an object which is specific to that document, and cleaned up when the document is unloaded, or stored as weak references. Examples Checking if an object ...
TypeError: Reduce of empty array with no initial value - JavaScript
ich will remove all elements of the list. Thus leaving none to be used as the initial value. var ints = [0, -1, -2, -3, -4, -5]; ints.filter(x => x > 0) // removes all elements .reduce((x, y) => x + y) // no more elements to use for the initial value. Similarly, the same issue can happen if there is a typo in a selector, or an unexpected number of elements in a list: var names = document.getElementsByClassName("names"); var name_list = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + name); Valid cases These problems can be solved in two different ways. One way is to actually provide an initialValue as the neutral element of the operator, such as 0 for the addition, 1 for a multiplication, or an empty string for a concatenation. var ints = [0, -1, -2, -3, -4, ...
...iplication, or an empty string for a concatenation. var ints = [0, -1, -2, -3, -4, -5]; ints.filter(x => x > 0) // removes all elements .reduce((x, y) => x + y, 0) // the initial value is the neutral element of the addition Another way would be two to handle the empty case, either before calling reduce, or in the callback after adding an unexpected dummy initial value. var names = document.getElementsByClassName("names"); var name_list1 = ""; if (names1.length >= 1) name_list1 = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + name); // name_list1 == "" when names is empty. var name_list2 = Array.prototype.reduce.call(names, (acc, name) => { if (acc == "") // initial value return name; return acc + ", " + name; }, ""); // name_list2 == "" when names is emp...
Array.isArray() - JavaScript
rray.isArray(); Array.isArray({}); Array.isArray(null); Array.isArray(undefined); Array.isArray(17); Array.isArray('Array'); Array.isArray(true); Array.isArray(false); Array.isArray(new Uint8Array(32)); Array.isArray({ __proto__: Array.prototype }); instanceof vs isArray When checking for Array instance, Array.isArray is preferred over instanceof because it works through iframes. ...
... Array.isArray(null); Array.isArray(undefined); Array.isArray(17); Array.isArray('Array'); Array.isArray(true); Array.isArray(false); Array.isArray(new Uint8Array(32)); Array.isArray({ __proto__: Array.prototype }); instanceof vs isArray When checking for Array instance, Array.isArray is preferred over instanceof because it works through iframes. ...
Promise.any() - JavaScript
function fetchAndDecode(url) { return fetch(url).then(response => { if(!response.ok) { throw new Error(`HTTP error! ...
...esponse => { if(!response.ok) { throw new Error(`HTTP error! ...
Proxy - JavaScript
obj, prop, newval) { let oldval = obj[prop]; if (prop === 'selected') { if (oldval) { oldval.setAttribute('aria-selected', 'false'); } if (newval) { newval.setAttribute('aria-selected', 'true'); } } // The default behavior to store the value obj[prop] = newval; // Indicate success return true; } }); let i1 = view.selected = document.getElementById('item-1'); //giving error here, i1 is null console.log(i1.getAttribute('aria-selected')); // 'true' let i2 = view.selected = document.getElementById('item-2'); console.log(i1.getAttribute('aria-selected')); // 'false' console.log(i2.getAttribute('aria-selected')); // 'true' Note: even if selected: !null, then giving oldval.setAttribute is not a function Value correction and...
...'browser' }] console.log(products.types); // ['browser', 'mailer'] console.log(products.number); // 3 A complete traps list example Now in order to create a complete sample traps list, for didactic purposes, we will try to proxify a non-native object that is particularly suited to this type of operation: the docCookies global object created by the "little framework" published on the document.cookie page. /* var docCookies = ... get the "docCookies" object here: https://developer.mozilla.org/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support */ var docCookies = new Proxy(docCookies, { get: function (oTarget, sKey) { return oTarget[sKey] || oTarget.getItem(sKey) || undefined; }, set: function (oTarget, sKey, vValu...
this - JavaScript
tion for listeners added dynamically with methods other than addEventListener()). ...
... dynamically with methods other than addEventListener()). ...
import - JavaScript
rom '/modules/file.js'; getUsefulContents('http://www.example.com', data => { doSomethingUseful(data); }); Dynamic Import This example shows how to load functionality on to a page based on a user action, in this case a button click, and then call a function within that module. This is not the only way to implement this functionality. The import() function also supports await. ...
...www.example.com', data => { doSomethingUseful(data); }); Dynamic Import This example shows how to load functionality on to a page based on a user action, in this case a button click, and then call a function within that module. This is not the only way to implement this functionality. The import() function also supports await. ...
Transitioning to strict mode - JavaScript
ype; // error! In non-strict, this would silently fail, in contradiction with the user expectation. Poisoned arguments and function properties Accessing arguments.callee, arguments.caller, anyFunction.caller, or anyFunction.arguments throws an error in strict mode. ...
...ction.arguments throws an error in strict mode. The only legitimate use case would be to reuse a function as in: // example taken from vanillajs: http://vanilla-js.com/ var s = document.getElementById('thing').style; s.opacity = 1; (function() { if ((s.opacity-=.1) < 0) s.display = 'none'; else setTimeout(arguments.callee, 40); })(); which can be rewritten as: 'use strict'; var s = document.getElementById('thing').style; s.opacity = 1; (function fadeOut() { // name the function if((s.opacity-=.1) < 0) s.display = 'none'; else setTimeout(fadeOut, 40); // use the name of the function })(); Semantic differences These differences are very subtle differences. It's possible that a test suite doesn't catch this kind of subtle difference. Careful review of your code base will ...
JavaScript
standard for JavaScript is ECMAScript. As of 2012, all modern browsers fully support ECMAScript 5.1. 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...
... variant of ECMAScript 5, for faster performance and easier debugging. JavaScript typed arrays JavaScript typed arrays provide a mechanism for accessing raw binary data. Memory Management Memory life cycle and garbage collection in JavaScript. Concurrency model and Event Loop JavaScript has a concurrency model based on an "event loop". Reference Browse the complete JavaScript reference documentation. Standard objects Get to know standard built-in objects Array, Boolean, Date, Error, Function, JSON, Math, Number, Object, RegExp, String, Map, Set, WeakMap, WeakSet, and others. Expressions and operators Learn more about the behavior of JavaScript's operators instanceof, typeof, new, this, the operator precedence, and more. Statements and declarations Learn how do-while, for-in, for...
MathML
For a quick overview, see the slides for the innovation fairs at Mozilla Summit 2013. MathML reference MathML element reference Details about each MathML element and compatibility information for desktop and mobile browsers. MathML attribute reference Information about MathML attributes that modify the appearance or behavior of elements. ...
... 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 GreaseMonkey script. Related topics CSS HTML SVG ...
Web video codec guide - Web media technologies
video files; the degree to which this is true varies depending on the codec Bit rate Quality generally improves with higher bit rates Higher bit rates inherently lead to larger output files The options available when encoding video, and the values to be assigned to those options, will vary not only from one codec to another but depending on the encoding software you use. The documentation included with your encoding software will help you to understand the specific impact of these options on the encoded video. Compression artifacts Artifacts are side effects of a lossy encoding process in which the lost or rearranged data results in visibly negative effects. Once an artifact has appeared, it may linger for a while, because of how video is displayed. Each frame of video is p...
....2 as well; 16 indicates that we want to use the characteristics for BT.2100 PQ color. 09 The matrix coefficents to use, from the section 6.4.2 again. A value of 9 specifies that we want to use BT.2020 with variable luminance; this is also known as BT.2010 YbCbCr. 1 The video "full range" flag. A value of 1 indicates that we want the full color range to be used. The documentation for your codec choices will probably offer information you'll use when constructing your codecs parameter. ...
Recommended Web Performance Timings: How long is too long? - Web Performance
Load goal The 'Under a second' is often touted as optimal for load, but what does that mean? A second should be considered a rule in the maximum amount of time to indicate to a user that the request for new content was made and will load, such as the browser displaying the page title and the background color of the page displaying. The first asset retrieved from a request is usually an HTML document, which then makes calls for additional assets. As noted in the description of the critical rendering path, when received, browsers immediately start processing the HTML, rendering the content as it is received rather than waiting for additional assets to load. Yes, one second for loading is a goal, but it's something few sites achieve. Expectations differ. A 'hello world' on the corporate networ...
...d 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 occur at 60 frames per second (60fps), which is once every 16.7ms. The 16.7 milliseconds includes scripting, reflow, and repaint. Realize a document takes about 6ms to render a frame, leaving about 10ms for the rest. Anything less than 60fps, especially an un-even or changing frame rate, will appear janky. Responsiveness goal When the user interacts with content, it is important to provide feedback and acknowledge the user's response or interaction and to do so within 100ms, preferably within 50ms. 50ms seconds feels immediate. The acknowle...
Add to Home screen - Progressive web apps (PWAs)
o improve user experience on mobile OSes, there is movement to make PWAs installable on desktop platforms too. Note: At the time of writing, the functionality described below was only supported in newer versions of Chrome -- by default on Windows, and behind the #enable-desktop-pwas flag on macOS. ...
...le 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 A2HS criteria. When this happens, supporting browsers will fire a beforeinstallprompt event. We can then use a handler like the one below to handle the installation: window.addEventListener('beforeinstallprompt', (e) => { // Prevent C...
Progressive web app structure - Progressive web apps (PWAs)
y, streaming is a better model, but it's also more complex, and at the time of writing (March 2018) the Streams API is still a work-in-progress and not yet fully available in any of the major browsers. When it is available, it will be the fastest way of serving the content -- the benefits are going to be huge in terms of performance. For working examples and more information, see the Streams API documentation. Structure of our example application The js13kPWA website structure is quite simple: it consists of a single HTML file (index.html) with basic CSS styling (style.css), and a few images, scripts, and fonts. The folder structure looks like this: The HTML From the HTML point of view, the app shell is everything outside the content section: <!DOCTYPE html> <html lang="en"> <head> <meta ...
...i++) { var entry = template.replace(/POS/g,(i+1)) .replace(/SLUG/g,games[i].slug) .replace(/NAME/g,games[i].name) .replace(/AUTHOR/g,games[i].author) .replace(/TWITTER/g,games[i].twitter) .replace(/WEBSITE/g,games[i].website) .replace(/GITHUB/g,games[i].github); entry = entry.replace('<a href=\'http:///\'></a>','-'); content += entry; }; document.getElementById('content').innerHTML = content; Next, it registers a service worker: if('serviceWorker' in navigator) { navigator.serviceWorker.register('/pwa-examples/js13kpwa/sw.js'); }; The next code block requests permission for notifications when a button is clicked: var button = document.getElementById("notifications"); button.addEventListener('click', function(e) { Notification.
Progressive loading - Progressive web apps (PWAs)
e 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 met. In our js13kPWA demo app, the CSS is simple enough to leave it all in a single file with no specif...
...a-src='data/img/SLUG.jpg' alt='NAME'> Those images will be loaded via JavaScript after the site finishes building the HTML structure. The placeholder image is scaled the same way the original images are, so it will take up the same space and not cause the layout to repaint as the images load. Loading via JavaScript The app.js file processes the data-src attributes like so: let imagesToLoad = document.querySelectorAll('img[data-src]'); const loadImages = (image) => { image.setAttribute('src', image.getAttribute('data-src')); image.onload = () => { image.removeAttribute('data-src'); }; }; The imagesToLoad variable contains references to all the images, while the loadImages function moves the path from data-src to src. When each image is actually loaded, we remove its data-src attribu...
Progressive web apps (PWAs)
start URL, icons, and all of the other details necessary to transform the website into an app-like format. PWA advantages PWAs should be discoverable, installable, linkable, network independent, progressive, re-engageable, responsive, and safe. To find out more about what these mean, read Progressive web app advantages. To find out how to implement PWAs, read through our PWA developer guide. Documentation <-- The temporary automatic list below will be replaced soon --> Add to Home screenAdd to Home screen (or A2HS for short) is a feature available in modern browsers that allows a user to "install" a web app, ie. add a shortcut to their Home screen representing their favorite web app (or site) so they can subsequently access it with a single tap. This guide explains how A2HS is used, an...
...new content whenever it is available.Introduction to progressive web appsThis article provides an introduction to Progressive Web Apps (PWAs), discussing what they are and the advantages they offer over regular web apps.Making PWAs work offline with Service workersIn this article we took a simple look at how you can make your PWA work offline with service workers. Be sure to check out our further documentation if you want to learn more about the concepts behind the Service Worker API and how to use it in more detail. Progressive loadingIn previous articles we covered APIs that help us make our js13kPWA example a Progressive Web App: Service Workers, Web Manifests, Notifications and Push. In this article we will go even further and improve the performance of the app by progressively loading its...
Web technology reference
The open web is based on a number of technologies which, together, can be used to create everything from simple sites to powerful web applications. Below you'll find links to a selection of key documentation for each. If you're new to web development, consider starting with our learning area, which is filled with step-by-step tutorials that will guide you from total webdev newbie to at least semi-pro! HTML -- Structuring the web HyperText Markup Language is used to define and describe semantically the content (markup) of a web page in a well-structured format. HTML provides a means to create structured documents made up of blocks called HTML elements that are delineated by tags, written using angle brackets. Some introduce content into the page directly, others provide information ab...
...Obviously, browsers do not display them, since they are used to interpret the content of the page. ...
SVG Core Attributes - SVG: Scalable Vector Graphics
Web › SVG › Attribute › Core
The SVG core attributes are all the common attributes that can be specified on any SVG element. id lang tabindex xml:base xml:lang xml:space Attributes id Defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS). Value: Any valid ID string; Animatable: No lang Participates in defining the language of the element, the language that non-editable elements are written in or the language that editable elements should be written in. The tag contains one single entry value in the format defined in the Tags for Identifying Languages (BCP47) IETF document. SVG 2 introduce the new lang attributes. If both lang and xml:lang attribute are used...
...lang attribute are used, xml:lang has priority over lang. Value: Any valid language ID; Animatable: No tabindex The tabindex SVG attribute allows you to control whether an element is focusable and to define the relative order of the element for the purposes of sequential focus navigation. Value type: <integer>; Animatable: No xml:base Specifies a base IRI other than the base IRI of the document. Value type: <IRI>; Animatable: No xml:lang It is a universal attribute allowed in all XML dialects to mark up the natural human language that an element contains. It's almost identical in usage to HTML's lang, but in conforming XML 1.0 documents, it does not allow the use of a null attribute value (xml:lang="") to indicate an unknown language. Instead, use xml:lang="und". SVG 2 introduc...
SVG Event Attributes - SVG: Scalable Vector Graphics
Web › SVG › Attribute › Events
every event type that the browser supports, SVG supports that as an event attribute, following the same requirements as for HTML event attributes. The global event attributes are available on all SVG elements. Other event attributes are available on a case by case basis for each elements. All event attribute are not animatable. ...
...attribute, following the same requirements as for HTML event attributes. The global event attributes are available on all SVG elements. Other event attributes are available on a case by case basis for each elements. All event attribute are not animatable. ...
externalResourcesRequired - SVG: Scalable Vector Graphics
This attribute applies to all types of resource references, including style sheets, color profiles and fonts specified by a reference using a <font-face> element or a CSS @font-face specification. In particular, if an element sets externalResourcesRequired="true", then all style sheets must be available since any style sheet might affect the rendering of that element. ...
...is. Instead, it is better to specify externalResourcesRequired="true" on those particular graphics elements or container elements which specifically need the availability of external resources in order to render properly. Usage notes Value false | true Default value false Animatable No true This value indicates that resources external to the current document are required. If an external resource is not available, progressive rendering is suspended, the document's SVGLoad event is not fired and the animation timeline does not begin until that resource and all other required resources become available, have been parsed and are ready to be rendered. false This value indicates that resources external to the current document are optional. Document rende...
fill - SVG: Scalable Vector Graphics
Web › SVG › Attribute › fill
...
... ...
height - SVG: Scalable Vector Graphics
Web › SVG › Attribute › height
th> | <percentage> Default value 100% Animatable Yes filter For <filter>, height defines the vertical length for the rendering area of the filter. Value <length> | <percentage> Default value 120% Animatable Yes foreignObject For <foreignObject>, height defines the vertical length for the rendering area for the referenced document. Value auto | <length> | <percentage> Default value auto (treated as 0) Animatable Yes Note: Starting with SVG2, height is a Geometry Property meaning this attribute can also be used as a CSS property for <foreignObject>. image For <image>, height defines the vertical length for the image. Value auto | <length> | <percentage> Def...
...ngth for the rectangle. Value auto | <length> | <percentage> Default value auto (treated as 0) Animatable Yes Note: Starting with SVG2, height is a Geometry Property meaning this attribute can also be used as a CSS property for rectangles. svg For <svg>, height defines the vertical length for the rendering area of the SVG viewport. Note: In an HTML document if both the viewBox and height attributes are omitted, the svg element will be rendered with a height of 150px Value auto | <length> | <percentage> Default value auto (treated as 100%) Animatable Yes Note: Starting with SVG2, height is a Geometry Property meaning this attribute can also be used as a CSS property for <svg>. use For <use>, height defi...
stroke - SVG: Scalable Vector Graphics
Web › SVG › Attribute › stroke
...
... ...
width - SVG: Scalable Vector Graphics
Web › SVG › Attribute › width
> | <percentage> Default value 100% Animatable Yes filter For <filter>, width defines the horizontal length for the rendering area of the filter. Value <length> | <percentage> Default value 120% Animatable Yes foreignObject For <foreignObject>, width defines the horizontal length for the rendering area for the referenced document. Value auto | <length> | <percentage> Default value auto (treated as 0) Animatable Yes Note: Starting with SVG2, width is a Geometry Property meaning this attribute can also be used as a CSS property for <foreignObject>. image For <image>, width defines the horizontal length for the image. Value auto | <length> | <percentage> Def...
...length for the rectangle. Value auto | <length> | <percentage> Default value auto (treated as 0) Animatable Yes Note: Starting with SVG2, width is a Geometry Property meaning this attribute can also be used as a CSS property for rectangles. svg For <svg>, width defines the horizontal length for the rendering area of the SVG viewport. Note: In an HTML document if both the viewBox and width attributes are omitted, the svg element will be rendered with a width of 300px Value auto | <length> | <percentage> Default value auto (treated as 100%) Animatable Yes Note: Starting with SVG2, width is a Geometry Property meaning this attribute can also be used as a CSS property for <svg>. use For <use>, width defines th...
SVG Attribute reference - SVG: Scalable Vector Graphics
Web › SVG › Attribute
SVG elements can be modified using attributes that specify details about exactly how the element should be handled or rendered. Below is a list of all of the attributes available in SVG along with links to reference documentation to help you learn which elements support them and how they work. SVG attributes A to Z A accent-height accumulate additive alignment-baseline allowReorder alphabetic amplitude arabic-form ascent attributeName attributeType autoReverse azimuth B baseFrequency baseline-shift baseProfile bbox begin bias by C calcMode cap-height class clip clipPathUnits clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering contentScriptType contentStyleType cursor cx cy D d decelerate d...
...n Attribute Target Attributes attributeType, attributeName Animation Timing Attributes begin, dur, end, min, max, restart, repeatCount, repeatDur, fill Animation Value Attributes calcMode, values, keyTimes, keySplines, from, to, by, autoReverse, accelerate, decelerate Animation Addition Attributes additive, accumulate Event Attributes Animation Event Attributes onbegin, onend, onrepeat Document Event Attributes onabort, onerror, onresize, onscroll, onunload Global Event Attributes oncancel, oncanplay, oncanplaythrough, onchange, onclick, onclose, oncuechange, ondblclick, ondrag, ondragend, ondragenter, ondragexit, ondragleave, ondragover, ondragstart, ondrop, ondurationchange, onemptied, onended, onerror, onfocus, oninput, oninvalid, onkeydown, onkeypress, onkeyup, onload, onloadedda...
<altGlyph> - SVG: Scalable Vector Graphics
Web › SVG › Element › altGlyph
e: none; Animatable: yes (non-additive) glyphRef The glyph identifier, the format of which is dependent on the format defined by the format attribute of the given font. Value type: <string> ; Default value: none; Animatable: no format The format of the given font. Value type: <string> ; Default value: none; Animatable: no xlink:href An <iri> reference either to a <glyph> element in an SVG document or to an <altGlyphDef> element. If the reference is to a <glyph> element and that glyph is available, then that glyph is rendered instead of the character(s) that are inside of the <altGlyph> element. If the reference is to an <altGlyphDef> element, then if an appropriate set of alternate glyphs is located from processing the <altGlyphDef> element, then those alternate glyphs are rendered i...
...ment, then those alternate glyphs are rendered instead of the character(s) that are inside of the <altGlyph> element. ...
<defs> - SVG: Scalable Vector Graphics
Web › SVG › Element › defs
objects that will be used at a later time. Objects created inside a <defs> element are not rendered directly. To display them you have to reference them (with a <use> element for example). Graphical objects can be referenced from anywhere, however, defining these objects inside of a <defs> element promotes understandability of the SVG content and is beneficial to the overall accessibility of the document. html,body,svg { height:100% } <svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- Some graphical objects to use --> <defs> <circle id="myCircle" cx="0" cy="0" r="5" /> <linearGradient id="myGradient" gradientTransform="rotate(90)"> <stop offset="20%" stop-color="gold" /> <stop offset="90%" stop-color="red...
...0)"> <stop offset="20%" stop-color="gold" /> <stop offset="90%" stop-color="red" /> </linearGradient> </defs> <!-- using my graphical objects --> <use x="5" y="5" xlink:href="#myCircle" fill="url('#myGradient')" /> </svg> Attributes Global attributes Core Attributes Most notably: id lang Styling Attributes class, style Event Attributes Global event attributes, Document element event attributes, Graphical event attributes Presentation Attributes Most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transfor...
Linking - SVG: Scalable Vector Graphics
Web › SVG › Linking
The target attribute on the SVG <a> element doesn't work in Mozilla Firefox 1.5. When SVG documents are embedded within a parent HTML document using the tag: page1.html: <html> <body> <p>This is a SVG button:</p> <object width="100" height="50" type="image/svg+xml" data="button.svg"/> </body> </html> button.svg: <?xml version="1.1" encoding="UTF-8"?> <svg xmlns="http://www.w3.org/2000/svg"> <a xlink:href="page2.html" target="_top"> <g> <!-- button graphical elements here --> </g> </a> </svg> The specification says that the browser should navigate to the HTML document page2.html when the button graphics are clicked. 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.) Any...
...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 1.1 Support in Firefox - SVG: Scalable Vector Graphics
Someday. There is also a description of the Mozilla support of the changes in SVG 2. Element implementation status A quick overview of the SVG 1.1 elements and the current status of the native support. Element Notes Structure Module svg Implemented. ...
... feComposite Implemented. feConvolveMatrix Implemented. feDiffuseLighting Implemented. feDisplacementMap Implemented. feFlood Implemented. feGaussianBlur Implemented. feImage Implemented. Document fragments (bug 455986) aren't supported in <svg:feImage>. feMerge Implemented. feMergeNode Implemented. feMorphology Implemented. feOffset Implemented. feSpecularLighting Implemented. feTile Implemented. ...
Positions - SVG: Scalable Vector Graphics
mine how Scalable Vector Graphics (SVG) represents the positions and sizes of objects within a drawing context, including coordinate system and what a "pixel" measurement means in a scalable context. The grid For all elements, SVG uses a coordinate system or grid system similar to the one used by canvas (and by a whole lot of other computer drawing routines). That is, the top left corner of the document is considered to be the point (0,0), or point of origin. Positions are then measured in pixels from the top left corner, with the positive x direction being to the right, and the positive y direction being to the bottom. Note that this is slightly different than the way you're taught to graph as a kid (y axis is flipped). However, this is the same way elements in HTML are positioned (By default, ...
...considered to be the point (0,0), or point of origin. Positions are then measured in pixels from the top left corner, with the positive x direction being to the right, and the positive y direction being to the bottom. Note that this is slightly different than the way you're taught to graph as a kid (y axis is flipped). However, this is the same way elements in HTML are positioned (By default, LTR documents are considered not the RTL documents which position X from right-to-left). Example: The element <rect x="0" y="0" width="100" height="100" /> defines a rectangle from the upper left corner, that spans from there 100px to the right and to the bottom. What are "pixels"? In the most basic case one pixel in an SVG document maps to one pixel on the output device (a.k.a. the screen). But SVG wo...
SVG: Scalable Vector Graphics
Web › SVG
Compared to classic bitmapped image formats such as JPEG or PNG, SVG-format vector images can be rendered at any size without loss of quality and can be easily localized by updating the text within them, without 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 M...
...uite Markup Validator More Tools... Other resources: 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 l...
Secure contexts - Web security
ry powerful, giving an attacker the ability to do the following and more: Invade a user's privacy. Get low-level access to a user's computer. Get access to data such as user credentials. When is a context considered secure? A context is considered secure when it meets certain minimum standards of authentication and confidentiality defined in the Secure Contexts specification. A particular document is considered to be in a secure context when it is the active document of a top-level browsing context (basically, a containing window or tab) that is a secure context. For example, even for a document delivered over TLS within an <iframe>, its context is not considered secure if it has an ancestor that was not also delivered over TLS. However, it's important to note that if a non-secure contex...
...ts context is not considered secure if it has an ancestor that was not also delivered over TLS. However, it's important to note that if a non-secure context causes a new window to be created (with or without specifying noopener), then the fact that the opener was insecure has no effect on whether the new window is considered secure. That's because the determination of whether or not a particular document is in a secure context is based only on considering it within the top-level browsing context with which it is associated -- and not whether a non-secure context happened to be used to create it. Locally-delivered resources such as those with http://127.0.0.1 URLs, http://localhost URLs (under certain conditions), and file:// URLs are also considered to have been delivered securely. Resources th...
XML Index - XML: Extensible Markup Language
Web › XML › Index
2 XML Index Index, Web, XML Found 4 pages: 3 XML introduction Beginner, Introduction, XML XML is a markup language similar to HTML. It stands for Extensible Markup Language and is a W3C recommended specification as a general purpose markup language. ...
...up language. This means, unlike other markup languages, XML is not predefined so you must define your own tags. The primary purpose of the language is the sharing of data across different systems, such as the Internet. 4 xml:base HTML BaseElement, NeedsSpecTable, SVG, xml:base xml:base is like the HTML BaseElement but can specify the base URI per element as well as the entire document. ...
XML: Extensible Markup Language
Web › XML
XML IndexFound 4 pages:XML introductionXML is a markup language similar to HTML. It stands for Extensible Markup Language and is a W3C recommended specification as a general purpose markup language. This means, unlike other markup languages, XML is not predefined so you must define your own tags. The primary purpose of the language is the sharing of data across different systems, such as the Internet. ...
... ...
Resources - XSLT: Extensible Stylesheet Language Transformations
...
... ...
The Netscape XSLT/XPath Reference - XSLT: Extensible Stylesheet Language Transformations
The following is an alphabetized and annotated list of the elements, axes, and functions from the W3C's 1.0 Recommendation for XSLT, as well as from the appropriate sections of the XPath Recommendation. Development of the XSLT processor is ongoing, and this document will be updated as functionality is expanded. Elements xsl:apply-imports (supported) xsl:apply-templates (supported) xsl:attribute (supported) xsl:attribute-set (supported) xsl:call-template (supported) xsl:choose (supported) xsl:comment (supported) xsl:copy (supported) xsl:copy-of (supported) xsl:decimal-format (supported) xsl:element (supported) xsl:fallback (not supported) xsl:for-each (supported) xsl:if (supported) xsl:import (mostly supported) xsl:include (supported) xsl:key (supported) xsl:mes...
...ted) xsl:when (supported) xsl:with-param (supported) Axes ancestor ancestor-or-self attribute child descendant descendant-or-self following following-sibling namespace (not supported) parent preceding preceding-sibling self Functions boolean() (supported) ceiling() (supported) concat() (supported) contains() (supported) count() (supported) current() (supported) document() (supported) element-available() (supported) false() (supported) floor() (supported) format-number() (supported) function-available() (supported) generate-id() (supported) id() (partially supported) key() (supported) lang() (supported) last() (supported) local-name() (supported) name() (supported) namespace-uri() (supported) normalize-space() (supported) not() (sup...
Basic Example - XSLT: Extensible Stylesheet Language Transformations
de()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> The example loads using synchronous XMLHTTPRequest both the .xsl (xslStylesheet) and the .xml (xmlDoc) files into memory. The .xsl file is then imported (xsltProcessor.importStylesheet(xslStylesheet)) and the transformation run (xsltProcessor.transformToFragment(xmlDoc, document)). This allows fetching of data after the page has been loaded, without initiating a fresh page load. Figure 6 : Example var xslStylesheet; var xsltProcessor = new XSLTProcessor(); var myDOM; var xmlDoc; function Init(){ // load the xslt file, example1.xsl var myXMLHTTPRequest = new XMLHttpRequest(); myXMLHTTPRequest.open("GET", "example1.xsl", false); myXMLHTTPRequest.send(null); ...
... myXMLHTTPRequest.send(null); xslStylesheet = myXMLHTTPRequest.responseXML; xsltProcessor.importStylesheet(xslStylesheet); // load the xml file, example1.xml myXMLHTTPRequest = new XMLHttpRequest(); myXMLHTTPRequest.open("GET", "example1.xml", false); myXMLHTTPRequest.send(null); xmlDoc = myXMLHTTPRequest.responseXML; var fragment = xsltProcessor.transformToFragment(xmlDoc, document); document.getElementById("example").innerHTML = ""; myDOM = fragment; document.getElementById("example").appendChild(fragment); } ...
Web technology for developers
Documentation for Web developers Web Developer Reference A list of all references for Web technologies, including those for HTML, CSS, and so on. Web Developer Guide The Web Developer Guide provides useful how-to content to help you actually use Web technologies to do what you want or need to do. ...
...f all references for Web technologies, including those for HTML, CSS, and so on. Web Developer Guide The Web Developer Guide provides useful how-to content to help you actually use Web technologies to do what you want or need to do. Tutorials for Web developers A list of tutorials to take you step-by-step through learning APIs, technologies, or broad topic areas. Developing Web applications Documentation for Web application developers; Web apps are true write-once, deploy anywhere apps for mobile, desktop, and Firefox OS. Code snippets This is a quick list of useful code snippets (small code samples) available for developers of extensions for the various Mozilla applications. Many of these samples can also be used in XULRunner applications, as well as in actual Mozilla code itself. View ...
Compiling from Rust to WebAssembly - WebAssembly
rname/hello-wasm" [lib] crate-type = ["cdylib"] [dependencies] wasm-bindgen = "0.2" Fill in your own repository and use the same info that git uses for the authors field. The big part to add is the stuff at the bottom. The first part -- [lib] -- tells Rust to build a cdylib version of our package; we won't get into what that means in this tutorial. For more, consult the Cargo and Rust Linkage documentation. The last section is the [dependencies] section. Here's where we tell Cargo what version of wasm-bindgen we want to depend on; in this case, that's any 0.2.z version (but not 0.3.0 or above). Building the package Now that we've got everything set up, let's build the package. Type this into your terminal: $ wasm-pack build This does a number of things (and they take a lot of time, especi...
...sult? You have an npm package inside of the pkg directory. A digression about code size If you check out the generated WebAssembly code size, it may be a few hundred kilobytes. We haven't instructed Rust to optimize for size at all, and doing so cuts down on the size a lot. This is beyond the scope of this tutorial, but if you'd like to learn more, check out the Rust WebAssembly Working Group's documentation on Shrinking .wasm Size. Making our package availabe to npm Let's use `npm link` to make this package available to other javascript packages installed $ cd pkg $ npm link We now have an npm package, written in Rust, but compiled to WebAssembly. It's ready for use from JavaScript, and doesn't require the user to have Rust installed; the code included was the WebAssembly code, not the Rust...
API - Archive of obsolete content
NavigatorFeatures that used to hang off the Navigator interface, but have since been removed. ...
Loading Content Scripts - Archive of obsolete content
: 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, debug and review. The contentScriptWhen option specifies when the content script(s) should be loaded. It takes one of three possible values: "start" loads the scripts immediately after the document element for the page is inserted into the DOM. At this point the DOM content hasn't been loaded yet, so the script won't be able to interact with it. "ready" loads the scripts after the DOM for the page has been loaded: that is, at the point the DOMContentLoaded event fires. At this point, content scripts are able to interact with the DOM content, but externally-referenced stylesheets and i...
Content Processes - Archive of obsolete content
de with chrome privileges, so we use specialized wrappers, called security wrappers, to limit access to the object in the other sandbox. The xray wrappers we saw earlier are an example of such a security wrapper. Security wrappers are created automatically, by the underlying host application. A full discussion of the different kinds of security wrappers and how they work is out of scope for this document, but the main point is this: security wrappers are very complex, and very error-prone. They are subject to change, in order to fix some security leak that recently popped up. As a result, code that worked just fine last week suddenly does not work the way you expect. By only passing messages between add-on modules and content scripts, these problems can be avoided, making your add-on both easier ...
Modules - Archive of obsolete content
ns: 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 scope. This object forms the central access point for all functionality provided by the host application. A complete explanation of how to use Components is out of scope for this document. However, the following example shows how it can be used to load scripts from other locations: const { classes: Cc interfaces: Ci } = Components; var instance = Cc["@mozilla.org/moz/jssubscript-loader;1"]; var loader = instance.getService(Ci.mozIJSSubScriptLoader); function loadScript(url) { loader.loadSubScript(url); } When a script is loaded, it is evaluated in the scope of the ...
Module structure of the SDK - Archive of obsolete content
ou want to use. For high-level modules this is just sdk/<module_name>, and for low-level modules it is sdk/<path_to_module>/<module_name>: // load the high-level "tabs" module var tabs = require("sdk/tabs"); // load the low-level "uuid" module var uuid = require('sdk/util/uuid'); The path to specify for a low-level module is given along with the module name itself in the title of the module's documentation page (for example, system/environment). Although the SDK repository in GitHub includes copies of these modules, they are built into Firefox and by default, when you run or build an add-on using jpm run or jpm xpi, it is the versions of the modules in Firefox that are used. If you need to use a different version of the modules, you can do this by checking out the version of the SDK that you ...
Working with Events - Archive of obsolete content
ou can add a listener to an event emitter by calling its on(type, listener) method. It takes two parameters: type: the type of event we are interested in, identified by a string. Many event emitters may emit more than one type of event: for example, a browser window might emit both open and close events. The list of valid event types is specific to an event emitter and is included with its documentation. listener: the listener itself. This is a function which will be called whenever the event occurs. The arguments that will be passed to the listener are specific to an event type and are documented with the event emitter. For example, the following add-on registers a listener with the tabs module to listen for the ready event, and logs a string to the console reporting the event: ...
notifications - Archive of obsolete content
ar notifications = require("sdk/notifications"); notifications.notify({ title: "Jabberwocky", text: "'Twas brillig, and the slithy toves", data: "did gyre and gimble in the wabe", onClick: function (data) { console.log(data); // console.log(this.data) would produce the same result. } }); This one displays an icon that's stored in the add-on's data directory. See the self module documentation for more information. var notifications = require("sdk/notifications"); var self = require("sdk/self"); var myIconURL = self.data.url("myIcon.png"); notifications.notify({ text: "I have an icon!", iconURL: myIconURL }); From Firefox 34, you can use "./myIcon.png" as an alias for self.data.url("myIcon.png"). So you can rewrite the above code like this: var notifications = require("sd...
selection - Archive of obsolete content
itself. Each iteration yields a Selection object from which text, html, and isContiguous properties can be accessed. Private Windows If your add-on has not opted into private browsing, then you won't see any selections made in tabs that are hosted by private browser windows. To learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module. Examples Log the current contiguous selection as text: var selection = require("sdk/selection"); if (selection.text) console.log(selection.text); Log the current discontiguous selections as HTML: var selection = require("sdk/selection"); if (!selection.isContiguous) { for (var subselection in selection) { console.log(subselection.html); } } S...
simple-prefs - Archive of obsolete content
ce, so users of your add-on won't be able to see or alter it. { "name": "myHiddenInteger", "type": "integer", "title": "How Many?", "hidden": true } Your add-on's code will still be able to access and modify it, just like any other preference you define. Type-Specific Attributes These are settings that are only applicable to certain preference types. They are documented along with the preference types themselves. Preference Types The setting types map to the inline settings types used by the Add-on Manager. All the inline preferences are supported. Type Description Example Specification bool Displayed as a checkbox and stores a boolean. { "description": "Does it have tentacles?", "type": "bool", "name": "hasTen...
simple-storage - Archive of obsolete content
erQuota", function () { while (ss.quotaUsage > 1) ss.storage.myList.pop(); }); Private browsing If your storage is related to your users' Web history, personal information, or other sensitive data, your add-on should respect private browsing. To read about how to opt into private browsing mode and how to use the SDK to avoid storing user data associated with private windows, refer to the documentation for the private-browsing module. Globals Properties storage A persistent object private to your add-on. Properties with array, boolean, number, object, null, and string values will be persisted. quotaUsage A number in the range [0, Infinity) that indicates the percentage of quota occupied by storage. A value in the range [0, 1] indicates that the storage is within quota. A value greate...
system - Archive of obsolete content
at functionality to add-on authors. For the full list of "special" directories and their IDs, see "Getting_files in special directories". For example: // get Firefox profile path var profilePath = require('sdk/system').pathFor('ProfD'); // get OS temp files directory (/tmp) var temps = require('sdk/system').pathFor('TmpD'); // get OS desktop path for an active user (~/Desktop on linux // or C:\Documents and Settings\username\Desktop on windows). var desktopPath = require('sdk/system').pathFor('Desk'); Parameters id : String The ID of the special directory. Returns String : The path to the directory. Properties env This object provides access to environment variables. You can get the value of an environment variable by accessing the property with that name: var system = require("sdk/sy...
High-Level APIs - Archive of obsolete content
addon-page Create a page that does not contain navigational elements. 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. ...
/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, Re...
content/loader - Archive of obsolete content
by this property are loaded before those specified by the contentScript property. contentScript The texts of content scripts to load. Content scripts specified by this property are loaded after those specified by the contentScriptFile property. contentScriptWhen When to load the content scripts. ...
core/heritage - Archive of obsolete content
ake a dance with // another special `constructor` property of the `prototype` object. Object.defineProperty(Pet.prototype, 'constructor', { value: Pet }); // Finally you can define some properties. Pet.prototype.call = function(name) { return this.name === name ? this.bark() : ''; }; Since SDK APIs may be interacting with untrusted code an extra security measures are required to guarantee that documented behavior can't be changed at runtime. To do that we need to freeze constructor's prototype chain to make sure functions are frozen: Object.freeze(Dog.prototype); Object.freeze(Pet.prototype); Note: Also, this is not quite enough as Object.prototype stays mutable & in fact we do little bit more in SDK to address that, but it's not in the scope of this documentation. Doing all of this manually...
core/namespace - Archive of obsolete content
s } = require('sdk/core/namespace'); let { View } = require('./view'); // Note this is completely independent from View's internal Namespace object. let sandboxes = ns(); function Widget(options) { let { element, contentScript } = options; let widget = Object.create(Widget.prototype); View.call(widget, options.element); sandboxes(widget).sandbox = Cu.Sandbox(element.ownerDocument.defaultView); // ... } Widget.prototype = Object.create(View.prototype); Widget.prototype.postMessage = function postMessage(message) { let { sandbox } = sandboxes(this); sandbox.postMessage(JSON.stringify(JSON.parse(message))); ... }; Widget.prototype.destroy = function destroy() { View.prototype.destroy.call(this); // ... delete sandboxes(this).sandbox; }...
core/promise - Archive of obsolete content
Doing things concurrently So far we have being playing with promises that do things sequentially, but there are many cases where one would need to do things concurrently. In the following example we implement functions that take multiple promises and return one that resolves to first one being fulfilled: function race() { let { promise, resolve } = defer()...
event/target - Archive of obsolete content
not define an API for emitting events. In majority of cases party emitting events is different from party registering listeners. In order to emit events one needs to use event/core module instead: let { emit } = require('sdk/event/core'); target.on('hi', function(person) { console.log(person + ' says hi'); }); emit(target, 'hi', 'Mark'); // info: 'Mark says hi' For more details see event/core documentation. More details Listeners registered during the event propagation (by one of the listeners) won't be triggered until next emit of the matching type: let { emit } = require('sdk/event/core'); target.on('message', function onMessage(message) { console.log('listener triggered'); target.on('message', function() { console.log('nested listener triggered'); }); }); emit(target, 'messag...
frame/hidden-frame - Archive of obsolete content
Globals Constructors HiddenFrame(options) Creates a hidden frame. Parameters options : object Required options: Name Type onReady function,array Functions to call when the frame is ready to load content. You must specify an onReady callback ...
fs/path - Archive of obsolete content
...
loader/cuddlefish - Archive of obsolete content
Deprecated in Firefox 38. The toolkit/loader module should be used instead. The SDK's module loader. This module still needs to be documented. ...
loader/sandbox - Archive of obsolete content
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). Evaluate code Module provides evaluate 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. e...
remote/child - Archive of obsolete content
level DOM window for the frame, and addEventListener/removeEventListener functions that enable you to listen to DOM events dispatched by the frame. Communicating with the parent process To communicate with the parent process, the process, frames, and frame objects in sdk/remote/child have a port object that you can use to receive messages from, and send messages to, code in the parent. See the documentation for sdk/remote/parent for more details. Globals Properties process A Process object. frames A Frames object. Process A link to the main process. Properties port An event emitter that sends and receives events from the main process. isRemote A boolean property indicating whether this process is remote from the main process or not. Frames A list of the content frames in this pro...
stylesheet/utils - Archive of obsolete content
Experimental Helper functions for working with stylesheets. Globals Functions loadSheet(window, uri, type) Synchronously loads a style sheet from uri and adds it to the list of additional style sheets of the document. The sheets added takes effect immediately, and only on the document of the window given. Parameters window : nsIDOMWindow uri : string, nsIURI} type : string The type of the sheet. It accepts the following values: "agent", "user" and "author". If not provided, the default value is "author". removeSheet(window, uri, type) Remove the document style sheet at sheetURI from the list of additional style sheets of the document. The removal takes effect immediately. Parameters window : nsIDOMWindow uri : string, nsIURI} type : string The type of the sheet. It accepts th...
test/httpd - Archive of obsolete content
").when(function cleanup() { srv.stop(function() { // you should continue execution from this point. }) }); This starts a server in background (assuming you're running this code in an application that has an event loop, such as Firefox). The server listens at http://localhost:port/ and serves files from the specified directory. You can serve static content or use SJS scripts, as described in documentation on developer.mozilla.org. You can also use nsHttpServer to start the server manually: var { nsHttpServer } = require("sdk/test/httpd"); var srv = new nsHttpServer(); // further documentation on developer.mozilla.org See HTTP server for unit tests for general information. ...
util/uuid - Archive of obsolete content
Generate or parse UUIDs. Usage It exports a single function, uuid(). For more details about UUID representations and what they are used for by the platform see the MDN documentation for JSID. Generate UUID To generate a new UUID, call uuid() with no arguments: let uuid = require('sdk/util/uuid').uuid(); Parsing UUID To convert a string representation of a UUID to an nsID, pass the string representation to uuid(): let { uuid } = require('sdk/util/uuid'); let firefoxUUID = uuid('{ec8030f7-c20a-464f-9b0e-13a3a9e97384}'); Globals Functions uuid(stringId) Generate a new UUID, or convert a string representation of a UUID to an nsID. Parameters stringId : string String representation of a UUID, such as: "8CBC9BF4-4A16-11E2-AEF7-C1A56188709B" Optional. If this argument is supplied, it...
Release notes - Archive of obsolete content
tails GitHub commits made between Firefox 30 and Firefox 31. This will not include any uplifts made after this release entered Aurora. Bugs fixed between Firefox 30 and Firefox 31. This will not include any uplifts made after this release entered Aurora. Firefox 30 Highlights Added the ability to anchor panels to buttons. Changes in the way content scripts share objects with page scripts. Documentation and blog post. Added child_process, an implementation of the node.js child_process API. Content scripts in page-mod get detach events when the add-on is disabled or removed. throttle() and debounce() functions added to lang/functional. getTabForId() function added to tabs/utils. Details GitHub commits made between Firefox 29 and Firefox 30. This will not include any uplifts made after...
jpm-mobile - Archive of obsolete content
Firefox specified in BINARY. jpm-mobile run -b fennec You can get the package name by following command. $ adb shell pm list packages | grep org.mozilla package:org.mozilla.firefox $ jpm-mobile run -b firefox # the package name is firefox -v --verbose Verbose operation. jpm-mobile test jpm-mobile test See the tutorial on unit testing and the reference documentation for the assert module for more details on this. jpm-mobile test accepts the following options: --adb /path/to/adb Provides the path to adb. -b --binary BINARY Use the package name of Firefox specified in BINARY. jpm-mobile test -b fennec You can get the package name by following command. $ adb shell pm list packages | grep org.mozilla package:org...
jpmignore - Archive of obsolete content
to specify a directory. /sample/ A .jpmignore file with the above contents would ignore all zip files and .DS_Store files and sample directory from the xpi generated by jpm xpi. Using .jpmignore to allow files Everything in your add-on directory will be included in the xpi file you make with jpm xpi. If your project folder contains a lot of files that aren't necessary for the xpi to run, like documentation, jshint, etc., you can use .jpmignore as a whitelist instead of a blacklist. For example: .* * !/data/** !/lib/** !/locale/** !/node_modules/** !/package.json !/icon.png !/icon64.png !/COPYING !/bootstrap.js !/install.rdf This would include all editor backup files and similar in the whitelisted subdirectories, to avoid that you can append another blacklist after the whitelist. This one wou...
Adding a Button to the Toolbar - Archive of obsolete content
indow, or for a specific tab. Read more about updating state. Attaching a panel If you need to attach a panel to a button, use the toggle button API. This is just like the action button API except it adds a boolean checked property which is toggled whenever the button is checked. To attach the panel, pass the button 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 refe...
Displaying annotations - Archive of obsolete content
sages to the main module, asking it to show or hide the annotation. Like the selector, the matcher also listens for the window's unload event and on unload sends a detach message to the main module, so the add-on can clean it up. ...
Display a Popup - Archive of obsolete content
is the text the user // entered. // In this implementation we'll just log the text to the console. text_entry.port.on("text-entered", function (text) { console.log(text); text_entry.hide(); }); The content script "get-text.js" looks like this: // When the user hits return, send the "text-entered" // message to main.js. // The message payload is the contents of the edit box. var textArea = document.getElementById("edit-box"); textArea.addEventListener('keyup', function onkeyup(event) { if (event.keyCode == 13) { // Remove the newline. text = textArea.value.replace(/(\r\n|\n|\r)/gm,""); self.port.emit("text-entered", text); textArea.value = ''; } }, false); // Listen for the "show" event being sent from the // main add-on code. It means that the panel's about // to be sho...
Getting Started (jpm) - Archive of obsolete content
. Summary In this tutorial we've built and packaged an add-on using three commands: jpm init to initialize an empty add-on template jpm run to run a new instance of Firefox with the add-on installed, so we can try it out jpm xpi to package the add-on into an XPI file for distribution These are the three main commands you'll use when developing SDK add-ons. There's comprehensive reference documentation covering all the commands you can use and all the options they take. The add-on code itself uses two SDK modules, action button and tabs. There's reference documentation for all the high-level and low-level APIs in the SDK. What's next? To get a feel for some of the things you can do with the SDK APIs, try working through some of the tutorials. ...
Open a Web Page - Archive of obsolete content
ou don't get direct access to any content hosted in the tab. To access tab content you need to attach a script to the tab using tab.attach(). This add-on loads a page, then attaches a script to the page which adds a red border to it: var tabs = require("sdk/tabs"); tabs.open({ url: "http://www.example.com", onReady: runScript }); function runScript(tab) { tab.attach({ contentScript: "document.body.style.border = '5px solid red';" }); } Learning More To learn more about working with tabs in the SDK, see the tabs API reference. To learn more about running scripts in tabs, see the tutorial on using tab.attach(). ...
Add-on SDK - Archive of obsolete content
ox compatibility. Content scripts A detailed guide to working with content scripts. SDK idioms The SDK's event framework and the distinction between add-on scripts and content scripts. XUL migration A guide to porting XUL add-ons to the SDK. This guide includes a comparison of the two toolsets and a working example of porting a XUL add-on. Reference High-Level APIs Reference documentation for the high-level SDK APIs. Tools reference Reference documentation for the jpm tool used to develop, test and package add-ons, the console global used for logging, and the package.json file. Low-Level APIs Reference documentation for the low-level SDK APIs. ...
Cookies - Archive of obsolete content
kie.name + "=" + cookie.value + "\n"); } All cookies, regardless of host, can be enumerated using Services.cookies.enumerator rather than getCookiesFromHost(). Setting a cookie The following code demonstrates how to set a cookie in Firefox. Services.cookies.add(".host.example.com", "/cookie-path", "cookie_name", "cookie_value", is_secure, is_http_only, is_session, expiry_date); See also document.cookie nsICookie nsICookie2 nsICookieService nsICookieManager nsICookieManager2 HTTP cookies ...
Finding window handles - Archive of obsolete content
pes.open(ctypes.libraryName('objc')); // types let id = ctypes.voidptr_t; let SEL = ctypes.voidptr_t; // constants let nil = ctypes.voidptr_t(0); //common functions let sel_registerName = objc.declare('sel_registerName', ctypes.default_abi, SEL, ctypes.char.ptr); let objc_msgSend = objc.declare('objc_msgSend', ctypes.default_abi, id, id, SEL, '...'); /* https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSApplication_Class/index.html#//apple_ref/occ/instp/NSApplication/orderFront: * [NSWindowPtr orderFront:nil] */ var orderFront = sel_registerName('orderFront:'); var NSWindowPtr = ctypes.voidptr_t(ctypes.UInt64(NSWindowString)); var rez_orderFront = objc_msgSend(NSWindowPtr, orderFront, nil); console.log('rez_orderFront:', rez_orderFront, rez_ord...
Examples and demos from articles - Archive of obsolete content
Capture the digitation of a hidden word This example shows the use of the onkeypress event during a digitation into a form field. AJAX - Submitting forms and uploading files This paragraph shows how to submit forms in pure-AJAX. Multipage AJAX navigation example This article provides a working (minimalist) example of a pure-AJAX web site composed only of three pages. 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 Aime...
IsDefaultNamespace - Archive of obsolete content
{ return att.value === namespaceURI; } } } if (node.parentNode) { // EntityReferences may have to be skipped to get to it return isDefaultNamespace(node.parentNode, namespaceURI); } else { return false; // unknown; } case 9: // DOCUMENT_NODE return isDefaultNamespace(node.documentElement, namespaceURI); case 6: // ENTITY_NODE case 12: // NOTATION_NODE case 10: // DOCUMENT_TYPE_NODE case 11: // DOCUMENT_FRAGMENT_NODE return false; // unknown case 2: // ATTRIBUTE_NODE: if (node.ownerElement ) { return isDefaultNamespace(node.ownerElement , ...
Page Loading - Archive of obsolete content
Post data to window Code to post data to an existing or new window/tab ...
JavaScript timers - Archive of obsolete content
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. The requestAnimationFrame() function tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame. Documentation setTimeout() Calls a function or executes a code snippet after specified delay. setInterval() Calls a function or executes a code snippet repeatedly, with a fixed time delay between 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 setTi...
Windows - Archive of obsolete content
dowUtils attribute currentInnerWindowID: var util = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(Components.interfaces.nsIDOMWindowUtils); var windowID = util.currentInnerWindowID; Programatically modifying HTML When attempting to modify HTML elements, it is important to specify the namespace. For example, the following code will add a horizontal rule. var hr = document.createElementNS("http://www.w3.org/1999/xhtml", "html:hr"); document.getElementById("id1").appendChild(hr); ...
XML-related code snippets - Archive of obsolete content
E4X ...
Default Preferences - Archive of obsolete content
...
Enhanced Extension Installation - Archive of obsolete content
a single extension at different Install Locations due to the singleton nature of RDF resources. Extension metadata is structured and not relational in the sense encouraged by RDF, and so a simple text storage format is probably desirable. Making the database file format human readable would also help developers debug their installation problems. Footnotes The term "Extension" is used in this document to imply any item managed by the Extension Manager, including themes. The term "Firefox" is used in this document to imply any application built on XULRunner that uses the Extension System. Original Document Information Author(s): Ben Goodger Last Updated Date: April 18, 2005 Copyright Information: Copyright (C) Ben Goodger ...
Extension Versioning, Update and Compatibility - Archive of obsolete content
pdate Manifests If you wish to serve your update RDF over regular http, Gecko 1.9 based applications will require that you digitally sign the update manifest to ensure that it's information isn't tampered with between you creating it and applications retrieving it. The McCoy tool should be used to sign the update RDF. The technical details of the signing mechanism are beyond the scope of this document however the basics are as follows: Step 1 - Done once, before you publish your add-on The target: Adding updateKey in install.rdf The add-on author creates a public/private RSA cryptographic key pair. The public part of the key is DER encoded and then base 64 encoded and added to the add-on's install.rdf as an updateKey entry. Step 2 - Done every time you change your "update.rdf" file The t...
Hotfix Extension - Archive of obsolete content
This document has been moved to the Add-ons wiki. ...
Install Manifests - Archive of obsolete content
optionsType The type of user-interface used for displaying the options. Accepted values are: 1 Opens optionsURL in a dialog box 2 Options are displayed inside the Add-on Manager 3 Opens optionsURL in a new tab (if the application supports that), or a dialog box optionsType defaults to 1 if there ...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
iscovered this, not a call to install, there will be no notification to the user. ...
Legacy Add-ons - Archive of obsolete content
This section contains links to documentation for legacy technology for add-on development, including: Add-on SDK Legacy extensions for Firefox for Android Earlier technology Bootstrapped extensions Overlay extensions ...
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
Strings The most obvious change required by frozen linkage is using the frozen string API. ...
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
on icons Creating the icons for toolbar buttons is one of the most difficult tasks when making extensions. It is not too hard to come up with some graphics for the buttons, but it can be hard to make them blend in with Firefox on all operating systems. The way icons are handled in Firefox changed considerably after Firefox 4, so supporting older versions is not mentioned here (you can check this document's change history for older revisions, though). These are the current icon sets for Firefox: Windows Mac OS X (Lion and above) Mac OS X Linux (Gnome) Note: the images above are probably not distributable under the same CC license, unlike the rest of this material. Here are the key similarities and differences between the 3 themes: All systems use small icons that are 16x16 pi...
Adding menus and submenus - Archive of obsolete content
this with a menubar. The menubar element should be a child of a toolbox element because it is treated like another toolbar on systems other than Mac OS X. Mac OS X treats menus in a very different way than other systems. If your extension involves menus in any way, you should test it on Mac OS X to make sure everything works adequately. ...
Handling Preferences - Archive of obsolete content
d first create a JS preferences file that describes the preferences and their default values, although setting defaults is not required. As mentioned earlier, a preference with no default value can be set later on. Note: We recommend that you include all of your extension preferences in the JS defaults file. It makes it easier to compile a list of the preferences your extensions handle, and to document what they do. The preferences file you need to create should be defaults/preferences/yourextensionname.js, under your extension root. The naming of the JS file is not compulsory, but it is the standard most extensions use. Note: The purpose of the defaults directory is to hold non-code files your extension needs. In the past we have used this directory to store XSLT files for XML transforma...
Introduction - Archive of obsolete content
utorial you'll learn how to develop Firefox extensions. You'll learn how to quickly do the most common tasks in extension development, comparing several different approaches to solve them. In most cases we'll provide code samples that you can easily copy and adapt to your needs, as well as some working example extensions. The tutorial aims to be as brief as possible, often falling back on Mozilla documentation for more detailed information. You can think of it as a quick guide to the expansive world that is the Mozilla platform. Most links in this documentation are meant to be clicked and read. We'll start with a brief introduction to some key concepts, in case you're not familiar with Mozilla and Firefox. Mozilla and Firefox The term Mozilla can be used to refer to several concepts: the Mozill...
Local Storage - Archive of obsolete content
ke in the install.rdf file. It is being phased out, with SQLite taking its place in most cases. The RDF API may be removed at some point in the future because it requires a great deal of code even for the simplest tasks, and it currently sees little maintenance, so we don't recommend using it unless you really have to. You'll still need to understand at least a little about RDF when you read the documentation about templates. Templates Templates are a very powerful tool in Firefox. They allow you to automatically generate XUL content using information from a datasource, and automatically update the content once the datasource changes. They were designed with RDF datasources in mind, but since Firefox 3 they have been extended to support SQLite datasources as well. Handling templates can also b...
Setting Up a Development Environment - Archive of obsolete content
be very useful for add-on development and overlap with 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 ...
XUL School Tutorial - Archive of obsolete content
The project is now pub...
Overlay extensions - Archive of obsolete 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. ...
Performance best practices in extensions - Archive of obsolete content
elector 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 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 us...
Adding preferences to an extension - Archive of obsolete content
freshInformation: function() { // Because we may be called as a callback, we can't rely on // "this" referring to the right object, so we need to reference // it by its full name var symbol = StockWatcher.tickerSymbol; var fullUrl = "http://quote.yahoo.com/d/quotes.csv?f=sl1d1t1c1ohgv&e=.csv&s=" + symbol; function infoReceived() { var samplePanel = document.getElementById('stockwatcher2'); var output = httpRequest.responseText; if (output.length) { // Remove any whitespace from the end of the string output = output.replace(/\W*$/, ""); // Build the tooltip string var fieldArray = output.split(","); samplePanel.label = symbol + ": " + fieldArray[1]; samplePanel.tooltipText = "Chg: ...
Underscores in class and ID Names - Archive of obsolete content
ames. A common substitute is the hyphen character (-), as in: p.urgent-note {color: maroon;} Many authors choose instead to use Camel Case names such as this: p.urgentNote {color: maroon;} If the initial-cap approach is used, however, remember that class and ID names are also supposed to be case-sensitive. See the tech note "Case Sensitivity in class and id Names" for more details. Original Document Information Author(s): Eric A. Meyer, Netscape Communications Last Updated Date: Published 05 Mar 2001 Copyright Information: Copyright (C) 2001-2003 Netscape. All rights reserved. Note: This reprinted article was originally part of the DevEdge site. ...
Creating a status bar extension - Archive of obsolete content
owser/content/browser.xul chrome://status-bar-sample-1/content/status-bar-sample-1.xul The first line registers the location on disk of the contents of the extension whose ID is "status-bar-sample-1". This path is relative to the extension's root folder in this case, but can be absolute if you want it to be. The second line registers an overlay. An overlay lets you add new content to an existing document. In this case, we want to augment the UI of the Firefox browser, so we specify the URI of the Firefox main window's XUL file, "chrome://browser/content/browser.xul", as the interface to overlay onto, and the URI of our own XUL file, "chrome://status-bar-sample-1/content/status-bar-sample-1.xul", as the interface to overlay onto the browser. See XUL Overlays for details on how overlays work. You c...
Getting the page URL in NPAPI plugin - Archive of obsolete content
offs: NPAPI only Probably works in all browsers, all versions Is sort of backwards (?) Advantages / disadvantages ? Via DOM From Benjamin Smedberg: The NPAPI gives you the ability to get access to the nsIDOMWindow object which contains the current plugin via the NPNVDOMElement enum passed to NPN_GetValue. This returns an addrefed nsIDOMElement interface pointer from which you can call .ownerDocument (on nsIDOMNode), QueryInterface that object to nsIDOM3Document, and call .documentURI. Tradeoffs: is inherently incompatible with other non-Mozilla browsers (i.e. does not work in Opera, Safari etc.) compatible with older versions of the Mozilla (probably back to Mozilla 1.0) requires C++ ...
Creating a Web based tone generator - Archive of obsolete content
// no sound selected } var k = 2* Math.PI * frequency / sampleRate; for (var i=0, size=soundData.length; i<size; i++) { soundData[i] = Math.sin(k * currentSoundSample++); } } var audioDestination = new AudioDataDestination(sampleRate, requestSoundData); function start() { currentSoundSample = 0; frequency = parseFloat(document.getElementById("freq").value); } function stop() { frequency = 0; } </script> </body> </html> ...
Working with BFCache - Archive of obsolete content
rward cache. For more info about this, read how to use Firefox caching. Q: When a user clicks a link that replaces the view in the current tab with a new page, what is the fate of the nsIDOMWindow supporting the view they click on? Or: what happens when they hit the 'back' button? A: The outer nsIDOMWindow (the |window| object in content JS, aka the <browser>'s contentWindow object in the parent document) stays right where it is. It just has its inner window and document replaced. The inner nsIDOMWindow (the global scope object in content JS) is either thrown away when GC happens, or frozen and placed in the bfcache. When the user hits the 'back' button, either the window in bfcache is thawed or a new inner window is created, depending on whether there's a window in the bfcache. Q: Is the page re...
Misc top level - Archive of obsolete content
the classic "convoluted tables and lots of images" paradigm. Whether you've sliced up a logo so it fits in well with the design, or used tons of single-pixel spacer GIFs, the principles (and perils) remain largely the same. Back in the early days, this approach worked, because browsers would usually make a table cell exactly as wide and tall as an image it contained.No Proxy For configurationThis document provides a comprehensive discussion of the manual proxy feature "No Proxy for:", including configuration issues, testing and bugs.Same-origin policy for file: URIsIn Gecko 1.8 or earlier, any two file: URIs are considered to be same-origin. In other words, any HTML file on your local disk can read any other file on your local disk. ...
Automatically Handle Failed Asserts in Debug Builds - Archive of obsolete content
la.org\windbgdlg. At the first match, it will take the action specified by the DWORD's value. The valid values are: 0x5 Automatically ignore 0x4 Automatically retry 0x3 Automatically abort Note that you can also force windbgdlg to prompt, by setting a value of 0xfffffffe. To "comment out" a value, set its value to 0xffffffff. As an example, consider the following failed assertion: ASSERTION: no document: 'mDocument != nsnull', file d:/cvs-1.11.4/mozilla/content/xul/content/src/nsXULElement.cpp, line 3173 (note that I have my source tree in d:/cvs-1.11.4/mozilla) If you have a DWORD in HKCU\Software\mozilla.org\windbgdlg\ named "d:/cvs-1.11.5/mozilla/content/xul/content/src/nsXULElement.cpp," (WITH the comma - matches are whole-word only) and value 0x5, the assert would automatically be ignored. ...
Bonsai - Archive of obsolete content
e mozilla/cmd/xfe/forms.c That's a small sample, but it should be enough to get you started. Play around with the various options on the main Bonsai Query page. If you're updating our cvs tree you'll need to learn about Hacking with Bonsai. Bonsai Source Code The source code to the Bonsai tool itself is also available, check out the information available at the Bonsai project page. Original Document Information Author(s): Jamie Zawinski Last Updated Date: September 8, 2004 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Bookmark Keywords - Archive of obsolete content
g Dictionary Search dictionary, dict, define, word Thesaurus Search thesaurus, like FedEx Tracking fedex UPS Tracking ups Of course, these are just a beginning. Any Web site that you commonly search is a candidate for its own keymark. Acknowledgements Thanks to Asa Dotzler and his article How Cool are Custom Keywords?, which provided the inspiration to write this article. Original Document Information Author(s): Eric A. Meyer, Netscape Communications Last Updated Date: Published 15 Mar 2002 Copyright Information: Copyright (C) 2001-2003 Netscape. All rights reserved. Note: This reprinted article was originally part of the DevEdge site. ...
Adding the structure - Archive of obsolete content
anel class="statusbarpanel-iconic" id="offline-status"/> <statusbarpanel class="statusbarpanel-iconic" id="security-button" onclick="BrowserPageInfo(null, 'securityTab')"/> </statusbar> The statusbar XUL element defines a horizontal status bar where informative messages about an application's state can be displayed. It can contain both text messages (i.e. "Done" in Mozilla when a document finishes loading) and graphical messages (f.e. the lock icon in Mozilla that shows whether or not a loaded document was encrypted with SSL). Status bars comprise a series of panels, each one defined by a statusbarpanel XUL element. Each status bar panel displays a different kind of status information. Graphical panels (like the one we are creating here that displays an icon) are given the status...
Enabling the behavior - updating the status bar panel - Archive of obsolete content
In order for loadTinderboxStatus() to have any effect we need to define a matching updateTinderboxStatus() function. function updateTinderboxStatus() { var icon = document.getElementById('tinderbox-status'); if (gXMLHttpRequest.responseText.match("EE0000")) icon.setAttribute("status", "busted"); else if (gXMLHttpRequest.responseText.match("FFAA00")) icon.setAttribute("status", "testfailed"); else if (gXMLHttpRequest.responseText.match("11DD11")) icon.setAttribute("status", "success"); else icon.setAttribute("status", ""); } updateTinderboxStatus() retrieves a reference to the statusbarpanel element then searches through the retrieved HTML document (stored in the responseText property of the XMLHttpRequest instance) for one of several color references. The color red (...
Finding the code to modify - Archive of obsolete content
When you select a node in the tree, a red border flashes for several seconds around the visual representation of that node in the browser window. Scroll down the tree to the statusbar node and select it. Notice the flashing red border around the horizontal status bar at the bottom of the browser window. ...
Making it into a static overlay - Archive of obsolete content
he default Mozilla distribution) and to package it into an installer that users can run from within Mozilla to add the extension to their Mozilla installation. Most extensions are distributed as installer packages, 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 Mozi...
Creating a hybrid CD - Archive of obsolete content
...
Creating a Release Tag - Archive of obsolete content
each of the build scripts find the variables defining the branch and change it from the branch you originally pulled from to the new tag you are creating. mozilla/client.mk Check the build scripts back in to the mini-branch. cvs ci mozilla/client.mk Create the tag. find . -type d \! -name CVS | xargs -l -P10 cvs tag -l MOZILLA_0_9_4_1_RELEASE >& ../taglog Original Document Information Author(s): Dawn Endico Last Updated Date: November 1, 2005 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Creating a Skin for Mozilla - Archive of obsolete content
What is a skin? A skin does not totally change the interface, it just defines how it looks. You cannot change what happens when the user right clicks on an image, but you can change the look of the right click menu (Make it blue with pink polka dots, for example). If you want to change the functionality of Mozilla, you'll have to look into modifying the chrome. That is beyond the scope of this document. Contents Getting Started Setup Changing Borders and Colours Changing Images Creating the Install Script In-Depth System Colours Mozilla CSS Commands How do I know what to Modify? Organizing Images Adding an image to the right of a toolbar Jar File Installer Utility (provided by Neil Marshall) Frequently Asked Questions Links Original Documen...
Creating regular expressions for a microsummary generator - Archive of obsolete content
mary generators use them to identify the pages that 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...
Dehydra - Archive of obsolete content
ried 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 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 ques...
Devmo 1.0 Launch Roadmap - Archive of obsolete content
Comments, ideas, questions and other discussion should be added on the Devmo talk:1.0 Launch Roadmap page. Further details on smaller tasks being done are available at User:Dria:TODO page. See also Current Events. Design Document Items Things that need to happen prior to a Devmo 1.0 Launch... Timeline Currently undetermined. ...
Download Manager improvements in Firefox 3 - Archive of obsolete content
ese files may currently be queued for download, actively being downloaded, or finished being downloaded. nsIDownloadProgressListener Applications and extensions implement this interface to be made aware of changes in the status of downloads. nsIDownloadManagerUI Implement this interface to replace or augment the Download Manager user interface. Other Download Manager documentation Download Manager preferences This article lists preferences used by the Download Manager as well as their default values. The Download Manager schema This article describes the database format used to store and track information about each download. Examples Monitoring downloads An example showing how to use the new Download Manager APIs to creat...
Download Manager preferences - Archive of obsolete content
Description browser.download.antivirus.dontclean Note: in Gecko 1.9.1. A boolean value that indicates whether the anti virus software should try to clean a downloaded file when a virus is detected. Default value is false. browser.download.manager.addToRecentDocs A boolean value that indicates whether or not new downloads should be added to the recent documents list. Default value is true. browser.download.manager.alertOnEXEOpen A boolean value that indicates whether the UI Should alert the user about the dangers of opening (executing) an EXE. The user may check a "don't ask" box on the UI to toggle this. Default value is true. browser.download.manager.closeWhenDone A boolean value indicating whether or not the Downloads...
Drag and drop events - Archive of obsolete content
determine when drag operations begin and end. These events are new in the current working draft of the HTML 5 specification. Note: The drag and drop event support advertised in the Firefox 3 release notes is not the same as the events described in the Drag and drop section of the HTML 5 working draft. E.g. Firefox 3 does not support the 'drag' event. This support is added in Firefox 3.5, and is documented separately on the page [Drag and Drop]. drag Sent when a drag operation begins. dragend Sent when a drag operation ends. For more information about drag and drop, see the article Drag and Drop. You can see an example of these events in action here: View source View example See also ^: Drag and Drop HTML 5 working draft: Drag and drop nsIDragService ...
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
roxy for the nsIWindowWatcher instance we created above. ...
External CVS snapshots in mozilla-central - Archive of obsolete content
...
Building Firefox with Rust code - Archive of obsolete content
Adding Rust code We generally target stable Rust, but sometimes issues temporarily require a beta or custom toolchain build. Our goal is to always ship a Firefox release build with a stable Rust toolchain release. If you don't have rust already, use the rustup tool to install it and update as new releases become available, or use the ./mach bootstrap command. ...
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. ...
GRE Registration - Archive of obsolete content
Windows On windows, GRE registration information is kept in the win32 registry under the HKEY_LOCAL_MACHINE/Software/mozilla.org/GRE and HKEY_CURRENT_USER/Software/mozilla.org/GRE keys. ...
GRE - Archive of obsolete content
To understand how GREs are registered, see GRE Registration. The XRE project, which means "XUL Runtime Environment", has been replaced by XULRunner. ...
Gecko Coding Help Wanted - Archive of obsolete content
up performance. It's kind of tedious but it's extremely valuable and will help you learn the way around the codebase. We've done a lot, but there's a lot more to do. roc is willing to work closely with anyone with reasonable C++ experience to get them started on this. Just send him mail. Not up for coding yet? Join the Gecko BugAThon and help save Gecko engineers from imminent doom! Original Document Information Author(s): fantasai Last Updated Date: May 4, 2004 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Help Viewer - Archive of obsolete content
Help Viewer: Allows information to be shown to the user inside Mozilla. Introduction Computers and software are incredibly complex. Naturally, then, everyone needs a little help now and then, and getting that help to the user is critical to making applications useful. Consequently, the Mozilla platform provides a cross-platform help viewer along with a framework for providing built-in help documentation. Mozilla's help viewer makes providing documentation an easy job, and this document will describe how you can use it. Help Viewer Project Page Articles & Tutorials Creating a Help Content Pack task-oriented, as opposed to spec-type stuff like the link below will be Other Resources Content Pack Specification a technical description of it, meant primarily to solidify the idea of e...
Helper Apps (and a bit of Save As) - Archive of obsolete content
o we get. Reworking the helper app dialog to save user choices better. GNOME integration for Unix. Future work Fix the deficiencies in nsIMIMEInfo. Better support for mailcap syntax. Possible KDE integration. Possibly reflecting the OS settings in our helper app preferences (readonly? writable?). Have a way for users to override things in the "not overridable" built-in list. Original Document Information Author(s): Boris Zbarsky Last Updated Date: September 12, 2002 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Hidden prefs - Archive of obsolete content
There is UI for the "mail.collect_email_address_outgoing" pref. See "Edit | Preferences.. | Mail & Newsgroups | Addressing" "other compose header" pref from mailnews.js: // you can specify a comma delimited list of optional headers // this will show up in the address picker in the compose window // examples: "X-Face" or "Approved" pref("mail.compose.other.heade...
Java in Firefox Extensions - Archive of obsolete content
ee 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."). 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 ...
Content - Archive of obsolete content
Note: This page documents the Jetpack Prototype, which is no 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! Page modifications Greasemonkey! Execute callbacks when certain pages are opened SiteBoost Allows a jetpack to empower a domain with extended abilities beyond those native to web pages ...
Extenders - Archive of obsolete content
Note: This page documents the Jetpack Prototype, which is no 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! Manifest Chief mechanism for allowing advanced API use within your jetpack Superpowers Similar to Libraries, Superpowers are for adding deeper platform coupling for your jetpack Sandboxes Safely abstracts library interoperability issues so you don't have to worry about them Future API interface method for including not yet finalized functionality in your jetpack ...
Libraries - Archive of obsolete content
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! Namespace: jetpack.lib Jetpack provides libraries for interacting with Web and other services not part of the Jetpack core. They live in the jetpack.lib namespace. ...
First run - Archive of obsolete content
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! Jetpack lets you specify arbitrary content that will be shown to your users when they install your jetpack. You can also register a callback that will be called after installation. First-run page When users install your jetpack, they will be greeted with a new page notifying them that installation was successful. By default this page contains some simple text explaining that they may now use the jetpack and how to uninstall it. You can replace this text with a page tailored to your jetpack. ...
Enabling Experimental Jetpack Features - Archive of obsolete content
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 proposed method for accessing Jetpack features that are still in development and may be added in the future is inspired by python's future module. In Python, you can call from __future__ import foo which adds the functionality that foo yields to the script. In Jetpack, we propse adding a new function to the base namespace called importFromFuture. Methods import(stringMountPath string)Imports the requested experimental feature into the script. ...
Me - Archive of obsolete content
Archive › Mozilla › Jetpack › Meta › Me
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.me namespace provides mechanisms for introspecting the dynamic state of your jetpack. The namespace currently lives in the future and must be imported before it is used: jetpack.future.import("me"); Methods onFirstRun(funcfunction)jetpack.me.onFirstRun() allows jetpacks to be notified after they are successfully installed. onFirstRun() accepts a callback which is called after installation. ...
Meta - Archive of obsolete content
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! Future Imports experimental new language and API features. Used often. ...
File access - Archive of obsolete content
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! Click on the paper-clip icon below for a demonstration of the file upload dialog. ...
Settings - Archive of obsolete content
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.settings namespace allows jetpacks to specify user-configurable settings. Jetpack will automatically generate a user interface based on the specification. The settings persist across browser sessions and are stored using the Jetpack simple storage API. Settings are private to each jetpack and are not accessible by other jetpacks. ...
Simple Storage - Archive of obsolete content
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. ...
Storage - Archive of obsolete content
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! Simple storage An easy-to-use persistent object data store File access Interface for performing file I/O Settings Settings persist across browser sessions and are accessible to jetpacks via simple object retrieval and assignment. ...
Clipboard - Archive of obsolete content
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! Jetpack's clipboard support API provides a standardized way for features to access the clipboard. Features can get and set the clipboard in various flavors of data type. The namespace associated with this API is jetpack.clipboard which provides both read and write access to the clipboard. The API is fairly straightforward; examples can be found here. The API lives in the future and must be imported for use. jetpack.future.import("clipboard"); Methods set(contentstringflavorstring) stringWrites data from Jetpack to the clipboard. ...
System - Archive of obsolete content
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! Clipboard Interactions with the OS clipboard System information Get information about the platform on which Jetpack is running Visual effects OS-level visual effects abilities Devices Methods for accessing and controlling devices (ex. ...
Notifications - Archive of obsolete content
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 Notification Box appears at the bottom right corner of the browser and displays important information to the user. The namespace for this class is jetpack.notifications. Methods show(titlestring, [body as string] iconstring)Draws a notification box. ...
Panel - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Panel
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! Please refer to the Panels JEP. ...
Selection - Archive of obsolete content
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! Jetpack's selection API provides a method for detecting the selections made by the user. Features can get, set, and listen for selection events in HTML or plain text. The namespace for this api is jetpack.selection. This API currently lives in the future and must be imported for use: jetpack.future.import("selection"); Getting and Setting the Selection The current version of jetpack.selection includes these formats: .text and .html Getting the selection The following is an example of getting the selection from the user. ...
slideBar - Archive of obsolete content
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! slideBar is a reinvention of the old sidebar features of browsers. They allow quick access to a wide range of both temporary and permanent information at the side of your browser window. When a slideBar feature is selected its contents will be revealed from behind the current webpage. It currently under development and lives in the future. ...
Litmus tests - Archive of obsolete content
See http://litmus.mozilla.org. If you're interested in automated testing, see Mozilla automated testing. Smoke Tests There are types of litmus tests. Smoke tests were the first developed. These were developed before litmus, but then pulled in. A "smoke test" is a quick check, done to verify the basic functionality of a certain feature, or a sanity check of the build process. BFTs, or Basic Functionality Tests This set of tests would take longer to run, but will cover an entire release. It may not cover it at much depth, but it does try to cover the major features. ...
Metro browser chrome tests - Archive of obsolete content
an have start up and tear down logic, plus the body of the test contained in run(). The test file can contain other functions which will be ignored unless invoked by test(). gTests make use of Promises and Tasks for managing execution. Test comparison functions used in metro browser chrome tests are identical to those supported by Mochitests, see how the comparison functions work in the Mochitest documentation for more details. Helper functions The EventUtils helper functions are available on the EventUtils object defined in the global scope. Additional metro specific test helpers can be found in /browser/metro/base/tests/mochitest/head.js. You may add additional common utils and helpers to head.js. Be careful about changing existing helpers as changes may impact tests in other libraries. Static c...
Mozilla Application Framework - Archive of obsolete content
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. ...
How to Write and Land Nanojit Patches - Archive of obsolete content
Try to avoid using it. Nanojit was removed during the development of (Firefox 11 / Thunderbird 11 / SeaMonkey 2.8), so this information is relevant to earlier versions of the codebase. Adobe and Mozilla share a copy of Nanojit. This means that landing nanojit patches is a bit complicated, but experience has taught us that this is much better than having separate versions of nanojit. (Note: this document is called NanojitMerge for historical reasons -- Adobe and Mozilla used to have separate copies of Nanojit, but this was a maintenance headache so they were merged. The first version of this document was written just after that merge occurred.) Resources Nanojit development now takes place on a single shared repository nanojit-central. Repository: http://hg.mozilla.org/projects/nanojit-central (...
Build - Archive of obsolete content
To build prism, you must first build the xulrunner tree, and then build prism. Make sure you have the required build prerequisites. Grab the latest release source code from Mozilla's ftp site. Extract the source code, and you should have a directory called mozilla/. Change directory into mozilla/ and checkout the latest prism code : cd mozilla/ svn co http://svn.mozilla.org/projects/webrunner/trunk prism Create a file called .mozconfig make sure it is in the mozilla/ directory. ...
Priority Content - Archive of obsolete content
If you would like to sign up to do the migration of any of these works, just "Edit" this page and add your name to the "Migrators" list for the piece. If there is DevEdge content you think should be migrated that isn't currently on this list, feel free to add it. Note: Use example at Sample:Original Document Information to credit original authors. DevEdge DevEdge Mirror Note: If you're digging around the 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. ...
Proxy UI - Archive of obsolete content
Preferences Panel Overview The UI is based on selecting a proxy mode, then filling out any additional needed information in "related" UI. The "OK" button saves the preferences. The preference changes Selecting the proxy "mode" All product's Proxy preference panels share a basic design: a radio button that selects the proxy mode, then "related proxy mode" UI when needed. For the purposes of this document, "proxy mode" means both: Whatever was selected in the UI (as opposed to the value of the network.proxy.type. The underlying behavior. The currently available modes are based on "network.proxy.type". For example, Firefox 3: [ ] No Proxy [ ] Auto-detect proxy settings for this network [ ] Manual proxy configuration: [ ] Automatic proxy configuration URL: Behavior Default value: "No Proxy" is s...
Reading textual data - Archive of obsolete content
This article describes how to read textual data from streams, files and sockets. In order to read textual data, you need to know which character encoding the data is in. Files and network sockets contain bytes, not characters - to give these bytes a meaning, you need to know the character encoding. XXX: Document nsIUnicharStreamListener (gecko 1.8) XXX: Also document nsIStreamListener here? Determining the character encoding of data If you have a network channel (nsIChannel), you can try the contentCharset property of it. Note that not all channels know the character encoding of the data. You can fallback to the default character encoding stored in preferences (intl.charset.default, a localized pref value) When reading from a file, the question is harder to answer. Using the system ch...
Safe Browsing - Archive of obsolete content
This documentation now lives on the main Mozilla Wiki, see https://wiki.mozilla.org/Safe_Browsing. ...
Safely loading URIs - Archive of obsolete content
one plans to load, and the third argument is a set of flags that can be used to impose additional restrictions on the URIs that may be loaded. It's important to make sure that the first argument to these methods identifies the source of the URI. So if you're implementing a context menu and you add a "View Image" option, the source of the image URI would be the page the image is in, not the chrome document the context menu code is in. Differences between the methods The three methods differ from each other in how the source of the URI is identified and in what is known about the URI to be loaded. In general, the following guidelines apply for Gecko 1.8: If you plan pass a URI string to nsIWebNavigation.loadURI (which can happen indirectly, e.g. by passing the string to something that loads it...
File object - Archive of obsolete content
dard, 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 surgery. Summary Non-Standard Server-Side Object This object lets you work files and directories on the local filesy...
Archived SpiderMonkey docs - Archive of obsolete content
File objectNon-Standard Server-Side ObjectMerging TraceMonkey RepoThese are the steps to merge the TraceMonkey repository to mozilla-central. ...
Standalone XPCOM - Archive of obsolete content
etween standalone XPCOM and the XPCOM that ships with the Mozilla browser. The one functional difference is that XPT files cannot be read from .zip files in standalone XPCOM. TODO for v 1.0 Optional exclusion of specific features into standalone XPCOM like registry, xpconnect. Tweeking these options will cause reduction in memory requirements and size. Get xpcom/tests directory upto date and documented. Update this document for Mac. API freeze and documentation Original Document Information Author: Suresh Duddi Last Updated Date: 15 May 2000 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Static Analysis for Windows Code under Linux - Archive of obsolete content
We highly recommend you to read the cross compiling manual and the Dehydra build manual before you start the following reading. Build GCC Corss-compiler with Plugin Support By default GCC does not support plugins. Dehydra requires patching GCC such that it can load plugins as shared libraries: # Prepare a directory mkdir $HOME/dehydra cd $HOME/dehydra #Obtain GCC 4.3 sources wget ftp://mirrors.kernel.org/gnu/gcc/gcc...-4.3.0.tar.bz2 tar jxvf gcc-4.3.0.tar.bz2 # Get the patches which enable plugins cd gcc-4.3.0/ # Create an hg repository. This makes it easy to apply patches, they can be applied manually hg init . ...
String Quick Reference - Archive of obsolete content
...
Table Cellmap - Border Collapse - Archive of obsolete content
Information storage Each cellmap entry stores for tables in the border collapse mode additional information about its top and left edge and its top left corner. As one can see from the following illustration this is enough to cover a whole table. Only the right most edge and the bottom most edge of a table need to be stored in a different place. Border For the top and left border we store the width and the owner of the border. The width is stored in pixel coordinates. ...
Table Layout Regression Tests - Archive of obsolete content
ditional Notes There is a special type of frame dumps - the printing regression tests, they are invoked by the -Prt command line argument to the viewer and include first a display then a frame dump taking into account the printer pages. Please contact if you need help with running those tests. I would like to thank Chris Karnaze for his guidance and fantasai for her language support. Original Document Information Author(s): Bernd Mielke Other Contributors: Boris Zbarsky Last Updated Date: February 5, 2007 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Table Layout Strategy - Archive of obsolete content
="80%"><tbody></tbody>foobar <col width="40%"><col><tbody></tbody>foobar <table border width="200px"> <col width="40%"><col width="80%"> <tbody> <tr><td>foo</td><td>bar</td></tr> </tbody> </table> The algorithm tries to satisfy the requirements on a first come first serve base. The second table has <col width="40%"><col>. IE and Opera handle this pretty much the same as mozilla. Original Document Information Author(s): Bernd Mielke Last Updated Date: September 27, 2003 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Tamarin Acceptance Test Template - Archive of obsolete content
ms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var SECTION = "test"; // provide a document reference (ie, Actionscript section) var VERSION = "AS3"; // Version of ECMAScript or ActionScript var TITLE = "test"; // Provide ECMA section title or a description var BUGNUMBER = ""; startTest(); // leave this alone /** * Calls to AddTestCase here. AddTestCase is a function that is defined * in shell.as and takes three arguments: * - a string representation o...
Cmdline tests - Archive of obsolete content
The cmdline testsuite is located in test/cmdline. The testsuite allows more flexibility by coding scripts in python allowing any executable to run, sending commands to stdin, and asserting output using regular expressions. See test/cmdline/README document for more information. Two use cases for the cmdline testsuite: Use case 1: test the interactive cmdline debugger Test contents: start avmshell -d test.abc, set breakpoint on a line, show local variable value, quit from cmdutils import * def run(): r=RunTestLib() r.run_test( 'debugger locals', '%s -d testdata/debug.abc'%r.avmrd, input='break 53\ncontinue\nnext\ninfo locals\nnext\ninfo locals\nquit\n', expectedout=['local1 = undefined','local2 = 10','local2 = 15'] ) Use case 2: test -memstats returns ...
Running Tamarin acceptance tests - Archive of obsolete content
/display/flexsdk/Flex+SDK. - Set the ASC environment variable, as described above. - Set the SHELLABC environment variable to the path of the generated/shell_toplevel.abc. adb 'adb' stands for Android Debug Bridge. adb is used to access your android device and can run both direct and shell-type commands. If you've correctly edited and run the android-vars.sh script mentioned on the Tamarin Build Documentation page you should already be pathed to the adb executable in the public sdk/ndk, but if not it exists at /android-public/android-sdk-mac_86/platform-tools. adb supports ssh-like commands to an android device. adb automatically connects to a phone if connected by usb. adb shell "ls /" is a good test to see if connected. The command: $ adb devices lists the device id of each phone. If you have...
Running Tamarin performance tests - Archive of obsolete content
wiki/dis...exsdk/Flex+SDK. - Set the ASC environment variable, as described above. - Set the SHELLABC environment variable to the path of the /generated/shell_toplevel.abc. adb 'adb' stands for Android Debug Bridge. adb is used to access your android device and can run both direct and shell-type commands. If you've correctly edited and run the android-vars.sh script mentioned on the Tamarin Build Documentation page you should already be pathed to the adb executable in the public sdk/ndk, but if not it exists at /android-public/android-sdk-mac_86/platform-tools. adb supports ssh-like commands to an android device. adb automatically connects to a phone if connected by usb. adb shell "ls /" is a good test to see if connected. The command: $ adb devices lists the device id of each phone. If this fails...
Tamarin Roadmap - Archive of obsolete content
Comments or questions are welcome and encouraged via the tamarin-devel mailing list. ...
The Download Manager schema - Archive of obsolete content
URI for the download. target TEXT The destination URI for the download. tempPath TEXT The path of the temporary file being used for the download. startTime INTEGER The download's start time. endTime INTEGER The download's end time. state INTEGER The download's current state. See the constants list in the nsIDownloadManager documentation. referrer TEXT The referrer for the download. entityID TEXT The entity ID from the nsIResumableChannel used to implement the download channel. This information is used to resume the download after it's been paused. currBytes INTEGER The current number of bytes that have been downloaded. Defaults to 0, may not be null. maxBytes INTEGER ...
TraceVis - Archive of obsolete content
TraceVis is a performance visualization system for TraceMonkey. If TraceMonkey is built with TraceVis, and run with TraceVis enabled, then TraceMonkey will output a log of all its activity transitions. The log can be postprocessed into a visualization that can be used to rapidly diagnose many tracing-related performance issues. So far, most of the documentation on TraceVis is contained in the announcement blog post. Prerequisites The visualization scripts require PIL (Python Imaging Library). Building with TraceVis These are the steps to build a JS shell with TraceVis, starting from a Mozilla source directory. These directions create an optimized build, because optimized builds are usually better for performance analysis. cd js/src autoconf213 mkdir opt-tracevis cd opt-tracevis ../configur...
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. For description of node types used in Treehydra see tree.def and cp-tree.def in the GCC sources. ...
Tuning Pageload - Archive of obsolete content
You use the URL about:config or the file prefs.js in your profile to change these. To best understand what the following preferences affect, there are a few things you should know. ...
Using addresses of stack variables with NSPR threads on win16 - Archive of obsolete content
y more likely to cause problems is passing addresses of automatically allocated variables to a function that wends its way though arbitrary amounts of convoluted logic, and finds its way into an object that is shared. ...
[Deprecated] The Mozilla build VM - Archive of obsolete content
Mentored bugs have a mentor who commits to helping you every step of the way. ...
Venkman Internals - Archive of obsolete content
ecord 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 the antecedent files: doc.getElementsByTagName("script"); then extract the URLs from the src attributes. ScriptWrapper newsgroup, 2002, rgrinda Here is a bit more information about how Venkman tracks files and functions... A scriptWrapper is a pure JS object defined only inside Venkman. As you pointed out, there is a 1:1 relationship between scriptWrappers and functions.
Venkman Introduction - Archive of obsolete content
enkman cannot debug extensions, doing so is in fact fully supported; it's just disabled by default. To debug your extension with Venkman (XUL files and their attached JS files), you'll have to load browser and extension files into Venkman by unchecking Debug > Exclude Browser Files. Resources Using Breakpoints in Venkman -- next article about Venkman. Venkman's home page on MDC. Original Document Information Authors: Ian Oeschger, Robert Ginda ...
Using Breakpoints in Venkman - Archive of obsolete content
on code. ...
Video presentations - Archive of obsolete content
o produce video presentations that can help you learn how the Mozilla codebase works and how to take advantage of its technology in your own applications and extensions. This article is a jumping-off point to help you find those presentations. Architecture These presentations provide an architectural overview of the codebase. How pages are built using the DOM This presentation describes how documents are loaded and the DOM tree is constructed. (as QuickTime; 198 MB) Laying out and drawing documents (slides) This presentation describes how a document is laid out and painted to the display by the Gecko engine. (as QuickTime; 282 MB) Community These presentations provide insight into the Mozilla community and how the project works. The Mozilla Community (Part 1, Part 2) This presentati...
Mozilla Web Developer Community - Archive of obsolete content
Get news from developer.mozilla.org and connect with developers involved in cross-browser, standards-based web development. ...
When To Use ifdefs - Archive of obsolete content
ducts, including Firefox, Thunderbird, XULRunner, and many others. Sometimes the same basic code is used for multiple projects, but there are small differences needed. "ifdefs", or conditional instructions, are used to build different code What are ifdefs ifdefs are conditional directives to a text preprocessor which mark that certain blocks of code are used only in certain conditions. In this document, the term is used more loosely to discuss any kind of conditional that differentiates between different build configurations. When are ifdefs used? There are three major kinds of ifdefs in use in the mozilla tree: platform/widget ifdefs, feature ifdefs, and application-specific ifdefs: Platform/widget ifdefs The mozilla code will frequently need to differentiate between code for different p...
Event Handlers - Archive of obsolete content
fire if event.originalTarget is the same as the target to which the handler is attached, and capturing, which indicates the handler should fire during the capturing phase of event flow. XBL event handlers always fire last, after all other event handlers at the same position in the event flow. Since XBL handlers usually constitute the default actions for a widget, this allows authors in the bound document to write events that potentially suppress the default actions taken by the XBL handlers. Within an XBL inheritance chain, event handlers always fire first on the derived binding and then on the base binding in the chain. A derived handler then has a way of preventing the event from flowing to its base binding handlers. Mouse and key handlers have certain additional properties that are supported...
Example Sticky Notes - Archive of obsolete content
ul sometimes. All namespaces above are supported by default and they do not require any additional downloads or initializations. --> <binding id="default"> <!-- A separate binding. You add a binding file using -moz-binding style rule and you address a particular binding by its ID: -moz-binding: url(notes.xml#default) This ID is local within the binding file (not visible in the target document DOM tree). --> <resources> <!-- Obtaining the stylesheet we'll use to (re)style the bound element. --> <stylesheet src="notes.css"/> </resources> <content> <!-- This SVG graphics will be added automatically around each bound element. The position of the original content is indicated by <children/> tag. --> <svg:svg width="60px" height="60px"> <svg:g fill-opacity="0.6" stroke="#FFFFFF...
Mac stub installer - Archive of obsolete content
y install.js. If it finds your module's jst file it will substitute that for the install.js. ...
Unix stub installer - Archive of obsolete content
d a call to generate the xpi at package time by adding a MakeXpiFile("<component>"); call at: <http://lxr.mozilla.org/seamonkey/sou.../makeall.pl#75> You can test it by changing your current working directory to mozilla/xpinstall/packager/unix and running "perl deliver.pl" on the shell prompt. The resulting stub and full installers will be delivered to "mozilla/installer/{stub,sea}". Original Document Information Author(s): Samir Gehani Other Contributors: Curt Patrick Last Updated Date: March 12, 2003 Copyright Information: Copyright (C) Samir Gehani, Curt Patrick ...
Windows stub installer - Archive of obsolete content
array @gComponentList at: <http://lxr.mozilla.org/seamonkey/sou...makeall.pl#125> You can test it by changing your current working directory to mozilla/xpinstall/wizard/windows/builder and running "perl build.pl" on the shell prompt. The resulting stub installer and packages will be delivered to "mozilla/dist/WIN32OBJ_D/installer". Run setup.exe there to launch the stub installer. Original Document Information Author(s): Samir Gehani Other Contributors: Curt Patrick Last Updated Date: March 12, 2003 Copyright Information: Copyright (C) Samir Gehani, Curt Patrick ...
confirm - Archive of obsolete content
n1Title, String aButton2Title, String aCheckMsg, Object aCheckState ); Parameters The second, extended confirm() method is supported starting with Gecko 1.8. It accepts any number of parameters up to 8. Previous Gecko versions only support the first, one-parameter method and will throw an error on occuring the extended form. See the notes at the end of this document for a safe way to implement a fallback. aText The string to be displayed in the confirmation dialog. This string is typically in the form of a prompt for the user (e.g., "Are you sure you want to delete the selected file(s)?"). aDialogTitle The string to be used as the dialog title. Defaults to "Confirm" (or the localized equivalent). aButtonFlags A ...
createKey - Archive of obsolete content
f WinReg object Syntax int createKey ( String subkey, String classname); Parameters The method has the following parameters: subkey The key path to the appropriate location in the key hierarchy, such as "Software\\Netscape\\Navigator\\Mail". classname Usually an empty string. For information on this parameter, see the description of RegCreateKeyEx in your Windows API documentation. Returns 0 if it succeeded; a nonzero number if it failed to schedule the creation. For a list of possible values, see Return Codes. Description The createKey method adds a key to the registry. You must add a key to the registry before you can add a value for that key. ...
WinRegValue - Archive of obsolete content
ta. Returns A new WinRegValue object, with the data members type and data set to the values passed to this constructor. Description Advanced Windows developers can use this object to manipulate non-string values for the Windows Registry. An object of this type has two fields: the type of the data and the value. For information on the possible data types for a registry value, see your Windows API documentation. You supply the value for these fields to the constructor for this class. ...
WinReg Object - Archive of obsolete content
as an extension. WinReg (Windows only) Windows developers use this object to manipulate the content of the Windows registry. Overview This object does not have a public constructor. Instead, you construct an instance of this object by calling the getWinRegistry method of the Install object. This discussion assumes you are already familiar with the Windows Registry. For information on it, see API documentation for Windows NT or Windows 95. When you construct a WinReg object, it is set to operate with HKEY_CLASSES_ROOT as its root key. To use a different root key, use the setRootKey method. Typically values in the Windows Registry are strings. To manipulate such values, use the getValueString and setValueString methods. To manipulate other values, use the getValue and setValue methods. Reading regi...
XPInstall - Archive of obsolete content
</RDF> Cross-Platform Install (XPInstall) is a technology used by Mozilla Application Suite, Mozilla Firefox, Mozilla Thunderbird and other XUL-based applications for installing extensions. An XPI (pronounced "zippy" and derived from XPInstall) installer module is a ZIP file that contains an install script or manifest (entitled install.js or install.rdf) at the root of the file. Documentation XPInstall API Reference XPInstall API Reference. Learn XPI Installer Scripting by Example This article uses the installer script from browser.xpi install package as the basis for discussing XPI installations in general. Creating XPI Installer Modules This article describes the packaging scheme of the Mozilla and offers a tutorial for creating a new package...
Mozilla E4X - Archive of obsolete content
(ECMA-357), a new standard for writing and processing XML directly in JavaScript (ECMA-262, ISO-16262). E4X marries XML and JavaScript syntax, and extends JavaScript to include namespaces, qualified names, and XML elements and lists. E4X also adds new JavaScript operators for filtering XML lists, and for enumerating XML children and descendants. Another E4X feature: the ability to bind a W3C DOM document to a new XML object, reflecting the DOM in E4X terms so that updates to either the DOM or the E4X object hierarchy show up in the other. Questions and Discussion Mozilla E4X - Discussion ...
XTech 2005 Presentations - Archive of obsolete content
(ECMA-357), a new standard for writing and processing XML directly in JavaScript (ECMA-262, ISO-16262). E4X marries XML and JavaScript syntax, and extends JavaScript to include namespaces, qualified names, and XML elements and lists. E4X also adds new JavaScript operators for filtering XML lists, and for enumerating XML children and descendants. Another E4X feature: the ability to bind a W3C DOM document to a new XML object, reflecting the DOM in E4X terms so that updates to either the DOM or the E4X object hierarchy show up in the other. Directions of the Mozilla RDF engine: website scripting, standards conformance and perfomance - Axel Hecht This presentation showed new developments in the Mozilla RDF engine. These include plans to expose the RDF API to public web content, as well as perfo...
XTech 2006 Presentations - Archive of obsolete content
-to-JS compiler is being developed, making JS2 a reality in 2006. Work on this compiler and the new features of JS2 is presented by the inventor of JavaScript. Layout Algorithm Improvements for Web User Interfaces (slides, slides as one page) - David Baron A discussion of problems with existing standards and potential improvements in two areas: layout systems for user interfaces (rather than documents) and mechanisms for reordering content to allow the author to use good markup and appropriate layout. Microsummaries in Firefox and on the Web - Myk Melez Microsummaries are regularly-updated compilations of the most important and timely information on web pages. This talk demonstrates how Firefox will incorporate microsummaries into its UI, starting with bookmark labels. SVG and Canvas...
disabled - Archive of obsolete content
form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. // Disabling an element document.getElementById('buttonRemove').setAttribute("disabled", "disabled"); // Enabling back an element by removing the "disabled" attribute document.getElementById('buttonRemove').removeAttribute("disabled"); Firefox 3.5 note For keyset elements, support for this attribute was added in Firefox 3.5. ...
disablefastfind - Archive of obsolete content
<< XUL Reference homedisablefastfindType: booleanPut disablefastfind="true" on the root element of a XUL document, which is intended to be loaded in a tab, to disable the find bar for the tab with this document. This is used to prevent the find bar from being displayed when it's not supported by the content (such as in the Add-ons manager tab). ...
editortype - Archive of obsolete content
<< XUL Reference home editortype Type: one of the values below The type of editor to use. This value will be overridden depending on the content type of the document in the editor. html An HTML editor. text A plaintext editor. ...
eventnode - Archive of obsolete content
t specified, events are listened to from the tabbox. Thus, if this attribute is not used, the tabbox or an element inside it must have the focus for the keyboard navigation to apply. parent Keyboard navigation is captured at the parent of the tabbox. window Keyboard navigation is captured at the window level. Tab navigation will occur as long as any element in the window is focused. document Keyboard navigation is captured at the document level. Tab navigation will occur as long as any element in the document is focused. ...
onchange - Archive of obsolete content
ed in different ways for different XUL Input Elements as listed below: onchange Type: script code TextBox When Enter key is pressed Radio/Check Box When the state is changed Select List When the selected item is changed What is accessible The script context at this point can only access the following things: Global Values/Functions i.e. ...
oninput - Archive of obsolete content
<< XUL Reference home 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 user presses non-displayable keys. Example <!-- This sets the label's text to the textbox value on each keystroke. --> <script language="javascript"> function setLabel(txtBox){ document.getElementById('lbl').value = txtBox.value; } </script> <label id="lbl"/> <textbox oninput="setLabel(this);"/> This is similar to the onkeypress event used in HTML documents. ...
persist - Archive of obsolete content
<< XUL Reference home persist Type: space-separated list of attribute names A space-separated list of attributes that are maintained when the window is closed. When the window is re-opened, the values of persistent attributes are restored. In Mozilla, persistent attributes are stored in the per-profile file xulstore.json. Persistence can also be stored using the document.persist function. In order for persistence to work, the element must also have an id. Persistence will not remember the absence of an attribute, so for boolean attributes like checked where absence means false, you will need to explicitly set the attribute to false before the window closes (bug 15232). ...
preference-editable - Archive of obsolete content
...
reserved - Archive of obsolete content
even though it can't override them. In future releases, it won't receive them. See bug 1173061 for details. ...
statustext - Archive of obsolete content
nect" statustext="Connect to remote server" onmouseover="setStatusMessage(this)" onmouseout="clearStatusMessage()"/> <button label="Ping" statustext="Ping the server" onmouseover="setStatusMessage(this)" onmouseout="clearStatusMessage()"/> <statusbar> <statusbarpanel id="myStatusPanel" label="" flex="1"/> <spacer flex="1"/> </statusbar> <script> function setStatusMessage(obj){ document.getElementById('myStatusPanel').label = obj.getAttribute('statustext'); } function clearStatusMessage(obj){ document.getElementById('myStatusPanel').label = ''; } </script> See also statusbar and statusbarpanel ...
textbox.type - Archive of obsolete content
<< XUL Reference home type Type: one of the values below You can set the type attribute to one of the values below for a more specialized type of textbox. Don't set the type if you wish to use a regular textbox. autocomplete A textbox that supports autocomplete. For more information about autocomplete textboxes, see the autocomplete documentation (XPFE [Thunderbird/SeaMonkey]) (Firefox) number A textbox that only allows the user to enter numbers. In addition, arrow buttons appear next to the textbox to let the user step through values. There are several attributes that allow the number textbox to be configured, including decimalplaces, min, max, increment, wraparound, hidespinbuttons, and textbox.value. password A textbox that hides what is typed, used for entering pa...
command - Archive of obsolete content
Archive › Mozilla › XUL › Events › command
Type Description target Read only EventTarget The event target (the topmost target in the DOM tree). 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? view Read only WindowProxy document.defaultView (window of the document) detail Read only long (float) Unused; always zero. sourceEvent Read only Event The activation event that caused this command event to be generated. Currently only set when a command event is redirected though use of the command attribute. ctrlKey Read only boolean true if the control key was down when the event w...
Accessing Files - Archive of obsolete content
g and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. Accessing Files This section describes how to create a file reference. Retrieving a File When working with files, usage is always done via a File object and not via string paths. This allows files to use...
Working With Directories - Archive of obsolete content
g and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. A reference to a directory may be created in the same way as with a file by using nsIScriptableIO.getFile(). You can access a subdirectory by supplying a directory name as the second argument, or refer t...
Getting File Information - Archive of obsolete content
g and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. The nsIFile object has a number of useful attributes which may be used to retrieve information about a file. Two useful attributes fileSize and lastModifiedTime (nsIFile.Attributes) provide a means of r...
Reading from Files - Archive of obsolete content
g and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. Reading data from a file involves getting a reference to a file and then creating an input stream to read from it. An input stream provides a means of reading bytes, strings or other values from the file...
Uploading and Downloading Files - Archive of obsolete content
g and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. The IO object and stream objects can be used to upload files to servers in various ways. The exact method depends on the type of upload that you wish to perform. HTTP File Upload Some web sites allow ...
Writing to Files - Archive of obsolete content
g and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. To write to a file, an output stream is used. An output stream is an object which can be used to write bytes, strings and other values to a file. To create an output stream, use nsIScriptableIO.newOutpu...
IO - Archive of obsolete content
Archive › Mozilla › XUL › FileGuide › IO
g and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. Files and Streams This section describes how to access and get information about files, read from files and create and write files. Using Files A XUL application or extension may access files on disk, an...
Moving, Copying and Deleting Files - Archive of obsolete content
g and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. There are several methods of the nsIFile object which may be used to move and copy files on disk. nsIFile.copyTo() is used to copy a file, while nsIFile.moveTo() is used to move files. nsIFile.remove() ...
TOC - Archive of obsolete content
Archive › Mozilla › XUL › FileGuide › TOC
...
findbar - Archive of obsolete content
ltipText, top, width browser Type: browser element Lets you set and get the browser in which the findbar is located. findMode Type: integer Read only. The find mode in use. ...
List of commands - Archive of obsolete content
nks cmd_findTypeText cmd_goToLine cmd_handleBackspace cmd_handleShiftBackspace cmd_minimizeWindow cmd_newEditor cmd_newEditorDraft cmd_newEditorTemplate cmd_newNavigator cmd_newNavigatorTab cmd_newTabWithTarget cmd_openHelp cmd_paste - paste a selection from the clipboard cmd_printSetup cmd_quit cmd_redo cmd_savePage cmd_scrollPageDown cmd_scrollPageUp cmd_selectAll cmd_SwitchDocumentDirection cmd_switchTextDirection cmd_textZoomEnlarge cmd_textZoomReduce cmd_textZoomReset cmd_undo cmd_viewcomponentbar cmd_viewlinktoolbar cmd_viewlinktoolbar_false cmd_viewlinktoolbar_maybe cmd_viewlinktoolbar_true cmd_viewnavbar cmd_viewpersonaltoolbar cmd_viewtaskbar cmd_zoomWindow Thanks for help of joe.user0 in compiling: http://readlist.com/lists/mozilla.or...l/3/15261.html...
addTabsProgressListener - Archive of obsolete content
<< XUL Reference home addTabsProgressListener( listener ) Return type: no return value Add a progress listener to the browser which will monitor loaded documents in all tabs in the tabbed browser. The progress listener should be based on the nsIWebProgressListener interface with an additional "browser" argument as the first argument of every method, which is the browser (not <tabbrowser> = gBrowser) where the event occurred. See Listening to events on all tabs for details. ...
addProgressListener - Archive of obsolete content
The progress listener should implement the nsIWebProgressListener interface. ...
appendGroup - Archive of obsolete content
<< XUL Reference home appendGroup( group ) Return type: no return value Not in Firefox Add several new tabs to the end of the existing tabs. The argument should be an array of objects, one for each document to load. The objects may be defined in script and contain a URI property for the URL of the page to load. A referrerURI property may also be optionally used to set the referrer page. ...
appendItem - Archive of obsolete content
<< XUL Reference home appendItem( label, value ) Return type: element Creates a new item and adds it to the end of the existing list of items. You may optionally set a value. The function returns the newly created element. ...
appendNotification - Archive of obsolete content
Reference home appendNotification( label , value , image , priority , buttons, eventCallback ) Return type: element Create a new notification and display it. If another notification is already present with a higher priority, the new notification will be added behind it. label - label to appear on the notification. This should be either a string, or, from Gecko 37 onwards, you can pass a DocumentFragment with rich content as well. Keep in mind that this is all XUL so using HTML elements for 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. but...
getEditor - Archive of obsolete content
Pass the editor's contentWindow as the argument. ...
getHTMLEditor - Archive of obsolete content
Pass the editor's contentWindow as the argument. ...
insertItemAt - Archive of obsolete content
. You may optionally set a value. The new item element is returned. ...
loadGroup - Archive of obsolete content
<< XUL Reference home loadGroup( group ) Not in Firefox Return type: the first tab Loads a group of pages into multiple tabs. They are either appended or replaced depending on the state of the preference browser.tabs.loadGroup. The argument should be an array of objects, one for each document to load. The objects may be defined in script and contain a URI property for the URL of the page to load. A referrerURI property may also be optionally used to set the referrer page. This function returns a reference to the first tab loaded. ...
loadURI - Archive of obsolete content
Archive › Mozilla › XUL › Method › loadURI
<< XUL Reference home NOTE: This is the XUL method on <browser> / <tabbrowser>, not the global function in chrome://browser/content/browser.js. Please check which one you're documenting! (This one has no post data parameter, see loadURIWithFlags for a version that does) loadURI( uri, referrer, charset ) Return type: no return value Load a URL into the document, with the given referrer and character set. The first argument should be a string, not a nsIURI object. To get a string from an nsIURI, use nsIURI.spec or nsIURI.asciiSpec ...
loadURIWithFlags - Archive of obsolete content
In addition to the flags allowed for the reloadWithFlags method, the following flags are also valid: LOAD_FLAGS_IS_REFRESH: This flag is used when the URL is loaded because of a meta tag refresh or redirect. LOAD_FLAGS_IS_LINK: This flag is used when the URL is loaded because a user clicked on a link. The HTTP Referer header is set accordingly. LOAD_FLAGS_BYPASS_HISTORY: Do not add the URL to the session history. ...
reload - Archive of obsolete content
Archive › Mozilla › XUL › Method › reload
...
reloadWithFlags - Archive of obsolete content
<< XUL Reference home reloadWithFlags( flags ) Return type: no return value Reloads the document in the browser with the given load flags. The flags listed below may be used, which are all constants of the webNavigation property (or the nsIWebNavigation interface). You may combine flags using a or symbol ( | ). LOAD_FLAGS_NONE: No special flags. The document is loaded normally. LOAD_FLAGS_BYPASS_CACHE: Reload the page, ignoring if it is already in the cache. This is the flag used when the reload button is pressed while the Shift key is held down. LOAD_FLAGS_BYPASS_PROXY: Reload the page, ignoring the proxy server. LOAD_FLAGS_CHARSET_CHANGE: This flag is used if the document needs to be reloaded because the character set changed. ...
replaceGroup - Archive of obsolete content
<< XUL Reference home replaceGroup( group ) Not in Firefox Return type: array of session history objects Replaces existing tabs with a new set. If there were more tabs before, the additional ones are not removed. You can use the removeTab method to remove the existing tabs first if that is desired. The argument should be an array of objects, one for each document to load. The objects may be defined in script and contain a URI property for the URL of the page to load. A referrerURI property may also be optionally used to set the referrer page. This method returns an array of the session history objects for the tabs that were removed. ...
stop - Archive of obsolete content
Archive › Mozilla › XUL › Method › stop
...
MenuItems - Archive of obsolete content
odifiers="accel" key="O"/> <key id="close-key" modifiers="accel" key="C"/> </keyset> <menubar> <menu label="View"> <menupopup> <menuitem label="Open" key="open-key"/> <menuitem label="Close" key="close-key"/> </menupopup> </menu> </menubar> The two menuitems are associated with a key using the key attribute. It should be set to the ID of a key element within the same document. The result is that the items will display the shortcut key next to their labels. For the "Open" item in this example, this command can be invoked by using the "accel" modifier key and pressing 'O'. The "accel" modifier key varies on each platform, but is the key typically used for shortcut keys. For instance, if the "accel" key is Control, the menu might display "Ctrl + O". Although there isn't...
Special per-platform menu considerations - Archive of obsolete content
he label and shortcut keys are overridden by platform conventions. However, regardless of the platform, the command event will be fired on the menu item when it is activated by the user. Notes for Firefox extension developers On the Mac, some elements, once moved to the Application menu, are no longer accessible from XUL overlays or from JavaScript injected into browser.xul. For example, using document.getElementById() for the Quit menu item returns the hidden item that still sits in the File menu. To change these items in Firefox, overlay hiddenWindow.xul instead. ...
Positioning - Archive of obsolete content
ult position to appear is with the upper left corner (or upper right corner in right to left locales) at the position where the mouse was clicked. Context menus will appear offset down and to the right a couple of pixels so that the menu can be dismissed again just by clicking in the same place. If a context menu was opened via the keyboard only, the menu will appear at the top left corner of the document, or underneath the currently selected item if a list is focused. Context menus will always appear in this location, and not respect any position attribute value. Tooltips will always appear near the current mouse position, offset vertically by a small amount. The position attribute The position of all types of popups can be controlled in two ways. First, the position can be specified when usi...
Tooltips - Archive of obsolete content
t the tooltip applies to, so you may need to set the content in a tooltip if you wish to use the same tooltip for several elements. This can be accomplished by using a popupshowing event listener and adjusting the tooltip as needed. The popupshowing event will be fired on the tooltip element just before the tooltip appears. For example: <tooltip id="iconic" onpopupshowing="this.lastChild.value = document.tooltipNode.label;"/> The document.tooltipNode property of the document holds the element that the mouse is hovering over. In this example, this property is examined to retrieve the label of the element that the mouse is over. This label is then set as the value of the last child of the tooltip. In the earlier example, the last child of the tooltip is a label. The effect is that the value of th...
Printing from a XUL App - Archive of obsolete content
This document will talk about PrintUtils, and the ways that XUL applications can trigger print-related behaviors. Structure of an Installable Bundle: describes the common structure of installable bundles, including extensions, themes, and XULRunner applications Extension Packaging: specific information about how to package extensions Theme Packaging: specific information about how to package themes Multiple-item Extension Packaging: specific information about multiple-item extension XPIs XUL Application Packaging: specific information about how to package XULRunner applications Chrome Registration Printing in XUL Apps ...
boxObject - Archive of obsolete content
It is covered further in the tutorial. ...
contentTitle - Archive of obsolete content
...
contentViewerEdit - Archive of obsolete content
...
contentViewerFile - Archive of obsolete content
...
currentIndex - Archive of obsolete content
rty 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. ...
disabled - Archive of obsolete content
<< XUL Reference disabled Type: boolean Gets and sets the value of the disabled attribute. ...
docShell - Archive of obsolete content
...
editortype - Archive of obsolete content
<< XUL Reference editortype Type: one of the values below The type of editor to use. This value will be overridden depending on the content type of the document in the editor. html An HTML editor. text A plaintext editor. ...
itemCount - Archive of obsolete content
<< XUL Reference itemCount Type: integer Read only property holding the number of child items. ...
securityUI - Archive of obsolete content
...
webBrowserFind - Archive of obsolete content
...
webNavigation - Archive of obsolete content
<< XUL Reference webNavigation Type: nsIWebNavigation This read-only property contains the nsIWebNavigation object for the document. Most of its methods are callable directly on the element itself, such as goBack and goForward. It also contains the load constants used by reloadWithFlags and loadURIWithFlags. ...
webProgress - Archive of obsolete content
...
Providing Command-Line Options - Archive of obsolete content
tions can modify the way command line parameters are handled by writing a component that implements the nsICommandLineHandler interface and registering it in a category. See also: XULRunner:CommandLine Overview The code below is an example of writing a JavaScript XPCOM component to handle command line parameters. You can learn more about how the command line is interpreted by looking at the documentation for the nsICommandLine interface. Example The below example component implements two command line parameters: firefox.exe -myapp Opens a chrome window for My Application. firefox.exe -viewapp url Opens a chrome window for My Application and passes it an nsIURI object. Using the example To use this sample code, save the commandLine.js file into the components directory and add th...
Additional Template Attributes - Archive of obsolete content
This allows you to share the same template among two different parts of the user interface. To use this technique, place a template attribute on the root element set to the id of a template. ...
Introduction - Archive of obsolete content
rce is already loaded, the builder can construct content all in one step, although even this isn't completely true as we'll see later. For XML datasources, use a querytype of xml. The datasources attribute should be the URL of an XML file, which can be either the location of a web site or a file on the local file system, using its file or chrome URL. This file will be loaded and the resulting XML document will be used as the datasource when the template builder generates results and creates content. For example: <listbox datasources="http://www.xulplanet.com/ds/sample.xml" querytype="xml"> <template> <listitem label="?name"/> </template> </listbox> This template uses an XML datasource to generate a listbox. Although we'll look at the details of this later, the simple result here is that a...
Namespaces - Archive of obsolete content
XML Namespaces can be used in XUL Templates by binding the namespace URI and prefix to the template element. ...
Rule Compilation - Archive of obsolete content
ns for how to retrieve a set of data from the datasource. The exact syntax is dependent on the type of datasource used in the template. For instance, for an SQLite datasource, an SQL statement is used as the query. This will return a table of result records which are then used to generate output. For RDF and XML, the query contains a set of instructions for navigating through the RDF graph or XML document tree. A query is declared with the query tag (new to FF3; FF2 only worked with RDF datasources and had no query tag), which you would place directly inside the <template>. The job of the query is to generate a set of output results. Rules The template also contains a set of rules which define content to be generated based on various conditions. An attribute substitution syntax, explained later, i...
SQLite Templates - Archive of obsolete content
> </listbox> Here, the age is an integer number, so the type attribute is set to integer. Integers are 32-bit values, but you can use the value int64 for 64-bit integers. You can also use the value double for double precision floating point values. If no type is specified, a string is assumed. We could later change the age to use in the query with a short script: function adjustAge(min, max) { document.getElementById("minage").textContent = min; document.getElementById("maxage").textContent = max; document.getElementById("friends").builder.rebuild(); } This function takes two arguments, the minimum and maximum values to use. We retrieve the param elements and set their textContent properties to the desired value. Finally, we rebuild the entire template. << PreviousNext >> ...
Simple Query Syntax - Archive of obsolete content
1/09/countries/iso#IT"/> Adjusting Simple Query Conditions The simple syntax is limited in the kind of filtering it can do, however it is often sufficient for many purposes. Naturally, if you want to set a filter dynamically, as the photos example does with a menulist, you will need to set the attribute on the rule element and rebuild the template. function applyFilter(country) { var rule = document.getElementById("filterRule"); if (country){ rule.setAttributeNS("http://www.xulplanet.com/rdf/", "country", country); } else { rule.removeAttributeNS("http://www.xulplanet.com/rdf/", "country"); } document.getElementById("photosList").builder.rebuild(); } This version of the applyFilter function only needs to set or remove the attribute on the rule as necessary. Note that the ...
Sorting Results - Archive of obsolete content
etermine where in the content the generated output should be inserted. The is similar to using a variable but any predicate may be used, not just one that is used in the template. Changing the Sort To change the sorting for a template's generated contents, you can either change the sort related attributes and rebuild the template, or you can call the sort method of the sort service: var listbox = document.getElementById("aListBox"); var sortService = Components.classes["@mozilla.org/xul/xul-sort-service;1"]. getService(Components.interfaces.nsIXULSortService); sortService.sort(listbox, "?gender", "descending"); This code will sort a listbox by title in a descending order. The arguments to the sort method specify the root node (the listbox), the sort key and the sort direction...
Template Logging - Archive of obsolete content
turally, semantic errors in the data in the datasource can't be easily detected automatically. However, for XML datasources, you can at least check the builder's datasource to see whether the XML data was loaded and parsed correctly. If null, then the datasource could not be loaded, or hasn't yet been loaded. If the datasource load and parsing was successful, the datasource will be set to the XML document. For example: if (root.builder.datasource instanceof XMLDocument) alert("XML Datasource loaded OK"); Be careful, as the datasource will only be set once the document has finished loading and has been parsed, so don't check this property too early. You may also get an error if you manipulate or analyze the template while the datasource is loading. You could iterate and wait using a timer. Futur...
Using Recursive Templates - Archive of obsolete content
te> <query expr="*"/> <action> <vbox uri="?" class="indent"> <label value="?name"/> </vbox> </action> </template> </groupbox> In this simplified example, the XPath expression just gets the list of child elements of the reference node. For the outermost iteration, a vbox is created with a child label. Since the initial reference node is the root of the XML source document, the results are two elements, one for each group element. However, a further step is done to retrieve an additional level of nodes. As each group has children itself, each result (in this case, each group) becomes the reference point for a futher iteration. The same query is executed again but using the groups generated from the previous execution of the query. This time, the query generates a r...
XML Assignments - Archive of obsolete content
e root node (or reference node) as the XPath context, the expressions for the assign element are evaluated using each result node as the context. For each result, the ?namelength variable will be assigned the length of the name attribute on the result node, and the ?siblings variable will be assigned the number of sibling nodes the result has. (In this case, the number of XML node siblings in the document, not the number of real siblings the people have, clearly the people in the datasource aren't actually siblings). Naturally, the number of siblings will be the same for all children, but you could imagine a more complex query expression that generated nodes where this wasn't actually the case. The two variable assignments may then be used in the action body to replace attributes in the generated ...
Code Samples - Archive of obsolete content
const path = "C:\\WINDOWS\\CHARMAP.EXE" var file = Components .classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile) file.initWithPath(path) file.launch() Open a web page If your button is in Firefox or SeaMonkey, use code like this to open a web page. Change the first line to specify the page that you want to open: const url = "http://www.mozilla.org/" document .getElementById("content") .webNavigation .loadURI(url, 0, null, null, null) If your button is in Thunderbird or Sunbird, use code like this to open a web page. Change the first line to specify the page that you want to open: const url = "http://www.mozilla.org/" var uri = Components .classes["@mozilla.org/network/simple-uri;1"] .getService(Components.interfaces.nsIURI) uri.spec = ur...
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
file's icon and drop it in SeaMonkey, or choose File - Open File... from the menu bar.) Distribute the XPI file to other users. Alternate "Quick and Dirty" method for hooking up a single preexisting XUL file to display in SeaMonkey: As described above, find the SeaMonkey\chrome folder. Create a subfolder (eg. SeaMonkey\chrome\myapp) and open it, placing your XUL file within. ...
Toolbars - Archive of obsolete content
Toolbar customization events A look at the events that are sent during toolbar customization; you can use these to be kept aware of changes to toolbars. ...
Tree Widget Changes - Archive of obsolete content
tree-separator pseudo has been improved to make it a proper box type and now has additional styling capabilities. Example: treechildren::-moz-tree-separator { margin-top: 1px; border-top: 1px solid ThreeDShadow; border-left: 1px solid ThreeDShadow; border-right: 1px solid ThreeDHighlight; border-bottom: 1px solid ThreeDHighlight; height: 2px; } Original Document Information Author: Neil Deakin Source: here ...
Adding HTML Elements - Archive of obsolete content
below to remember this decision. <html:p> <html:input id="rtd" type="checkbox"/> <html:label for="rtd">Remember This Decision</html:label> </html:p> </html:p> In this case, one p tag was used to place the text in and another was used to break apart the text into multiple lines. Text outside of HTML blocks Example 3 : Source View <html:div> Would you like to save the following documents? <html:hr/> </html:div> Expense Report 1 What I Did Last Summer <button id="yes" label="Yes"/> <button id="no" label="No"/> As can be seen in the image, the text inside the div tag was displayed but the other text (Expense Report 1 and What I Did Last Summer) was not. This is because there is no HTML or XUL element capable of displaying text enclosing it. To have this text appear, you would...
Adding Labels and Images - Archive of obsolete content
de opening and closing description tags for longer blocks of text. It is more common to use the attribute syntax for labels, and the text content syntax for descriptions. Example 4 : Source View <description> This longer section of text is displayed. </description> You can set the text via script using the textContent property, as in the following example: <description id="text" width="200"/> document.getElementById('text').textContent = "Some lengthy word wrapped text goes here."; Internally, both the label element and the description elements are the same. The label element is intended for labels of controls, such as text fields. The control attribute is only supported for labels. The description element is intended for other descriptive text such as informative text at the top of a dialog ...
Creating a Skin - Archive of obsolete content
Modifying userChrome.css is not guaranteed to work between versions of Firefox and may lead to hard-to-diagnose bugs. Use at your own risk! This section describes how to create a simple skin. For simplicity, we'll only apply it to the find files dialog. A Simple Skin The image below shows the current find files dialog. Let's create a skin that we can apply to it. Normally, a skin would apply to the entire application, but we'll focus on just the find files dialog to make it easier. For this reason, we'll modify only the file findfile.css rather than the global.css file. This section assumes that you are starting with the Classic skin. ...
Grids - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Grids
utton element of course. If you wanted one particular cell to contain multiple elements, you can use a nested hbox or other box element. An hbox is a single element but you can put as many elements that you want inside it. For example: Example 2 : Source View <grid flex="1"> <columns> <column/> <column flex="1"/> </columns> <rows> <row> <label control="doctitle" value="Document Title:"/> <textbox id="doctitle" flex="1"/> </row> <row> <label control="docpath" value="Path:"/> <hbox flex="1"> <textbox id="docpath" flex="1"/> <button label="Browse..."/> </hbox> </row> </rows> </grid> Notice in the image how the first column of elements containing the labels has only a single element in each row. The second column co...
Install Scripts - Archive of obsolete content
ply 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 contains a number of functions to customize the install process. Some ...
Keyboard Shortcuts - Archive of obsolete content
has the focus. Note that the event will be called as soon as the key is pressed, even if it hasn't been released yet. keyup Called when a key is released while an element has the focus. Key events are only sent to the element that has the focus. Typically, this will include textboxes, buttons, checkboxes and so forth. If no element is focused, the key event will instead be targeted at the XUL document itself. In this case, you can add an event listener to the window tag. Normally though, if you want to respond to keys globally, you will use a keyboard shortcut as described earlier. The key event object has two properties which hold the key that was pressed. The keyCode property holds the key code and may be compared to one of the constants from the key table earlier in this section. The charC...
Localization - Archive of obsolete content
s. The example below demonstrates the use of an entity in a button. <button label="&findLabel;"/> The text that will appear on the label will be the value that the entity &findLabel; has. A file is created which contains the entity declarations for each supported language. In English, the &findLabel; entity will probably be declared to have the text "Find". DTD Files Entities are declared in Document Type Definition (DTD) files. Files of this type are normally used to declare the syntax and semantics of a particular XML file, but they also let you declare entities. In the Mozilla chrome system, you will find DTD files located in the locales subdirectory. You would normally have one DTD file (with an extension .dtd) per XUL file. If you look in the chrome directory, you should see an archive ...
Modifying the Default Skin - Archive of obsolete content
Support for the userChrome.css file and any of its elements described below are not guaranteed in future versions of Firefox. Using it may lead to hard-to-diagnose bugs or crashes. Use at your own risk! This section describes how to modify the skin of a window. ...
Scroll Bars - Archive of obsolete content
You can also use it when you need to ask for a value that falls within a certain range. Scroll bars can be created in a number of ways. In XUL, one can be created using the scrollbar tag. Some elements, such as text boxes, will also add scroll bars as necessary when the content inside is too large. In this section, we'll discuss creating a stand-alone scroll bar. The user will set the value by adjusting the scroll bar. ...
Templates - Archive of obsolete content
duplicates it for each row. For instance, if the user had ten bookmarks in the example above, ten label elements would be created and added as children of the vbox element. If you were to use DOM functions to traverse the tree, you will find these elements there and can query their properties. These elements get displayed, but the template itself is not displayed, although it still exists in the document tree. In addition, the id of each of the labels will be set to the RDF resource for that row. The content builder always starts at the place where uri="rdf:*" is specfied. If the uri attribute is placed on an element lower in the element tree, the elements outside are only created once. In the example below, one hbox will be created and it will be filled with a label for each item. <template> ...
The Chrome URL - Archive of obsolete content
The Chrome URL XUL files can be referenced with a regular HTTP URL (or any type of URL) just like HTML files. However, packages that are installed into Mozilla's chrome system can be referenced with special chrome URLs. The packages included with Mozilla will already be installed but you can register your own. Installed packages have the advantage that they don't have security restrictions placed on them, which is necessary for many applications. Another advantage over other URL types is that they automatically handle multiple themes and locales. ...
Updating Commands - Archive of obsolete content
se these extra steps when invoking commands implemented by a controller. In addition, you will need to do this when creating your own menu commands, for instance to implement the edit menu commands in your own application. Fortunately, the extra code is fairly simple. All we need to do is get the needed controller and call the command. A simple way of doing this is the following: var controller = document.commandDispatcher.getControllerForCommand("cmd_paste"); if (controller && controller.isCommandEnabled("cmd_paste")){ controller.doCommand(command); } The code above first retrieves the controller for the 'cmd_paste' command from the command dispatcher. Then, it checks to see whether the command is enabled, and then executes the command using the doCommand method of the controller. Note that we...
XPCOM Examples - Archive of obsolete content
() 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 list with the names of all of the cookies set from MozillaZine. ...
XPCOM Interfaces - Archive of obsolete content
ce is placed in the variable bmarks. We use QueryInterface() to get the nsIBookmarksService interface. The function addBookmarkImmediately() provided by this interface can be used to add bookmarks. The first two parameters to this function are the bookmark's URL and its title. The third parameter is the bookmark type which will normally be 0 and the last parameter is the character encoding of the document being bookmarked, which may be null. Next, we will see some of the interfaces provided with Mozilla that we can use. << PreviousNext >> ...
Using spell checking in XUL - Archive of obsolete content
See Controlling spell checking in HTML forms for details on adding spell check support to HTML forms for your website. Checking the spelling of a word To check the spelling of a word, you must first create an interface to the mozISpellCheckingEngine component and then call the check() method on the string you wish to test. This method returns true if the word is correctly spelled, or false if it's not. ...
XUL Changes for Firefox 1.5 - Archive of obsolete content
ent has a strings property which may be used to retrieve an enumeration of all of the strings in the bundle. Draggable tabs The tabbrowser now allows the user to rearrange tabs by dragging them. <tabbox> The <tabbox> element now supports a selectedIndex attribute to specify the tab to be selected by default. Loading overlays dynamically XUL now supports loading overlays dynamically with the document.loadOverlay function. Original Document Information Author(s): Neil Deakin ...
XUL FAQ - Archive of obsolete content
Are there decent visual editors for laying out XUL applications? There are no production-quality visual editors available for XUL. The recommended way is to edit XUL by hand, possibly with the help of a good text or XML editor. Ted Mielczarek's Live XUL Editor (also part of Extension Developer's Extension) often proves useful. A list of projects (dead and active) aiming to create a XUL IDE/editor is at wikimo:XUL:IDE. ...
XUL controls - Archive of obsolete content
ton element. Button Reference Related Elements: menupopup menuitem <button type="menu-button"> A button that that has a separate arrow button with a menu attached to it. Unlike with the 'menu' type, a separate action may be performed when the main part of the button is pressed. <button type="menu-button" label="New"> <menupopup> <menuitem label="New Document"/> <menuitem label="New Image"/> </menupopup> </button> More information about this type of menu button element. Button Reference Related Elements: menupopup menuitem <checkbox> A control that may be turned on and off, typically used to create options which may be enabled or disabled. <checkbox label="Show Toolbar Labels" checked="true"/...
action - Archive of obsolete content
collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
arrowscrollbox - Archive of obsolete content
ard that many lines. scrollByPixels( pixels ) Return type: no return value Scrolls the contents of the arrowscrollbox by a certain number of pixels. Use a positive value as the pixels argument to scroll forward that many pixels, or a negative value to scroll backward that many pixels. ...
assign - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
bbox - Archive of obsolete content
Archive › Mozilla › XUL › bbox
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
binding - Archive of obsolete content
collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
bindings - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
box - Archive of obsolete content
Archive › Mozilla › XUL › box
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
broadcaster - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
broadcasterset - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
button - Archive of obsolete content
open attribute. orient Type: string Gets and sets the value of the orient attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. type Type: string Gets and sets the value of the type attribute. ...
caption - Archive of obsolete content
crop attribute. image Type: image URL Gets and sets the value of the image attribute. label Type: string Gets and sets the value of the label attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. ...
checkbox - Archive of obsolete content
ets the value of the disabled attribute. src Type: URL Gets and sets the value of the src attribute. label Type: string Gets and sets the value of the label attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. ...
column - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
columns - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
command - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
commandset - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
conditions - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
content - Archive of obsolete content
variable name for the content. When a rule is evaluated, it scans through each resource in the RDF datasource looking for a match. Each resource is placed in the variable specified in the uri attribute in turn. Then, the other rules are evaluated for a match. This attribute should always be present. ...
datepicker - Archive of obsolete content
year Type: integer The currently selected year from 1 to 9999. Set this property to change the selected year. yearLeadingZero Type: boolean A read only value indicating whether a leading zero should be displayed before the year when it is less than 1000. ...
deck - Archive of obsolete content
Archive › Mozilla › XUL › deck
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
dialog - Archive of obsolete content
tring Normally this attribute should not be set, but if it is, it specifies the default button in the dialog. Typically, this means that the button will be activated when the Enter key is pressed. This should be set to one of the same values as those for the buttons attribute. ...
dialogheader - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
dropmarker - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
grid - Archive of obsolete content
Archive › Mozilla › XUL › grid
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
grippy - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
groupbox - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
hbox - Archive of obsolete content
Archive › Mozilla › XUL › hbox
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
image - Archive of obsolete content
Archive › Mozilla › XUL › image
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
keyset - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
label - Archive of obsolete content
Archive › Mozilla › XUL › label
Gets and sets the value of the disabled attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
listcol - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
listcols - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
listhead - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
listheader - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
listitem - Archive of obsolete content
er Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
member - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
menu - Archive of obsolete content
Archive › Mozilla › XUL › menu
ilable for menuitem and menuseparator elements in Firefox 3. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
menubar - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
menuitem - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
menulist - Archive of obsolete content
er Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
menuseparator - Archive of obsolete content
r Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
notification - Archive of obsolete content
ring Gets and sets the value of the type attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
observes - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
page - Archive of obsolete content
Archive › Mozilla › XUL › page
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
param - Archive of obsolete content
Archive › Mozilla › XUL › param
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
popup - Archive of obsolete content
Archive › Mozilla › XUL › popup
...
popupset - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
query - Archive of obsolete content
Archive › Mozilla › XUL › query
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
queryset - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
radio - Archive of obsolete content
Archive › Mozilla › XUL › radio
r Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
radiogroup - Archive of obsolete content
r Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
resizer - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
richlistbox - Archive of obsolete content
r Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
richlistitem - Archive of obsolete content
r Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
row - Archive of obsolete content
Archive › Mozilla › XUL › row
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
rows - Archive of obsolete content
Archive › Mozilla › XUL › rows
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
rule - Archive of obsolete content
Archive › Mozilla › XUL › rule
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
scale - Archive of obsolete content
Archive › Mozilla › XUL › scale
r Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
script - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
scrollbar - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
scrollbox - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
scrollcorner - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
separator - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
spacer - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
spinbuttons - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
splitter - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
stack - Archive of obsolete content
Archive › Mozilla › XUL › stack
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
statusbar - Archive of obsolete content
collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
<statusbarpanel> - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
stringbundle - Archive of obsolete content
(e.g. %1$S, %2$S, etc.) can be used to specify the position of the corresponding parameter explicitly. If you need to handle substitutions involving plurals, take a look at Localization and Plurals. getString( key ) Return type: string Returns the string with the given key name from the string bundle. ...
stringbundleset - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
tab - Archive of obsolete content
Archive › Mozilla › XUL › tab
r Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
tabpanel - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
tabpanels - Archive of obsolete content
will be deselected. Returns -1 if no items are selected selectedPanel Type: element Holds a reference to the currently selected panel within a <tabbox> element. Assigning a value to this property will modify the selected panel. A select event will be sent when the selected panel is changed. ...
tabs - Archive of obsolete content
Archive › Mozilla › XUL › tabs
r Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
template - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
textnode - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
timepicker - Archive of obsolete content
ng zero should be displayed before the second when it is less than 10. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string The currently entered time of the form HH:MM:SS. Set this property to change the time. ...
titlebar - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
toolbar - Archive of obsolete content
atch an element in the toolbar's toolbarpalette. Some special ids may also be used to create special spacing items: separator: A separator, which is drawn as a vertical bar. spacer: A non-flexible space. spring: A flexible space. The method returns the DOM element for the created item. ...
toolbarbutton - Archive of obsolete content
f the open attribute. orient Type: string Gets and sets the value of the orient attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. type Type: string Gets and sets the value of the type attribute. ...
toolbargrippy - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
toolbaritem - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
toolbarpalette - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
toolbarseparator - Archive of obsolete content
collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
toolbarset - Archive of obsolete content
collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
toolbarspacer - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
toolbarspring - Archive of obsolete content
collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
toolbox - Archive of obsolete content
at is, toolbar elements that should be considered to be members of this toolbox, even if they are not actually children of the toolbox. palette Firefox only Type: element The toolbarpalette within the toolbox. toolbarset Firefox only Type: element The toolbarset within the toolbox. ...
treecell - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
treechildren - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
treecol - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
treecols - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
treeitem - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
treerow - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
treeseparator - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
triple - Archive of obsolete content
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
vbox - Archive of obsolete content
Archive › Mozilla › XUL › vbox
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
where - Archive of obsolete content
Archive › Mozilla › XUL › where
ollapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
wizardpage - Archive of obsolete content
ntrollers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttributeNS(), hasAttributes(), hasChildNodes(), insertBefore(), i...
XUL - Archive of obsolete content
XUL (XML User Interface Language) is Mozilla's XML-based language for building user interfaces of applications like Firefox. The term XUL is sometimes used to refer to the whole Mozilla platform (e.g. XUL applications are applications using XUL and other components of the platform). XUL Controls lists some of the common controls provided by XUL. Documentation XUL Tutorial A guided tutorial that will help you get started with XUL, originally from XULPlanet. XUL Reference XUL elements, attributes, properties, methods, and event handlers. XUL Controls A quick list of all of the available XUL controls. The Joy of XUL Describes the key feat...
XULRunner 1.8.0.1 Release Notes - Archive of obsolete content
nd are typically packaged as a ZIP archive with the extension .xulapp or .xpi. Sample applications are available from the Mozilla Developer Center. Save the application archive to your desktop or another convenient place. ...
XULRunner 1.8.0.4 Release Notes - Archive of obsolete content
are typically packaged as a ZIP archive with the extension .xulapp or .xpi. Sample applications are available from the Mozilla Developer Center. Save the application archive to your desktop or another convenient place. ...
XULRunner 1.9.1 Release Notes - Archive of obsolete content
and are typically packaged as a ZIP archive with the extension .xulapp or .xpi. Sample applications are available from the Mozilla Developer Center. Save the application archive to your desktop or another convenient place. ...
XULRunner 1.9.2 Release Notes - Archive of obsolete content
s, and are typically packaged as a ZIP archive with the extension .xulapp or .xpi. Sample applications are available from the Mozilla Developer Center. Save the application archive to your desktop or another convenient place. ...
XULRunner 1.9 Release Notes - Archive of obsolete content
and are typically packaged as a ZIP archive with the extension .xulapp or .xpi. Sample applications are available from the Mozilla Developer Center. Save the application archive to your desktop or another convenient place. ...
XULRunner 2.0 Release Notes - Archive of obsolete content
ces, and are typically packaged as a ZIP archive with the extension .xulapp or .xpi. Sample applications are available from the Mozilla Developer Center. Save the application archive to your desktop or another convenient place. ...
Building XULRunner - Archive of obsolete content
By default, XULRunner is built with JavaXPCOM support; the build system must be able to find an appropriate JDK on the system; see the instructions on Building JavaXPCOM for more details. If you do not want to build JavaXPCOM support, specify --disable-javaxpcom in your configuration. On Mac, XULRunner requires Mac OS X 10.3 or higher and XCode 1.5 or higher to build properly. The runtime requirement is Mac OS X 10.2. ...
CommandLine - Archive of obsolete content
0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="main" title="&window.title;" windowtype="xulmine" style="width: 300px; height: 350px;" persist="screenX screenY width height sizemode"> <script type="application/javascript" src="cmdline.js" /> ... </window> Original Document Information Author: Georges-Etienne Legendre Last Updated Date: August 21st, 2007 ...
Creating a Windows Inno Setup installer for XULRunner applications - Archive of obsolete content
Inno Setup Script (.iss file). The Inno Setup Script Wizard can't set chrome directory's deployment point, so you have to edit the iss file yourself. Also you had better set the AppName and AppPublisher properties to the same values specified in your XULRunner application's application.ini file. My App's .iss file sample as follows: ; Script generated by the Inno Setup Script Wizard. ...
Deploying XULRunner - Archive of obsolete content
Current XULRunner is a stable developer preview release. This means that while the release is immature in some areas such as embedding, application deployment, and OS integration, it can be used by developers that are releasing standalone XUL applications. This document explains how deployment should be managed for self contained portable applications built on XULRunner. Note: To actually install a XULRunner application, a compatible version of XULRunner must be registered on the system and the app must be deployed per the instructions at XUL Application Packaging. If your installer is capable of determining whether or not XULRunner has been registered on the system you could perform the check and register the appropriate version if necessary. After that, the app could be installed to th...
Dialogs in XULRunner - Archive of obsolete content
ases. Firefox and Thunderbird both support nearly native Page Setup and Print dialogs. ...
XULRunner Hall of Fame - Archive of obsolete content
wser is a very simple example browser", xulmine. An updated version of "mybrowser" that works with Firefox 25.0.1+ is available in Matthew Kastor's XULRunner examples at https://github.com/matthewkastor/XULRunner-Examples/ Exch A currency conversion tool using updated data from http://finance.yahoo.com/currency. You can use the Firefox extension or the stand-alone XUL application. OpenDocument Viewer Cross-platform viewer for OpenDocument files. TaskPool TaskPool is a little application to help keep track of time. You can add tasks to a pool, turn them on and off, and it will tick off seconds. SVGclock An SVG-based clock. Crowbar A web scraping environment based on the use of a server-side headless mozilla-based browser. 30b A XULRunner-based wrapper...
Using LDAP XPCOM with XULRunner - Archive of obsolete content
By default, XULRunner is built without LDAP XPCOM support. If you want to use LDAP components in your XUL application, you have two options : compile XULRunner with LDAP support enabled, or add LDAP XPCOM directly to your XUL app (in the components directory). In any case, you will have to build LDAP XPCOM, by adding --enable-ldap build option. See the Build_Documentation for more information about how to build XULRunner. When Configuring Build Options, just add: ac_add_options --enable-ldap to your .mozconfig file. This will create two files in the components directory of the build package: mozldap.dll (or libmozldap.so or...) mozldap.xpt and two files in the root directory of the build package: On windows: nsldap32v50.dll nsldappr32v50.dll On linux: libldap50.so libprld...
MacFAQ - Archive of obsolete content
In your .mozconfig for custom builds of XULRunner, add --enable-libxul. If you've completed a XULRunner build, you should copy or symlink the dist/XUL.framework directory to /Library/Frameworks. Note that in order to copy the framework while keeping the relative soft-links in the framework, do something like: % ( cd dist ; gnutar cf - XUL.framework | ( cd /Library/Frameworks ; gnutar xf - )) Installing Your Application Your application must be installed as a XULRunner app before you can open it. ...
Opening a Link in the Default Browser - Archive of obsolete content
lso check whether an external handler for a scheme exists. This is how you do it: var extps = Components.classes["@mozilla.org/uriloader/external-protocol-service;1"] .getService(Components.interfaces.nsIExternalProtocolService); if (extps.externalProtocolHandlerExists("http")) { // Handler for http:// URLs exists } Link Within an IFrame To enable a link inside an html document that is the "src" of an iframe to be opened in the default browser, setting the preference: pref("network.protocol-handler.expose-all", false); seems to work. ...
Windows and menus in XULRunner - Archive of obsolete content
uded in the application. There are quite a few things XUL offers for application UI. ...
application/http-index-format specification - Archive of obsolete content
1: presented. 100: 300: ftp://test.netscape.com/u/montulli 100: 200: Filename Content-Length Content-Type File-type Last-Modified 201: foo.txt 512 Text/Plain FILE Tue,%2015%20Nov%201994%2008:12:31%20GMT 201: bar.html 9683 text/Html FILE Tue,%2025%20Oct%201994%2008:12:31%20GMT 201: foobar 0 application/http-index-format DIRECTORY Tue,%2025%20Oct%201994%2008:12:31%20GMT Original Document Information Author(s): Christian Biesinger Last Updated Date: May 10, 2004 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
mozilla.dev.platform FAQ - Archive of obsolete content
refox 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 found." A: See Bug 350616 ...
Mozrunner - Archive of obsolete content
For more information about mozrunner as part of the mozbase project, please see the mozbase project page. mozrunner is a python package which handles running of Mozilla applications. mozrunner utilizes mozprofile for managing application profiles and mozprocess for robust process control. mozrunner may be used from the command line or programmatically as an API. Command Line Usage The mozrunner command will launch the application (specified by --app) from a binary specified with -b or as located on the PATH. mozrunner takes the command line options from mozprofile for constructing the profile to be used by the application. Run mozrunner --help for detailed information on the command line program. ...
2006-10-06 - Archive of obsolete content
cements Legal Precedent Set for Web Accessibility US Federal court rules that retailers may be sued if its website is inaccsessible. Read more... Discussions W3C Sets Road Map for Web App Accessibility The W3C introduced its WAI-ARIA (Web Accessibility Initiative for Accessible Rich Internet Applications) roadmap--a set of guidelines for developers to make accessible web content. This set of documents tackles some of the difficulties that AJAX has been causing with regards to accessibility. Read more... Other links of interest: Roadmap for Accessible Rich Internet Applications (WAI-ARIA Roadmap) Roles for Accessible Rich Internet Applications (WAI-ARIA Roles) States and Properties Module for Accessible Rich Internet Applications (WAI-ARIA States and Properties) Making Ajax Work with Screen Re...
2006-12-01 - Archive of obsolete content
The debate continues. Discussion of support for Modal windows within Firefox 2.0 A lengthy post regarding the re-implementation of modal windows into firefox. Basic Feature that I think is a must in any web broswer A discussion revolving around the idea of having firefox automatically convert mistaken non-English characters to English so that web addresses will be completed. mozStorage documentation up A revisted discussion surround the mozStorage documentation. rich results for searches A proposal to implement "rich results", a set of registered sites that would provide information as it relates to a user's search. Windows DDE Shell Integration removal A call for responses or concerns regarding the removal of the DDE Shell Integration. How do allow an internal web site to h...
2006-11-17 - Archive of obsolete content
oaz invites your Comments XULRunner 1.8.0.4 is running a kiosk-type application on Linux with 512Mb, and there is the appearance of a significant memory leak. Win2XUL asks for any quick pointers, opinions, experience, suggestions or Ideas on where xulrunner might leak memory Bug 319654 was fixed on trunk recently. Nickolay Ponomarev lets us know that Processing instructions are now added to XUL document's DOM This also means, you can no longer use document.firstChild in XUL scripts to get the root element of a XUL document and the xml-stylesheet and xul-overlay processing instructions outside the prolog no longer have any effect peter.sei...@gmail.com runs into some difficulties Deploying XULRunner 1.8 on OS X? Please see mozilla.dev.platform FAQ for solution. Peter Naulls makes the suggestion...
2006-10-27 - Archive of obsolete content
gray one. Help for getting HTML element width info Discussion on retrieving width information on HTML elements when using the Gecko engine. It was determined that the offsetWidth property can be used to get this value. Multiple presshells Discussion on why current interfaces allow for multiple presshells and how the relationships work for the following objects: docshell, presshell, prescontext, document, domwindow, widget, docshell and contentviewer. Boris Zbarsky explains in detail the relationships between these objects. The presshells are currently used for printing, but should or could have been used for print previews and multiple views in editors. Meetings None this week. ...
2006-11-17 - Archive of obsolete content
to being merged with the trunk. Nightly builds, instructions and the current list of known regressions on the branch can be found at: http://wiki.mozilla.org/Gecko:Reflow...ng#Quick_Links. Users are asked to file bugs on encountered problems that are not present on the current trunk builds. If bugs are filed, "[reflow branch]" should be placed at the beginning of the summary. Parsing HTML into a document object in Fx3 Discussion if Gecko 1.9 will support parsing HTML into a document object. The possibility of turning the MicrosummaryResource object into a XPCOM component, which accomplishes this task in a "hacky" manner, was also discussed. Meetings None this week. ...
2006-12-24 - Archive of obsolete content
Summary: mozilla.dev.tech.layout November 24 -December 1, 2006 Announcements None this week. Discussions [Reset issue for overflow='hidden' In IE and Opera there is a very modest horizontal shift of the document due to reflow associated with the removal of the vertical scroll bar (because the document content is using a horizontal centering style). But in Firefox the document is reset (shifted both horizontally and vertically) to its 0,0 position before being centered horizontally. ...
2006-12- 02 - Archive of obsolete content
Summary: mozilla.dev.tech.layout - November 24 2006 - December 2, 2006 Announcements None this week. Discussions [Reset issue for overflow='hidden' In IE and Opera there is a very modest horizontal shift of the document due to reflow associated with the removal of the vertical scroll bar (because the document content is using a horizontal centering style). But in Firefox the document is reset (shifted both horizontally and vertically) to its 0,0 position before being centered horizontally. ...
2006-11-10 - Archive of obsolete content
Summary: mozilla.dev.tech.xpcom - Oct 04-Nov 10, 2006 Announcements XPTCall changes in process - ports owners needed If you maintain an xptcall port, you are needed to submit a patch to that bug 349002 with xptcall updates. Discussions Developing an extension like XmlHttpRequest / nsIDocument / MOZILLA_INTERNAL_API A discussion on how to develop an extension similar to XmlHttpRequest but for a different protocol than Http, emulating the asynchronous aspect. Meetings None during this week. ...
2006-11-17 - Archive of obsolete content
Summary: mozilla.dev.tech.xul - Nov 11-Nov 17, 2006 Return to mozilla-dev-tech-xul Announcements Processing instructions are now added to XUL document's DOM On November 12, 2006, Nickolay Ponomarev announces the results of the recently fixed Bug 319654. The result of the bug fix is that you may no longer use document.firstChild in XUL scripts. For a summary of the changes and workarounds, read Nickolay's post in the mozilla.dev.tech.xul newsgroup. Discussions None during this week. Meetings None during this week. ...
NPAPI plugin developer guide - Archive of obsolete content
urages website developers to avoid using plugins wherever possible. If there are plugin features which are not available in the web platform, we encourage developers to post their use cases to mozilla.dev.platform project list, so that Mozilla can prioritize web platform work to make those use cases possible. Plugins are written using NPAPI, the cross-browser API for plugins. The main source of documentation for NPAPI is the NPAPI plugin API reference. To make your plugin scriptable from web pages, use npruntime. Plug-in Basics How Plug-ins Are Used Plug-ins and Helper Applications How Plug-ins Work Understanding the Runtime Model Plug-in Detection How Gecko Finds Plug-ins Checking Plug-ins by MIME Type Overview of Plug-in Structure Understanding the Plug-...
Logging Multi-Process Plugins - Archive of obsolete content
plugins are enabled, Firefox has the ability to dump additional information about interactions between the browser and a plugin. This is done using NSPR logging. Run Firefox in a custom environment to enable this special logging mode. Make sure you have write permissions to wherever you wish to save the log. Your safest bet is your home directory (C:\Users\username on Windows Vista and above, C:\Documents and Settings\username on Windows XP, and ~ (home directory) on Mac OS X and Linux). Windows Make sure Firefox is not running. From within a command prompt: C:\> set NSPR_LOG_MODULES=IPCPlugins:5 C:\> set NSPR_LOG_FILE=c:\plugins.log C:\> cd C:\Program Files\Mozilla Firefox C:\> firefox.exe The log file will be saved to C:\plugins.log (or wherever NSPR_LOG_FILE is set). Linux Make sure Firefox i...
NPN_GetValue - Archive of obsolete content
ells whether the browser supports windowless plugins. The value parameter should point to a NPBool, which will be set appropriately if the function returns NPERR_NO_ERROR. NPNVprivateModeBool: Indicates whether or not the browser is currently in private browsing mode. The value parameter should point to an NPBool, which will be set appropriately if the function returns NPERR_NO_ERROR. NPNVdocumentOrigin: The value for this variable is the Unicode serialization of the origin converted to NFKC-encoded (normalized) UTF-8. Memory for this string must be freed by the plugin via NPN_MemFree(). For more information, see the document origin specification. NPNVpluginDrawingModel: (Mac only) NPNVsupportsQuickDrawBool : (Mac only) NPNVsupportsCoreGraphicsBool : (Mac only) value ...
NPN_InvalidateRect - Archive of obsolete content
ss plug-in can repaint or refresh part of its drawing area, the plug-in must first invalidate the area with either NPN_InvalidateRect() or NPN_InvalidateRegion(). NPN_InvalidateRect() causes the NPP_HandleEvent() method to pass an update event or a paint message to the plug-in. After calling this method, the plug-in receives a paint message asynchronously. The browser redraws invalid areas of the document and any windowless plug-ins at regularly timed intervals. To immediately send a paint message, the plug-in can call NPN_ForceRedraw() after calling this method. See also NPN_ForceRedraw() NPN_InvalidateRegion() NPRect NPP ...
NPN_InvalidateRegion - Archive of obsolete content
a windowless plug-in can repaint or refresh part of its drawing area, the plug-in must first invalidate the area with either NPN_InvalidateRect() or NPN_InvalidateRegion(). NPN_InvalidateRegion() causes the NPP_HandleEvent() method to pass an update event or a paint message to the plug-in. If a plug-in calls this method, it receives a paint message later. The browser redraws invalid areas of the document and windowless plug-ins at regularly timed intervals. To force a paint message, the plug-in can call NPN_ForceRedraw() after calling this method. See also NPN_ForceRedraw() NPN_InvalidateRect() NPRegion NPP ...
NPP_Print - Archive of obsolete content
log boxes, getting the printer device context, and any other tasks involved in printing, as well as printing the rest of the page. For an embedded plug-in, set the printInfo field to NPEmbedPrint. A full-page plug-in handles all aspects of printing itself. For a full-page plug-in, set the printInfo field to NPFullPrint or null. For information about printing on your platform, see your platform documentation. MS Windows On MS Windows printInfo->print.embedPrint.platformPrint is the device context (DC) handle. Be sure to cast this to type HDC. The coordinates for the window rectangle are in TWIPS format. This means that you need to convert the x-y coordinates using the Windows API call DPtoLP when you output text. See Also NPPrint, NPFullPrint, NPEmbedPrint ...
NPRegion - Archive of obsolete content
region of a page. Syntax Windows: typedef HRGN NPRegion; Mac OS X: typedef RgnHandle NPRegion; Note: This may need to be updated for the Cocoa event model. XWindows: typedef Region NPRegion; Description NPRegion defines the region of the plug-in window to be updated, painted, invalidated, or clipped to. For information about the region type definition used by your platform, see your platform documentation. See also NPN_ForceRedraw() NPN_InvalidateRect() NPN_InvalidateRegion() NPWindow NPRect ...
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
3.3 / SeaMonkey 2.1), it was possible to package multiple plugin libraries for different operating systems into a single xpi bundle. In the XPI you can use the following structure: platform/ Linux_x86-gcc3/ plugins/ libplugin.so Darwin_ppc-gcc3/ plugins/ libplugin.dylib More specific information can be found in the platform-specific subdirectories documentation. Gecko 2.0 (Firefox 4) and later Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) removed support for platform-specific subdirectories. Instead, you need to place the different plugin libraries into the plugins directory. For example: plugins/ libplugin.so libplugin.dylib Install Manifest The install manifest describes the plugin to the user. For a plugin the manifest only ne...
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
nt to take advantage of the capabilities of newer toolkits use Xt. Also, when included with builds of Mozilla that are based on Gtk 1.2 or Gtk 2.x, the Xt code that hosts the plugins is at best hacky and has been the source for many minor problems including inconsistent focus behavior as well as occasional crashes. It's recommended that you have a look at the Gecko Plugin API Reference since this document will include information that assumes that you are already familiar with the way that plugins are currently hosted as well as the APIs. Key Differences All of the interfaces that you would normally expect to exist in the plugins will still exist when using XEmbed plugins. There are only two key differences: In the NPP_SetWindow call, the window parameter will be the XID of the hosting XEmbed win...
Plugins - Archive of obsolete content
rmation. Plugins are shared libraries that users can install to display content that the browser can't display natively. For example, the Adobe Reader plugin lets the user open PDF files directly inside the browser, and the QuickTime and RealPlayer plugins are used to play special format videos in a web page. Plugins are written using NPAPI, the cross-browser API for plugins. The main source of documentation for NPAPI is the Gecko Plugin API Reference. To make your plugin scriptable from web pages, use npruntime. Plugins can be written completely from scratch using C APIs (usually in C or C++) or they may be built on a plugin framework such as Firebreath, JUCE, or QtBrowserPlugin. There are also some code generation tools that may be helpful. More information about these tools can be found on t...
Atomic RSS - Archive of obsolete content
Archive › RSS › Module › Atom
article yet written, should be populated with another feature article or tutorial, should one exist. Otherwise, just comment it out Getting Started A guided tutorial that will help you get started with Atomic RSS. Atomic RSS uses Atom as an RSS Module. It brings in Atom elements into RSS, adding the advantages of Atom to RSS while maintaining backwards compatibility. Documentation Selected Articles Atomic RSS Tim Bray talks about using Atom 1.0 as a micro format and extension module for RSS 2.0; keeping RSS 2.0 as your sydication format but bringing in and using selected Atom 1.0 elements. References Atomic RSS Element List Examples no...
Content - Archive of obsolete content
here is no "Getting Started" article yet written, should be populated with another feature article or tutorial, should one exist. Otherwise, just comment it out Getting Started A guided tutorial that will help you get started with the RSS Content Module. The RSS Content Module provides facilities to include content for an <item>. But doing this in more efficient ways. Documentation Selected Articles Why RSS Content Module is Popular - Including HTML Contents Charles Iliya Krempeaux talks about the RSS Content Module, why it is popular among some, and how it is used to include HTML contents. References RSS Content Module Element List Examples ...
Slash - Archive of obsolete content
Archive › RSS › Module › Slash
Getting Started A guided tutorial that will help you get started with the RSS Slash Module. The RSS Slash Module is popular among Slash based blogs and blogs imitating the feel for Slashdot. Slash is the engine behind the famous Slashdot. Documentation Selected Articles UP TO 10 Why RSS Slash is Popular: Counting Your Comments Charles Iliya Krempeaux talks about the RSS Slash Module, why it is popular among some, and how it is used to give a count for your comments (2005-08-22). References RSS Slash Module Element List Examples none available at this time Community none available at this time Tools none available at this time Other Resources ...
Well-Formed Web - Archive of obsolete content
Getting Started A guided tutorial that will help you get started with the Well-Formed Web RSS Module. The Well-Formed Web RSS Module provides facilities for <item> level commenting: for linking to comments contained in an external RSS Feed, and for posting new comments. Documentation Selected Articles Why Well-Formed Web RSS Module is Popular - Syndicating Your Comments Charles Iliya Krempeaux talks about the RSS Well-Formed Web Module, why it is popular among some, and how it is used to link to your comments (2005-08-22). References RSS Well-Formed Web Module Element List Examples none available at this time Community none available at this time Tools none availa...
Module - Archive of obsolete content
They are ways of extending RSS. Below is a list of the popular RSS modules. ...
RSS - Archive of obsolete content
Simple Syndication (RSS) is a popular HTML-like XML-based data format used for syndication. RSS has a sordid history and a multitude of different incompatible RSS versions. (Some being based on RDF, but most only being based on XML.) Nonetheless, RSS is an extremely popular format that is used for syndicating news, blog posts, IPradio, and IPTV, with an amazing amount of momentum. Documentation Why RSS Slash is Popular - Counting Your Comments Charles Iliya Krempeaux talks about the RSS Slash Module, why it is popular among some, and how it is used to give a count for your comments. Why Well-Formed Web RSS Module is Popular - Syndicating Your Comments Charles Iliya Krempeaux talks about the RSS Well-Formed Web Module, why it is popular among some, and how ...
.htaccess ( hypertext access ) - Archive of obsolete content
to the directory SSI or Server Side Include : Include external files to each file requested by the user without the need to write include statements in the file; you can have them automatically attached to all the files, whether at top or bottom, automatically through your .htaccess file. php_value auto_prepend_file "/real/path/to/file/functions.php" # Adds function.php at the top of requested document php_value auto_append_file "/real/path/to/file/footer.php" # Adds footer.html at bottom of requested document Customized error responses : User can be directed to different pages depending on the Error they caused or by the webserver. ErrorDocument 404 /notfound.html # Redirects traffic to notfound.html in case of a 404 error ErrorDocument 500 /serverr.html # Redirects traffic to serverr.html...
Confidentiality, Integrity, and Availability - Archive of obsolete content
u are directed to is not genuine. Availability Availability means that information is accessible by authorized users. If an attacker is not able to compromise the first two elements of information security (see above) they may try to execute attacks like denial of service that would bring down the server, making the website unavailable to legitimate users due to lack of availability. Original Document Information Author(s): Karen Scarfone, Wayne Jansen, and Miles Tracy Title: NIST Special Publication 800-123, Guide to General Server Security Last Updated Date: July 2008 Copyright Information: This document is not subject to copyright. ...
Encryption and Decryption - Archive of obsolete content
lues for a key of a given length, rather than a subset of those values. Because it is relatively trivial to break an RSA key, an RSA public-key encryption cipher must have a very long key, at least 1024 bits, to be considered cryptographically strong. On the other hand, symmetric-key ciphers can achieve approximately the same level of strength with an 80-bit key for most algorithms. Original Document Information Author(s): Ella Deon Lackey Last Updated Date: 2012 Copyright Information: (C) 2012 Red Hat, Inc. Link: Red Hat Certificate System Common Criteria Certification 8.1: Deployment, Planning, and Installation ...
NSPR Release Engineering Guide - Archive of obsolete content
.z [BUILD_OPT=1 | USE_DEBUG_RTL=1] Copy the bits from MDist to /share/builds/components/nspr20/.vx.y.z In /share/builds/components/nspr20/ run the following scripts: explode.pl rename.sh symlink.sh RTM Bits Rename the .vx.y.z directory to vx.y.z (remove the hidden directory 'dot'). Copy /share/builds/components/nspr20/vx.y.z/* to /share/systems/mozilla/pub/nspr/vx.y.z/ Original Document Information Author: larryh@netscape.com Last Updated Date: September 20, 2000 1 Copying files to /share/builds/components requires that one be logged on to a machine named "smithers" as user "svbld". The password to this account is restricted to a small set of designated release engineers. ...
SSL and TLS - Archive of obsolete content
112 2048 224-255 128 3072 256-383 192 7860 384-511 256 15360 512+ The information in this table is from the National Institute of Standards and Technology (NIST). For more information, see http://csrc.nist.gov/publications/nistpubs/800-57/SP800-57-Part1.pdf. For more information on ECC, see RFC 4492, Section 5.6.1, Table 2. Original Document Information Author(s): Ella Deon Lackey Last Updated Date: 2012 Copyright Information: (C) 2012 Red Hat, Inc. Link: Red Hat Certificate System Common Criteria Certification 8.1: Deployment, Planning, and Installation ...
TCP/IP Security - Archive of obsolete content
f the other SSL endpoint with which it wishes to communicate, ensuring that the network traffic and data is being sent from the expected host. SSL authentication is typically performed one-way, authenticating the server to the client, but it can be performed mutually. Replay Protection. The same data is not delivered multiple times, and data is not delivered grossly out of order. Original Document Information Author(s): Sheila Frankel, Paul Hoffman, Angela Orebaugh, and Richard Park Title: National Institute of Standards and Technology (NIST) Special Publication 800-113, Guide to SSL VPNs Last Updated Date: July 2008 Copyright Information: This document is not subject to copyright. ...
Vulnerabilities - Archive of obsolete content
Security Misconfiguration 6. Cross-Site Request Forgery (CSRF) ...
Creating a Skin for Firefox - Archive of obsolete content
skin does not totally change the interface; instead, it just defines how the interface looks. You can't change what happens when the user right clicks on an image, but you can change the look of the right click menu (Make it blue with pink polka dots, for example). If you want to change the functionality of Firefox, you'll have to look into modifying the chrome, which is beyond the scope of this document. Contents Getting Started Original Document Information Author(s): Neil Marshall and Tucker Lee Other Contributors: Brent Marshall, CDN (http://themes.mozdev.org), JP Martin, Boris Zbarsky, Asa Dotzler, WeSaySo, David James, Dan Mauch, Anders Conbere, Tim Regula (http://www.igraphics.nn.cx) Copyright Information: Copyright 2002-2003 Neil Marshall, permission given to MDC to migrate into t...
Themes - Archive of obsolete content
Archived theme documentation. Building a ThemeCommon Firefox theme issues and solutionsCreating a Skin for FirefoxUUIDcontents.rdfinstall.rdfMaking sure your theme works with RTL localesTheme changes in Firefox 2Theme changes in Firefox 3Theme changes in Firefox 3.5Theme changes in Firefox 4 ...
Using Firebug and jQuery (Screencast) - Archive of obsolete content
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 quick introduction to the subject, so ...
Using IO Timeout And Interrupt On NT - Archive of obsolete content
errors. If <tt>CancelIo()</tt> really works as advertised, that should fundamentally solve this problem. ...
Using SSH to connect to CVS - Archive of obsolete content
Anonymous/read-only access via SSH is not available at this time. Please see our source code page for directions accessing read-only CVS, and our getting write access page for directions on obtaining write access. Generating an SSH key First, install ssh. Most Linux, BSD, and OSX distributions come with it installed already. Cygwin makes ssh available on Windows if you install the openssh package from the Net category. If all else fails, OpenSSH is a widely used and highly portable implementation. ...
Using Web Standards in your Web Pages - Archive of obsolete content
s excellent and best references for those wishing to learn more about upgrading techniques presented in this article and more for those wishing to perfect their web pages. Contents Benefits of using web standards Making your page using web standards - how to Using the W3C DOM Developing Cross Browser and Cross Platform Pages Using XMLHttpRequest Summary of Changes References Original Document Information Author(s): Mike Cowperthwaite, Marcio Galli, Jim Ley, Ian Oeschger, Simon Paquet, Gerard Talbot Last Updated Date: May 29, 2008 Copyright Information: Portions of this content are (C) 1998-2008 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
-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> Gradient progid:DXImageTransfor...
-ms-flow-from - Archive of obsolete content
Initial valuenoneApplies tonon-replaced elementsInheritednoComputed valueas specifiedAnimation typediscrete Syntax Values none Default. No container has been specified. ...
-ms-flow-into - Archive of obsolete content
Initial valuenoneApplies toiframe elementsInheritednoComputed valueas specifiedAnimation typediscrete Syntax Values none Default. No container has been specified. ...
-ms-scroll-translation - Archive of obsolete content
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-scroll-translation property to vertical-to...
:-moz-system-metric(scrollbar-thumb-proportional) - Archive of obsolete content
The :-moz-system-metric(scrollbar-thumb-proportional) CSS pseudo-class will match an element if the computer's user interface uses proportional scrollbar thumbs; that is, the draggable thumb on the scrollbar resizes to indicate the relative size of the visible area of the document. This selector is intended for use mainly by theme developers. Note: Since Firefox 58, this pseudo-class is no longer available to web content -- it is only available internally (e.g. to XUL / chrome code). See bug 1396066 for more details. Specifications Not part of any specification. ...
:-moz-system-metric() - Archive of obsolete content
r's user interface includes a forward arrow button at the start of scrollbars.:-moz-system-metric(scrollbar-thumb-proportional)The :-moz-system-metric(scrollbar-thumb-proportional) CSS pseudo-class will match an element if the computer's user interface uses proportional scrollbar thumbs; that is, the draggable thumb on the scrollbar resizes to indicate the relative size of the visible area of the document.:-moz-system-metric(touch-enabled)The :-moz-system-metric(touch-enabled) CSS pseudo-class will match an element if the device on which the content is being rendered offers a supported touch-screen interface.:-moz-system-metric(windows-default-theme)The :-moz-system-metric(windows-default-theme) CSS pseudo-class matches an element if the user is currently using one of the following themes in Windo...
-moz-scrollbar-thumb-proportional - Archive of obsolete content
Otherwise it's 0. Media: media/visual Accepts min/max prefixes: no ...
E4X - Archive of obsolete content
Archive › Web › E4X
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 implemented (at least partially) in SpiderMonkey (Geck...
Namespaces - Archive of obsolete content
You can declare the default namespace for your E4X objects by placing the statement: default xml namespace = "http://www.w3.org/1999/xhtml"; within the same scope as your E4X. You can also change namespaces at any time, by repeating the statement. ...
E4X Tutorial - Archive of obsolete content
Next >> 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 >> ...
Iterator - Archive of obsolete content
} Passing Generator instance function* f() { yield 'a'; yield 'b'; } var g = f(); console.log(g == Iterator(g)); // true for (var v in Iterator(g)) { console.log(v); // a // b } Passing Iterator instance var a = { x: 10, y: 20, }; var i = Iterator(a); console.log(i == Iterator(i)); // true Specifications Non-standard. Not part of any current standards document ...
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
implemented, but only available in the Firefox Nightly channel and not yet included in a draft edition of an ECMAScript specification. Additions to the ArrayBuffer object ArrayBuffer.transfer() (spec) New TypedObject objects Based on Typed Objects draft, and exposed via a global TypedObject object, e.g. TypedObject.StructType & TypedObject.ArrayType. This feature is non-standard and not documented. See https://bugzilla.mozilla.org/show_bug.cgi?id=1336740 and https://bugzilla.mozilla.org/show_bug.cgi?id=578700. New Shared Memory objects SharedArrayBuffer Atomics ...
Expression closures - Archive of obsolete content
age something similar to a typical Lambda notation. ...
Date.getVarDate() - Archive of obsolete content
eturns 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 Explorer 10 standards. Not supported in Windows 8.x Store apps. Applies To: Date Object See Also Date.getDate() Date.parse() ...
Debug.debuggerEnabled - Archive of obsolete content
The debug.debuggerEnabled property determines whether debugging is enabled for the script context. Debugging may be enabled or disabled whether or not a debugger is attached. Syntax var dbgEnabled = Debug.debuggerEnabled; Requirements Supported in the following document modes: Internet Explorer 10 standards and Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards. ...
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
s result of async operation. }, function (error) { Debug.msTraceAsyncOperationCompleted(opID, Debug.MS_ASYNC_OP_STATUS_ERROR); Debug.msTraceAsyncCallbackStarting(opID); }); Debug.msTraceAsyncCallbackCompleted(); } function doSomethingAsync() { return WinJS.Promise.as(true); } asyncWrapperFunction(); Requirements Supported in the Internet Explorer 11 standards document mode. Also supported in Store apps (Windows 8.1 and Windows Phone 8.1). Not 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. Not supported in Windows 8. ...
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
s result of async operation. }, function (error) { Debug.msTraceAsyncOperationCompleted(opID, Debug.MS_ASYNC_OP_STATUS_ERROR); Debug.msTraceAsyncCallbackStarting(opID); }); Debug.msTraceAsyncCallbackCompleted(); } function doSomethingAsync() { return WinJS.Promise.as(true); } asyncWrapperFunction(); Requirements Supported in the Internet Explorer 11 standards document mode. Also supported in Store apps (Windows 8.1 and Windows Phone 8.1). Not 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. Not supported in Windows 8. ...
Debug.msUpdateAsyncCallbackRelation - Archive of obsolete content
GN_DELEGATE Debug.MS_ASYNC_CALLBACK_STATUS_JOIN Debug.MS_ASYNC_CALLBACK_STATUS_CHOOSEANY Debug.MS_ASYNC_CALLBACK_STATUS_CANCEL Debug.MS_ASYNC_CALLBACK_STATUS_ERROR For more information, see Debug Constants. Note: Some debugging tools do not display the information sent to the debugger by this function. Requirements Supported in the Internet Explorer 11 standards document mode. Also supported in Store apps (Windows 8.1 and Windows Phone 8.1). Not 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. Not supported in Windows 8. ...
Debug.setNonUserCodeExceptions - Archive of obsolete content
to false is the same as never having set the property. For more information on debugging, see the Active Script Debugging Overview. Example The following code shows how to set this property. (function () { Debug.setNonUserCodeExceptions = true; try{ var x = null; x.y(); } catch (e) { // Catch the exception. } })(); Requirements Supported in the following document modes: Internet Explorer 10 standards and Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards. ...
Debug.write - Archive of obsolete content
: 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, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). ...
Debug.writeln - Archive of obsolete content
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 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). Applies To: Debug ...
Debug - Archive of obsolete content
ciated asynchronous operation. Debug.write Sends strings to the script debugger. Debug.writeln Sends strings to the script debugger, followed by a newline character. Examples Print the value of a variable This example uses the write function to display the value of the variable. 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, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). ...
Enumerator.atEnd - Archive of obsolete content
Not supported in Windows 8.x Store apps. Applies To: Enumerator Object ...
Enumerator.item - Archive of obsolete content
Not supported in Windows 8.x Store apps. Applies To: Enumerator Object ...
Enumerator.moveFirst - Archive of obsolete content
Not supported in Windows 8.x Store apps. Applies To: Enumerator Object ...
Enumerator.moveNext - Archive of obsolete content
Not supported in Windows 8.x Store apps. Applies To: Enumerator Object ...
Error.stackTraceLimit - Archive of obsolete content
If the property is set to a negative value or a non-numeric value, the value is converted to 0. If the stackTraceLimit is set to Infinity, the entire stack is shown. Otherwise, ToUint32 is used to convert the value. Example The following example shows how to set and then get the stack trace limit. try { var err = new Error("my error"); Error.stackTraceLimit = 7; throw err; } catch(e) { document.write("Error stack trace limit: ") document.write(Error.stackTraceLimit); } Requirements Supported in Internet Explorer 10 and in Windows 8.x Store apps. Applies To: Error Object ...
ScriptEngine() - Archive of obsolete content
e 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). ...
ScriptEngineBuildVersion - Archive of obsolete content
n value corresponds directly to the version information contained in the dynamic-link library (DLL) for the scripting language in use. Example The following example illustrates the use of the ScriptEngineBuildVersion function: if(window.ScriptEngineBuildVersion) { console.log(window.ScriptEngineBuildVersion()); } // Output: <current build version> 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). ScriptEngine Function ScriptEngineMajorVersion Function ScriptEngineMinorVersion Function ...
ScriptEngineMajorVersion - Archive of obsolete content
ks The return value corresponds directly to the version information contained in the dynamic-link library (DLL) for the scripting language in use. Example The following example illustrates the use of the ScriptEngineMajorVersion function: if (window.ScriptEngineMajorVersion) { console.log(window.ScriptEngine()); } Output: <current major version> 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). ...
ScriptEngineMinorVersion - Archive of obsolete content
value corresponds directly to the version information contained in the dynamic-link library (DLL) for the scripting language in use. Example The following example illustrates the use of the ScriptEngineMinorVersion function. if (window.ScriptEngineMinorVersion) { console.log(window.ScriptEngineMinorVersion()); } //Output: <current minor version> 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). ...
New in JavaScript 1.1 - Archive of obsolete content
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. ...
New in JavaScript 1.2 - Archive of obsolete content
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 in JavaScript 1.3 - Archive of obsolete content
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. ...
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. New features in JavaScript 1.4 Exception handling (throw and try...catch) in operator instanceof operator Changed functionality in JavaScript 1.4 eval() changes (cannot be called indirectly and no longer a method of Object) arguments not a property of functions Deprecated Function.arity in favor of Function.length Changes to LiveConnect ...
Object.prototype.watch() - Archive of obsolete content
ded 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.location += '#myAnchor' will call myHandler. Note: Calling watch() on an object for a specific property overrides any previous handler attached for that property. Examples Using watch and unwatch const o = { p: 1 }; o.watch('p', (id, oldval, newval) => { console.log('o.' + id + ' changed from ' + oldval + ' to ' + newval); return newval; }); o.p = 2; o.p = 3; delete o...
LiveConnect Overview - Archive of obsolete content
f .jar or .zip file. Specify the location of .jar or .zip file when you compile by using the -classpath command line parameter. You can specify an environment variable in Windows NT by double-clicking the System icon in the Control Panel and creating a user environment variable called CLASSPATH with a value similar to the following: C:\Program Files\Java\jre1.4.1\lib\plugin.jar See the Sun JDK documentation for more information about CLASSPATH. Note: Because Java is a strongly typed language and JavaScript is weakly typed, the JavaScript runtime engine converts argument values into the appropriate data types for the other language when you use LiveConnect. See Data Type Conversions for complete information. Using the LiveConnect Classes All JavaScript objects appear within Java code as instance...
LiveConnect Reference - Archive of obsolete content
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. ...
RDF: Resource Description Framework for metadata - Archive of obsolete content
Archive › Web › RDF
d upon the idea of making statements about resources in the form of a subject-predicate-object expression, called a triple in RDF terminology. The subject is the resource, the "thing" being described. The predicate is a trait or aspect about that resource, and often expresses a relationship between the subject and the object. The object is the object of the relationship or value of that trait. Documentation Directions of the Mozilla RDF engine This presentation shows new developments in the Mozilla RDF engine. These include plans to expose the RDF API to public web content, as well as performance and correctness improvements. What is RDF Tim Bray's introduction to the Resource Description Framework, at XML.com. RDF Datasource How-To A cookbook-style document describing how to crea...
Standards-Compliant Authoring Tools - Archive of obsolete content
e that may require extra debugging for compatibility with standards-based browsers. Newer versions of Microsoft FrontPage(TM) have improved, however be sure not to rely on FrontPage-specific extensions for critical website content or functionality. Some versions of Microsoft Word create invalid HTML code that only works with Internet Explorer. Always be sure to validate your web pages. Original Document Information Last Updated Date: January 30th, 2003 Copyright (C) 2001-2003 Netscape. All rights reserved. Related links Validators HTML Central ...
StopIteration - Archive of obsolete content
or(a); console.log(iter.next()); // ["x", 10] console.log(iter.next()); // ["y", 20] console.log(iter.next()); // throws StopIteration Throwing StopIteration. function f() { yield 1; yield 2; throw StopIteration; yield 3; // this is not executed. } for (var n in f()) { console.log(n); // 1 // 2 } Specifications Non-standard. Not part of any current standards document ...
forEach - Archive of obsolete content
Feel free to alter the text as English is not my mother tongue and I'm more concerned with the code quality that the English grammar ;-S dotnetCarpenter 30 June 2012 <hr> The Compatibility section goes to extraordinary lengths in providing a forEach implementation. ...
RFE to the Custom Controls - Archive of obsolete content
XUL, in many cases, is much better suited for application development than XHTML. Therefore the control set may need to be more extensive to address the wider spectrum of requirements that a XUL application will have on its controls. ...
XForms Styling - Archive of obsolete content
peats See the Mozilla XForms Specials page for some general points. Switches Can be styled as tabs. Triggers Use appearance="minimal" to be able to style buttons Portability The Mozilla XForms extension is one of the few XForms processors which allow for styling of the XForms elements directly, using mostly standard CSS. Processors such as Chiba create "old-style" HTML forms from XForms documents, and must be styled accordingly. However, most of the time the transition is straight-forward: View the source after processing of your XForms document, and map the old styles to the new elements. Appearance attributes can also make a big difference. Experimenting with these can give you some easier way of styling the contents than just using the default. === Example === Here's a small example t...
XForms Help Element - Archive of obsolete content
Introduction Specifies contextual help for the containing form control (see the spec). The help message will be displayed if the F1 key is pressed while the containing form control has focus or if the containing form control recieves a xforms-help event. The message of the help element can exist in instance data, in a remote document, or as inline text. If more than one source of message is specified in this element, the order of precedence is: single node binding attributes, linking attributes, inline text. Attributes Single-Node Binding Linking src - URL of a document whose contents will be retrieved by the help element and used to provide a help message for the containing form control. Type restrictions The help element can be bound to any simple content. Representations Is repr...
XForms Hint Element - Archive of obsolete content
Introduction Similar to a tooltip (see the spec). The hint is displayed when the mouse moves and pauses over the containing form control. The hint will also be displayed if the containing form control recieves a xforms-hint event. The message of the hint element can exist in instance data, in a remote document, or as inline text. If more than one source of message is specified in this element, the order of precedence is: single node binding attributes, linking attributes, inline text. Attributes Single-Node Binding Linking src - URL of a document whose contents will be retrieved by the hint element and used to provide hint text for the containing form control. Type restrictions The hint element can be bound to any simple content. Representations Is represented by a tooltip window t...
XForms Input Element - Archive of obsolete content
splaying a text field is the default presentation. XForms inputs are most often used when a form author needs to allow for the input/output of simple text into an instance node. Allows for free-form data entry (xhtml/xul). Characteristics A text field is presented to the user when there is no type given for the bound node or a type is specified that is not handled by one of the other widgets (as documented below). analogous widgets are <xhtml:input type="text"/> and <xul:textbox/> Specific handling of attributes incremental - if "true", the bound instance node will be updated on each character typed by the user. If "false", or the incremental attribute is omitted on this element then the bound instance node will be updated when the control loses the focus. checkbox Most often used when the for...
XForms Message Element - Archive of obsolete content
Introduction Used in combination with XML Event listeners to display a message to the user when the specified event occurs (see the spec). The message of the message element can exist in instance data, in a remote document, or as inline text. If more than one source of message is specified in this element, the order of precedence is: single node binding attributes, linking attributes, inline text. Attributes Single-Node Binding Linking src - URL of a document whose contents will be retrieved by the message element and used to provide the message text for the message element. Special level - defines a representation of message element Type restrictions The message element can be bound to any simple content. Representations It may be represented in the following ways: modal wind...
XForms Output Element - Archive of obsolete content
ment to display the image (Fx 3.0 only, xhtml/xul). text Displaying the data as text is the default presentation. XForms output is most often used when a form author needs to render simple text of an instance node (xhtml/xul). Characteristics text is presented to the user when there is no type given for the bound node or a type is specified that is not handled by one of the other widgets (as documented below). analogous widgets are <xhtml:span/> and <xul:description/> calendar A form author may notice a XForms output element represented by a calendar widget in the Mozilla XForms processor if the control meets the following criteria (xhtml/xul). Characteristics the bound instance node is of type xsd:date or a type derived from it in addition, the appearance attribute must also contain t...
XForms Repeat Element - Archive of obsolete content
For each node in the nodeset, the contents of the repeat element will be displayed in the form. That node will serve as the context node for any relative xpath expressions in that set of repeated markup. Attributes UI Common appearance - the value of this attribute gives a hint to the XForms processor as to which type of widget(s) to use to represent this control. Node Set Binding Special startindex - optional 1-based initial value of the repeat index. The default value is 1. number - isn't supported Type restrictions The repeat element can be bound to a nodeset. ...
XForms Submit Element - Archive of obsolete content
Upon receiving a DOMActivate event, this form control dispatches a xforms-submit event to the submission element (see the spec) specified in its submission attibute. Attributes UI Common appearance - the value of this attribute gives a hint to the XForms processor as to which type of widget(s) to use to represent this control. accesskey - used to specify the keyboard shortcut for focusing this control. ...
RDF in Fifty Words or Less - Archive of obsolete content
n> </rdf:RDF> Upon receipt of the above monstrosity, the RDF engine folds the RDF into the graph at the appropriate place, and the tree control that actually implements the UI to the bookmarks is notified that it should begin drawing some icons for the latest message about Yam Soup from Aunt Helga. This isexactly how SmartMail works. Contact: Chris Waterson (waterson@netscape.com) Original Document Information Author(s): Chris Waterson Last Updated Date: November 19, 1998 Copyright Information: Copyright (C) Chris Waterson Interwiki Language Link ...
Styling Abbreviations and Acronyms - Archive of obsolete content
ormation associated with it. In Mozilla, placing the mouse pointer over the element and leaving it for a moment will cause the contents of the title attribute to appear as a tooltip next to the mouse pointer. Removing the underline from these elements will rob readers of an indication that there is extra information available. Related Links Web Content Accessibility Guidelines 1.0 Original Document Information Author(s): Eric A. Meyer, Netscape Communications Last Updated Date: Published 09 Aug 2002 Copyright Information: Copyright (C) 2001-2003 Netscape. All rights reserved. Note: This reprinted article was originally part of the DevEdge site. ...
XQuery - Archive of obsolete content
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 URLs, the currently loaded webpage (even if originally from poorly formed HTML), and/or XML (including well-formed XHTML) documents stored locally. The extension now includes and interfaces with the open-source version of Saxonica's Saxon B (though this extension currently only performs the XQueries). Other popular native XML databases might also be supported (e.g., eXist) in the future, especially now that the extension has added some basic support for the open-standard (XQJ) for Java and eXist is in the midst of getting s...
XUL Parser in Python - Archive of obsolete content
om the XULParser and XULWriter XPCOM objects. ...
Anatomy of a video game - Game development
r tasks, or handle asynchronous events. While we are on the topic of budgeting time, many web browsers have a tool called High Resolution Time. The Date object is no longer the recognised method for timing events because it is very imprecise and can be modified by the system clock. High Resolution Time, on the other hand, counts the number of milliseconds since navigationStart (when the previous document is unloaded). This value is returned as a decimal number accurate to a thousandth of a millisecond. It is known as a DOMHighResTimeStamp but, for all intents and purposes, consider it a floating point number. Note: Systems (hardware or software) that are not capable of microsecond accuracy are allowed to provide millisecond accuracy as a minimum. They should provide 0.001ms accuracy if they are...
Building up a basic demo with PlayCanvas - Game development
The online editor is free for public projects with up to two team members, but there are also paid plans if you'd like to run a commercial private project with more developers. Games and demos PlayCanvas has a few well-known demos published that showcase its possibilities. Tanx is a multiplayer tank game where you can drive your tank around, shooting at other players as you go. ...
Desktop mouse and keyboard controls - Game development
n pure JavaScript. The good thing about using Phaser is that it offers helper variables and functions for easier and faster development, but it's totally up to you which approach you chose. Pure JavaScript approach Let's think about implementing pure JavaScript keyboard/mouse controls in the game first to see how it would work. First, we'd need an event listener to listen for the pressed keys: document.addEventListener('keydown', keyDownHandler, false); document.addEventListener('keyup', keyUpHandler, false); Whenever any key is pressed down, we're executing the keyDownHandler function, and when press finishes we're executing the keyUpHandler function, so we know when it's no longer pressed. To do that we'll hold the information on whether the keys we are interested in are pressed or not: var...
Unconventional controls - Game development
nces 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 JavaScript tutorials available on the Leap Motion documentation pages, which will get you through the basics. You can also check out the tutorial about using Leap Motion plugin for Kiwi.js, or the case study of building a web game with Leap Motion and Pixi.js. Be sure to visit the LeapJS repository on GitHub to learn about the JavaScript client for the Leap Motion controller and read the documentation there. If all else fails, there's also a gallery of w...
Crisp pixel art look with image-rendering - Game development
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: You can check out the original code on Github (and a live example.) ...
Efficient animation for web games - Game development
t 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. There are several techniques worth knowing that will improve the performance of your game or application whilst also using less battery life, especially on low-end devices. It is worth documenting some of these things, as there is evidence to suggest (in popular and widely-used UI libraries, for example) that they aren't necessarily common knowledge. First off, let us discuss some basic ideas. Help the browser help you If you are using DOM for your UI, which I would certainly recommend, you really ought to use CSS transitions and/or CSS animations, rather than JavaScript-powered anima...
Mouse controls - Game development
s actually finished, so let's work on polishing it up. We have already added keyboard controls, but we could easily add mouse controls too. Listening for mouse movement Listening for mouse movement is even easier than listening for key presses: all we need is the listener for the mousemove event. Add the following line in the same place as the other event listeners, just below the keyup event: document.addEventListener("mousemove", mouseMoveHandler, false); Anchoring the paddle movement to the mouse movement We can update the paddle position based on the pointer coordinates -- the following handler function will do exactly that. Add the following function to your code, below the previous line you added: function mouseMoveHandler(e) { var relativeX = e.clientX - canvas.offsetLeft; if(...
Paddle and keyboard controls - Game development
an 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). Add these t...
Track the score and win - Game development
+) { var b = bricks[c][r]; if(b.status == 1) { if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) { dy = -dy; b.status = 0; score++; if(score == brickRowCount*brickColumnCount) { alert("YOU WIN, CONGRATULATIONS!"); document.location.reload(); clearInterval(interval); // Needed for Chrome to end game } } } } } } Thanks to this, your users can actually win the game when they destroy all the bricks, which is quite important when it comes to games. The document.location.reload() function reloads the page and starts the game again once t...
Physics - Game development
re with physics, for example by adding ball.body.gravity.y = 100; you will set the vertical gravity of the ball. As a result it will be launched upwards, but then fall due to the effects of gravity pulling it down. This kind of functionality is just the tip of the iceberg -- there are various functions and variables that can help you manipulate the physics objects. Check out the official physics documentation and see the huge collection of examples using the Arcade and P2 physics systems. Compare your code You can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: Next steps Now we can move to the next lesson and see how to make the ball bounce off the walls. << PreviousNext >> ...
Randomizing gameplay - Game development
ou could expand our little game, to get you started: Add a second ball or paddle. Change the color of the background on every hit. Change the images and use your own. Grant extra bonus points if bricks are destroyed rapidly, several-in-a-row (or other bonuses of your choosing.) Create levels with different brick layouts. Be sure to check the ever growing list of examples and the official documentation, and visit the HTML5 Gamedevs forums if you ever need any help. You could also go back to this tutorial series' index page. << Previous ...
2D 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. You can check it out on GitHub where it's open sourced, read the online documentation and go through the big collection of examples. The Phaser framework provides you with a set of tools that will speed up development and help handle generic tasks needed to complete the game, so you can focus on the game idea itself. Starting with the project You can see Cyber Orb source code on GitHub. The folder structure is quite straightforward: the starting point is the index.html file...
Visual typescript game engine - Game development
egister etc. Implemented video chat based on webRTC protocol. - Running rtc3 server is also easy : Command 'npm run broadcaster' is not necessary for beginners. Features come with broadcaster: Multiplatform video chat works with other hybrid frameworks or custom implementation throw the native mobile application web control (Chrome implementation usually tested). npm run broadcaster Documentation : Beta version for documentation. API Documentation If you wanna generate doc you will need manual remove the comment from plugin section in webpack.config.js. Restart 'npm run dev' Best way to fully healthy build. HTML/CSS is not prior to this project. If you wanna insert some new HTML page just define it intro webpack.config.js : plugins : [ new HtmlWebpackPlugin({ ...
Accessibility - MDN Web Docs Glossary: Definitions of Web-related terms
for keeping a website usable despite physical and technical restrictions. ...
Base64 - MDN Web Docs Glossary: Definitions of Web-related terms
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 be passed binary data, and will throw an exception if the given string contains any characters whose UTF-16 representation occupies more than one byte. For more details, see the documentation for btoa(). Encoded size increase Each Base64 digit represents exactly 6 bits of data. So, three 8-bits bytes of the input string/binary file (3x8 bits = 24 bits) can be represented by four 6-bit Base64 digits (4x6 = 24 bits). This means that the Base64 version of a string or file will be at most 133% the size of its source (a ~33% increase). The increase may be larger if the encoded data...
BiDi - MDN Web Docs Glossary: Definitions of Web-related terms
Even when both directionalities occur in the same paragraph, the text in each language must appear in its proper directionality. ...
Breadcrumb - MDN Web Docs Glossary: Definitions of Web-related terms
A breadcrumb, or breadcrumb trail, is a navigational aid that is typically placed between a site's header and the main content, displaying either a hierarchy of the current page in relation to the the site's structure, from top level to current page, or a list of the links the user followed to get to the current page, in the order visited. A location breadcrumb for this document might look something like this: MDN > Glossary > Breadcrumb Breadcrumb trails enable users to be aware of their location within a website. This type of navigation, if done correctly, helps users know where they are in a site and how they got there. They can also help a user get back to where they were before and can reduce the number of clicks needed to get to a higher-level page. ...
Browsing context - MDN Web Docs Glossary: Definitions of Web-related terms
In modern browsers, it usually is a tab, but can be a window or even only parts of a page, like a frame or an iframe. Each browsing context has a specific origin, the origin of the active document and a history that memorize all the displayed documents, in order. Communication between browsing context is severaly constrained. ...
CSP - MDN Web Docs Glossary: Definitions of Web-related terms
A CSP (Content Security Policy) is used to detect and mitigate certain types of website related attacks like XSS and data injections. The implementation is based on an HTTP header called Content-Security-Policy. Learn more General knowledge Content Security Policy on Wikipedia Technical knowledge Content Security Policy documentation on MDN ...
CSS Object Model (CSSOM) - MDN Web Docs Glossary: Definitions of Web-related terms
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. ...
Selector (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
The matching elements will have the rule's specified style applied to them. ...
Canvas - MDN Web Docs Glossary: Definitions of Web-related terms
images. It is a low level, procedural model that updates a bitmap and does not have a built-in scene graph. ...
Cookie - MDN Web Docs Glossary: Definitions of Web-related terms
eft on a visitor's computer by a website, via a web browser. Cookies are used to personalize a user's web experience with a website. It may contain the user's preferences or inputs when accessing that website. A user can customize their web browser to accept, reject, or delete cookies. Cookies can be set and modified at the server level using the Set-Cookie HTTP header, or with JavaScript using document.cookie. Learn more General Knowledge HTTP cookie on Wikipedia ...
Doctype - MDN Web Docs Glossary: Definitions of Web-related terms
In HTML, the doctype is the required "<!DOCTYPE html>" preamble found at the top of all documents. Its sole purpose is to prevent a browser from switching into so-called "quirks mode" when rendering a document; that is, the "<!DOCTYPE html>" doctype ensures that the browser makes a best-effort attempt at following the relevant specifications, rather than using a different rendering mode that is incompatible with some specifications. Learn more General Knowledge Definition of the DOCTYPE in the HTML specification Quirks Mode and Standards Mode Technical reference Document.doctype, a JavaScript method that returns the doctype ...
Element - MDN Web Docs Glossary: Definitions of Web-related terms
An element is a part of a webpage. In XML and HTML, an element may contain a data item or a chunk of text or an image, or perhaps nothing. A typical element includes an opening tag with some attributes, enclosed text content, and a closing tag. Elements and tags are not the same things. Tags begin or end an element in source code, whereas elements are part of the DOM, the document model for displaying the page in the browser. ...
Expando - MDN Web Docs Glossary: Definitions of Web-related terms
...
Falsy - MDN Web Docs Glossary: Definitions of Web-related terms
negative zero 0n BigInt, 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. Examples Examples of falsy values in JavaScript (which are coerced to false in Boolean contexts, and thus bypass the if block): if (false) if (null) if (undefined) if (0) if (-0) if (0n) if (NaN) if ("") The logical AND operator, && If the first object is falsy, it returns that object false && "dog" // ? false 0 && "dog" // ? 0 Specifications ...
Gecko - MDN Web Docs Glossary: Definitions of Web-related terms
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 MDN ...
Git - MDN Web Docs Glossary: Definitions of Web-related terms
uted Source Code Management (SCM) system. ...
Grid Axis - MDN Web Docs Glossary: Definitions of Web-related terms
laying out blocks of text. If you have two paragraphs and are working in a right to left, top to bottom language they lay out one below the other, on the block axis. The inline or row axis runs across the Block Axis and is the direction along which regular text flows. These are our rows in CSS Grid Layout. The physical direction of these axes can change according to the writing mode of the document. Learn More Further reading CSS Grid Layout Guide: Basic concepts of grid layout CSS Grid Layout Guide: Box alignment in Grid Layout CSS Grid Layout Guide: Grids, logical values and writing modes ...
Grid Lines - MDN Web Docs Glossary: Definitions of Web-related terms
div>Two</div> <div>Three</div> <div>Four</div> <div>Five</div> </div> .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: 100px 100px; } Lines can be addressed using their line number. In a left-to-right language such as English, column line 1 will be on the left of the grid, row line 1 on the top. Lines numbers respect the writing mode of the document and so in a right-to-left language for example, column line 1 will be on the right of the grid. The image below shows the line numbers of the grid, assuming the language is left-to-right. Lines are also created in the implicit grid when implicit tracks are created to hold content positioned outside of the explicit grid, however these lines cannot be addressed by a number. Placing items onto ...
HTML5 - MDN Web Docs Glossary: Definitions of Web-related terms
The latest stable release of HTML, HTML5 takes HTML from a simple markup for structuring a document to a full app development platform. Among other features, HTML5 includes new elements and JavaScript APIs to enhance storage, multimedia, and hardware access. Learn more our HTML5 guide ...
Head - MDN Web Docs Glossary: Definitions of Web-related terms
The Head is the part of an HTML document that contains metadata about that document, such as author, description, and links to CSS or JavaScript files that should be applied to the HTML. Learn more HTML head <head> element reference on MDN The HTML <head> on the MDN Learning Area ...
Hyperlink - MDN Web Docs Glossary: Definitions of Web-related terms
Hyperlinks connect webpages or data items to one another. ...
I18N - MDN Web Docs Glossary: Definitions of Web-related terms
i18n (from "internationalization", a 20-letter word) is the best practice that enables products or services to be readily adapted to any target culture. Internationalization is the design and development of a product, application or document content that enables easy localization for target audiences that vary in culture, region, or language. (The W3C definition) Among other things, i18n requires support for multiple character sets (usually via Unicode) units of measure (currency, ?C/?F, km/miles, etc.) time and date formats keyboard layouts text directions Learn more General knowledge i18n on Wikipedia Technical reference i18n on W3C i18n on gala-global.org Learn about it i18n material on i18nguy.com ...
Layout viewport - MDN Web Docs Glossary: Definitions of Web-related terms
The layout viewport is the viewport into which the browser draws a web page. Essentially, it represents what is available to be seen, while the visual viewport represents what is currently visible on the user's display device. This becomes important, for example, on mobile devices, where a pinching gesture can usually be used to zoom in and out on a site's contents. The rendered document doesn't change in any way, so the layout viewport remains the same as the user adjusts the zoom level. Instead, the visual viewport is updated to indicate the area of the page that they can see. Learn more General knowledge Visual Viewport API Viewport on Wikipedia A tale of two viewports (Quirksmode) Viewport in the MDN Glossary Visual viewport in the MDN Glossary ...
mime - MDN Web Docs Glossary: Definitions of Web-related terms
MIME "Multipurpose internet mail extensions" is a standard to describe documents in other forms beside ASCII text, e.g. audio, video and images. Initially used for E-Mail attachments, it has become the de facto standard to define types of documents anywhere. See also MIME-Type Learn more General knowledge MIME on Wikipedia ...
Media (Audio-visual presentation) - MDN Web Docs Glossary: Definitions of Web-related terms
r other still images. ...
Media (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
In the context of CSS (Cascading Style Sheets), the term media refers to the destination to which the document is to be drawn by the rendering engine. Typically, this is a screen--but it may also be a printer, a speech synthesizer, Braille display, or another type of device. CSS offers several features that allow you to tweak your document's styles--or even offer different styles--according to the media type (such as screen or print, to name two) or media capabilities (such as width, resolution, or other values) of the viewer's device. Learn more General knowledge Using media queries Technical reference Media queries Define a set of characteristics or parameters required to apply the CSS styles that are specified within the curly braces of the media query; for example: only app...
Media - MDN Web Docs Glossary: Definitions of Web-related terms
context. Media (Audio-visual presentation) The term media (more accurately, multimedia) refers to audio, video, or combined audio-visual material such as music, recorded speech, movies, TV shows, or any other form of content that is presented over a period of time. Media (CSS) In the context of CSS (Cascading Style Sheets), the term media refers to the destination to which the document is to be drawn by the rendering engine. Learn more Media on Wikipedia ...
Metadata - MDN Web Docs Glossary: Definitions of Web-related terms
Metadata is -- in its very simplest definition -- data that describes data. For example, an HTML document is data, but HTML can also contain metadata in its <head> element that describes the document -- for example who wrote it, and its summary. Learn more General knowledge metadata on Wikipedia HTML metadata The <meta> element on MDN ...
Mozilla Firefox - MDN Web Docs Glossary: Definitions of Web-related terms
s overseen by the Mozilla Corporation. ...
Navigation directive - MDN Web Docs Glossary: Definitions of Web-related terms
m to, for example. Navigation directives don't fall back to the default-src directive. List of CSP Navigation directives form-action Restricts the URLs which can be used as the target of a form submissions from a given context. frame-ancestors Specifies valid parents that may embed a page using <frame>, <iframe>, <object>, <embed>, or <applet>. navigate-to Restricts the URLs to which a document can initiate navigation by any means, including <form> (if form-action is not specified), <a>, window.location, window.open, etc. Learn more https://www.w3.org/TR/CSP/#directives-navigation Other kinds of directives: Fetch directive Document directive Reporting directive block-all-mixed-content upgrade-insecure-requests require-sri-for trusted-types Content-Se...
Node (DOM) - MDN Web Docs Glossary: Definitions of Web-related terms
Glossary › Node › DOM
In the context of the DOM, a node is a single point in the node tree. Various things that are nodes are the document itself, elements, text, and comments. Learn more Technical reference The node tree WHATWG spec ...
Node.js - MDN Web Docs Glossary: Definitions of Web-related terms
Node.js is a cross-platform JavaScript runtime environment that allows developers to build server-side and network applications with JavaScript. Learn more General Knowledge Node.js on Wikipedia Node.js website Technical information API reference documentation Tutorials ...
Node - MDN Web Docs Glossary: Definitions of Web-related terms
The term node can have several meanings depending on the context. It may refer to: Node (DOM) In the context of the DOM, a node is a single point in the node tree. Various things that are nodes are the document itself, elements, text, and comments. Node (networking) In networking, a node is a connection point in the network. In physical networks, a node is usually a device, like a computer or a router. Another use of the word is when talking about Node.js ...
Parse - MDN Web Docs Glossary: Definitions of Web-related terms
Parsing means analyzing and converting a program into an internal format that a runtime environment can actually run, for example the JavaScript engine inside browsers. 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. Parsing can continue when a CSS file is encountered, but <script> tags--particularly those without an async or defer attribute--blocks rendering, and pauses pars...
Perceived performance - MDN Web Docs Glossary: Definitions of Web-related terms
sources, and the final paint. While increased performance generally increases perceived performance, there are some techniques that can be used to increase perceived performance while marginally decreasing actual performance. There are front end optimization techniques that can improve perceived performance, such as adding the defer or async attribute to scripts, or placing scripts at the end of documents, and placing CSS in the head of documents. Learn more perceived performance ...
Plaintext - MDN Web Docs Glossary: Definitions of Web-related terms
Plaintext refers to information that is being used as an input to an encryption algorithm, or to ciphertext that has been decrypted. It is frequently used interchangeably with the term cleartext, which more loosely refers to any information, such as a text document, image, etc., that has not been encrypted and can be read by a human or computer without additional processing. ...
Pseudo-element - MDN Web Docs Glossary: Definitions of Web-related terms
For example, rather than putting the first letter of each paragraph in its own element, you can style them all with p::first-letter. ...
QUIC - MDN Web Docs Glossary: Definitions of Web-related terms
port the semantics of HTTP/2. ...
RSS - MDN Web Docs Glossary: Definitions of Web-related terms
RSS (Really Simple Syndication) refers to several XML document formats designed for publishing site updates. When you subscribe to a website's RSS feed, the website sends information and updates to your RSS reader in an RSS document called a feed, so you don't need to check all your favorite websites manually. Learn more General knowledge RSS on Wikipedia Technical reference Latest specification ...
RTP (Real-time Transport Protocol) and SRTP (Secure RTP) - MDN Web Docs Glossary: Definitions of Web-related terms
nologies. ...
RTSP: Real-time streaming protocol - MDN Web Docs Glossary: Definitions of Web-related terms
of a media should occur between a server and a client. ...
Ruby - MDN Web Docs Glossary: Definitions of Web-related terms
Ruby is an open-source programming language. In a Web context, Ruby is often used server-side with the Ruby On Rails (ROR) framework to produce websites/apps. Ruby is also a method for annotating east Asian text in HTML documents to provide pronunciation information; see the <ruby> element. Learn More General knowledge Ruby on Wikipedia Technical reference Ruby's official web site Ruby On Rails' official web site ...
SPA (Single-page application) - MDN Web Docs Glossary: Definitions of Web-related terms
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. ...
Same-origin policy - MDN Web Docs Glossary: Definitions of Web-related terms
The same-origin policy is a critical security mechanism that restricts how a document or script loaded from one origin can interact with a resource from another origin. It helps isolate potentially malicious documents, reducing possible attack vectors. ...
Script-supporting element - MDN Web Docs Glossary: Definitions of Web-related terms
These elements may be important, but do not affect the displayed page unless the page's scripts explicitly cause them to do so. There are only two script-supporting elements: <script> and <template>. Technical reference To learn more, see Script-supporting elements in Kinds of HTML content. ...
Scrollport - MDN Web Docs Glossary: Definitions of Web-related terms
A scroll container is created by applying overflow: scroll to a container, or overflow: auto when there is enough content to cause overflow. ...
Signature (security) - MDN Web Docs Glossary: Definitions of Web-related terms
rates a digital signature linked to the signing entity, using the entity's private key. On receiving the message, the verification process authenticates the sender - uses the sender's public key to decrypt the signature and recover the hash, which can only be created with the sender's private key, and checks message integrity - compares the hash with a newly calculated one from the received document (the two hashes will differ if the document has been tampered with) The system fails if the private key is compromised or the recipient is deceitfully given the wrong public key. Learn more General knowledge Digital signature on Wikipedia See digest, encryption ...
Slug - MDN Web Docs Glossary: Definitions of Web-related terms
A Slug is the unique identifying part of a web address, typically at the end of the URL. In the context of MDN, it is the portion of the URL following "<locale>/docs/". It may also just be the final component when a new document is created under a parent document; for example, this page's slug is Glossary/Slug . ...
Specification - MDN Web Docs Glossary: Definitions of Web-related terms
A specification is a document that lays out in detail what functionality or attributes a product must include before delivery. In the context of describing the Web, the term "specification" (often shortened to simply "spec") generally means a document describing a language, technology, or API which makes up the complete set of open Web technologies. Learn more General knowledge Specification on Wikipedia Technical reference Open Web platform specifications ...
Style origin - MDN Web Docs Glossary: Definitions of Web-related terms
ng elements. User origin The user origin is the style origin containing any CSS that the user of the web browser has added. These may be from adding styles using a developer tool or from a browser extension that automatically applies custom styles to content, such as Stylus or Stylish. Author origin The author origin is the style origin which contains all of the styles which are part of the document, whether embedded within the HTML or loaded from an external stylesheet file. The style origins are used to determine where to stop rolling back (or backtracking through) the cascade of styles that have been applied to an element when removing styles, such as when using the unset or revert keywords. Learn more Technical information CSS Cascading and Inheritance: Cascading Origins ...
Syntax - MDN Web Docs Glossary: Definitions of Web-related terms
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, otherwise a syntax error occurs. Even small errors, like a missing parenthesis, can stop source code from compiling successfully. Frameworks are said to have a "clean" syntax if they ...
World Wide Web - MDN Web Docs Glossary: Definitions of Web-related terms
t.hypertext newsgroup, marking the moment the Web was first made public. The system we know today as "the Web" consists of several components: The HTTP protocol governs data transfer between a server and a client. To access a Web component, a client supplies a unique universal identifier, called a URL (uniform resource location) or URI (uniform resource identifier) (formally called Universal Document Identifier (UDI)). HTML (hypertext markup language) is the most common format for publishing web documents. Linking, or connecting resources through hyperlinks, is a defining concept of the Web, aiding its identity as a collection of connected documents. Soon after inventing the Web, Tim Berners-Lee founded the W3C (World Wide Web Consortium) to standardize and develop the Web further. This c...
XForms - MDN Web Docs Glossary: Definitions of Web-related terms
XForms is a convention for building Web forms and processing form data in the XML format. No major browser supports XForms any longer--we suggest using HTML5 forms instead. Learn more Technical reference XForms documentation on MDN ...
XHR (XMLHttpRequest) - MDN Web Docs Glossary: Definitions of Web-related terms
XMLHttpRequest (XHR) is a JavaScript API to create AJAX requests. Its methods provide the ability to send network requests between the browser and a server. Learn more General knowledge XMLHttpRequest on Wikipedia Synchronous vs. Asynchronous Communications Technical information The XMLHttpRequest object. The documentation on MDN about how to use XMLHttpRequest. ...
XHTML - MDN Web Docs Glossary: Definitions of Web-related terms
Learn more XHTML ...
Character encoding - MDN Web Docs Glossary: Definitions of Web-related terms
d text. A sequence of bytes allows for different textual interpretations. By specifying a particular encoding (such as UTF-8), we specify how the sequence of bytes is to be interpreted. For example, in HTML we normally declare a character encoding of UTF-8, using the following line: <meta charset="utf-8"> This ensures that you can use characters from just about any human language in your HTML document, and they will display reliably. Learn more General knowledge Character encoding on W3C Character encoding on Wikipedia ...
Event - MDN Web Docs Glossary: Definitions of Web-related terms
Events are assets generated by DOM elements, which can be manipulated by a Javascript code. ...
markup - MDN Web Docs Glossary: Definitions of Web-related terms
t of the content. Types of markup language Presentational Markup: Used by traditional word processing sytem with WYSIWYG (what you see it is what you get); this is hidden from human authors, users and editors. Procedural Markup: Combined with text to provide instructions on text processing to programs. This text is visibly manipulated by the author. Descriptive Markup: Labels sections of documents as to how the program should handle them. For example, the HTML <td> defines a cell in a HTML table. ...
Property (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
A CSS property is a characteristic (like color) whose associated value defines one aspect of how the browser should display the element. ...
About Scriptable Interfaces - Interfaces
Interfaces are written in an Interface Description Language. When we label an interface as scriptable, we're saying that components exporting this interface can be referenced (through this interface) from scripts (e.g JavaScript), and that we can write new components implementing the interface using script languages. ...
Test your skills: HTML accessibility - Learn web development
ecreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. HTML accessibility 3 In this task you are required to turn all the information links in the paragraph into good, accessible links. The first two links just go to regular web pages. The third link goes to a PDF, and it's large -- 8MB. The fourth link goes to a Word document, so the user will need some kind of application installed that can handle that. 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. HTML accessibility 4 In our final HTML accessibility task, you are given a simple image gallery, which has some accessibility problems. Can you fix th...
What is accessibility? - Learn web development
There are numerous checklists and sets of guidelines available for basing accessibility tests on, which might seem overwhelming at first glance. Our advice is to familiarize yourself with the basic areas in which you need to take care, as well as understanding the high-level structures of the guidelines that are most relevant to you. For a start, the W3C has published a large and very detailed document that includes very precise, technology-agnostic criteria for accessibility conformance. These are called the Web Content Accessibility Guidelines (WCAG), and they are not a short read by any means. The criteria are split up into four main categories, which specify how implementations can be made perceivable, operable, understandable, and robust. The best place to get a light introduction and star...
A cool-looking box - Learn web development
Make local copies of the starting HTML and CSS -- save them as index.html and style.css in a new directory. Alternatively, you could use a site like JSBin or Glitch to do your assessment. You could paste the HTML and fill in the CSS into one of these online editors. If the online editor you are using doesn't have a separate CSS panel, feel free to put it in a <style> element in the head of the document. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project brief Your task is to create a cool, fancy box and explore the fun we can have with CSS. General tasks Apply the CSS to the HTML. Styling the box We'd like you to style the provided <p>, giving it the following: A reasonable width for a large button, say a...
Cascade and inheritance - Learn web development
all to unset. Try setting the value of all to some of the other available values and observe what the difference is. Understanding the cascade We now understand why a paragraph nested deep in the structure of your HTML is the same color as the CSS applied to the body, and from the introductory lessons we have an understanding of how to change the CSS applied to something at any point in the document -- whether by assigning CSS to an element or creating a class. We will now take a proper look at how the cascade defines which CSS rules apply when more than one thing could style an element. There are three factors to consider, listed here in increasing order of importance. Later ones overrule earlier ones: Source order Specificity Importance We will look at these to see how browsers fig...
Creating fancy letterheaded paper - Learn web development
w directory. Save local copies of the top, bottom and logo images in the same directory as your code files. Alternatively, you could use a site like JSBin or Glitch to do your assessment. You could paste the HTML and fill in the CSS into one of these online editors. If the online editor you are using doesn't have a separate CSS panel, feel free to put it in a <style> element in the head of the document. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project brief You have been given the files needed to create a letterheaded paper template. You just need to put the files together. To get there, you need to: The main letter Apply the CSS to the HTML. Add a background declaration to the letter that: Fixes the t...
Fundamental CSS comprehension - Learn web development
nd combine to answer part of this assessment. Alternatively, you could use a site like JSBin or Glitch to do your assessment. You could paste the HTML and fill in the CSS into one of these online editors, and use this URL to point the <img> element to the image file. If the online editor you are using doesn't have a separate CSS panel, feel free to put it in a <style> element in the head of the document. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project brief You have been provided with some raw HTML and an image, and need to write the necessary CSS to style this into a nifty little online business card, which can perhaps double as a gamer card or social media profile. The following sections describe what you need ...
Handling different text directions - Learn web development
on the page -- either from top-to-bottom, right-to-left, or left-to-right. This then dictates the direction text flows in sentences. Writing modes and block and inline layout We have already discussed block and inline layout, and the fact that some things display as block elements and others as inline elements. As we have seen described above, block and inline is tied to the writing mode of the document, and not the physical screen. Blocks are only displayed from the top to the bottom of the page if you are using a writing mode that displays text horizontally, such as English. If we look at an example this will become clearer. In this next example I have two boxes that contain a heading and a paragraph. The first uses writing-mode: horizontal-tb, a writing mode that is written horizontally and ...
Organizing your CSS - Learn web development
u, or you can install command line tools to help. The most popular pre-processor is Sass. This is not a Sass tutorial, so I will briefly explain a couple of the things that Sass can do, which are really helpful in terms of organisation, even if you don't use any of the other Sass features. If you want to learn a lot more about Sass, start with the Sass basics article, then move on to their other documentation. Defining variables CSS now has native custom properties, making this feature increasingly less important, however one of the reasons you might use Sass is to be able to define all of the colors and fonts used in a project as settings, then use that variable around the project. This means that if you realise you have used the wrong shade of blue, you only need change it in one place. If w...
Attribute selectors - Learn web development
"a"] matches any attribute value where a appears anywhere in the string, so it matches all of our list items. Case-sensitivity If you want to match attribute values case-insensitively you can use the value i before the closing bracket. This flag tells the browser to match ASCII characters case-insensitively. Without the flag the values will be matched according to the case-sensitivity of the document language -- in HTML's case it will be case sensitive. In the example below, the first selector will match a value that begins with a -- it only matches the first list item because the other two list items start with an uppercase A. The second selector uses the case-insensitive flag and so matches all of the list items. Note: There is also a newer value s, which will force case-sensitive matc...
Sizing items in CSS - Learn web development
n the example, resize the browser window, and observe what happens to the size of the box and text. Sizing things according to the viewport can be useful in your designs. For example, if you want a full-page hero section to show before the rest of your content, making that part of your page 100vh high will push the rest of the content below the viewport, meaning that it will only appear once the document is scrolled. Test your skills! We have covered a lot in 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: Sizing. Summary This lesson has given you a rundown of some key issues that you might run into when sizing things on the web. When you move onto CSS...
Test Your Skills: Fundamental layout comprehension - Learn web development
n the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project Brief You have been provided with some raw HTML, basic CSS, and images -- now you need to create a layout for the design, which should look just like the image below. Basic Setup You can download the HTML, CSS, and a set of six images here. Save the HTML document and stylesheet into a directory on your computer, and add the images into a folder named images. Opening the index.html file in a browser should give you a page with basic styling but no layout, which should look something like the image seen below. This starting point has all of the content of your layout as displayed by the browser in normal flow. If you don't want to work locally then using...
Grids - Learn web development
ating as many 200 pixel columns as will fit into the container, then sharing whatever space is leftover between all of the columns -- the maximum is 1fr which, as we already know, distributes space evenly between tracks. Line-based placement We now move on from creating a grid, to placing things on the grid. Our grid always has lines, which lines start at 1 and relate to the Writing Mode of the document. Therefore in English, column line 1 is on the left hand side of the grid and row line 1 at the top. In Arabic column line 1 would be on the right hand side, as Arabic is written right to left. We can place things according to these lines by specifying the start and end line. We do this using the following properties: grid-column-start grid-column-end grid-row-start grid-row-end These pr...
CSS layout - Learn web development
then test your grid skills before moving on. Floats Originally for floating images inside blocks of text, the float property became one of the most commonly used tools for creating multiple column layouts on webpages. With the advent of Flexbox and Grid it has now returned to its original purpose, as this article explains. Positioning Positioning allows you to take elements out of the normal document layout flow, and make them behave differently, for example sitting on top of one another, or always remaining in the same place inside the browser viewport. This article explains the different position values, and how to use them. Multiple-column layout The multiple-column layout specification gives you a method of laying content out in columns, as you might see in a newspaper. This article exp...
Using your new knowledge - Learn web development
Previous Overview: First steps With the things you have learned in the last few lessons you should find that you can format simple text documents using CSS, to add your own style to them. This assessment gives you a chance to do that. Prerequisites: Before attempting this assessment you should have worked through the rest of the CSS basics module, and also have an understanding of HTML basics (study Introduction to HTML). Objective: To have a play with some CSS and test your new-found knowledge. Starting point You can work in the live editor below, or you can download the starting point to work with in your own editor. This is a single page with the HTML, plus the starting point CSS in the head of the document. If you prefer you could move this CSS t...
Using CSS generated content - Learn web development
This article describes some ways in which you can use CSS to add content when a document is displayed. You modify your stylesheet to add text content or images. One of the important advantages of CSS is that it helps you to separate a document's style from its content. However, there are situations where it makes sense to specify certain content as part of the stylesheet, not as part of the document. You can specify text or image content within a stylesheet when that content is closely linked to the document's structure. Note: Content specified in a stylesheet does not become part of the DOM. Specifying content in a stylesheet can cause complications. For example, you might have different language versions of your document that share a stylesheet. If you specify content in your sty...
Styling links - Learn web development
{ } a:hover { } a:active { }</textarea> <h2>Output</h2> <div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></div> <div class="controls"> <input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;"> <input id="solution" type="button" value="Show solution" style="margin: 10px 0 0 10px;"> </div> </div> var htmlInput = document.querySelector(".html-input"); var cssInput = document.querySelector(".css-input"); var reset = document.getElementById("reset"); var htmlCode = htmlInput.value; var cssCode = cssInput.value; var output = document.querySelector(".output"); var solution = document.getElementById("solution"); var styleElem = document.createElement('style'); var headElem = document.querySelector('head'); headElem.ap...
Styling lists - Learn web development
x solid #0095dd;"></textarea> <h2>Output</h2> <div class="output" style="width: 90%;height: 12em;padding: 10px;border: 1px solid #0095dd;overflow: auto;"></div> <div class="controls"> <input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;"> <input id="solution" type="button" value="Show solution" style="margin: 10px 0 0 10px;"> </div> </div> var htmlInput = document.querySelector(".html-input"); var cssInput = document.querySelector(".css-input"); var reset = document.getElementById("reset"); var htmlCode = htmlInput.value; var cssCode = cssInput.value; var output = document.querySelector(".output"); var solution = document.getElementById("solution"); var styleElem = document.createElement('style'); var headElem = document.querySelector('head'); headElem.ap...
Typesetting a community school homepage - Learn web development
rnal link icon. Make a copy of them on your local computer. Alternatively, you could use a site like JSBin or Glitch to do your assessment. You could paste the HTML and fill in the CSS into one of these online editors, and use this URL to point the background image. If the online editor you are using doesn't have a separate CSS panel, feel free to put it in a <style> element in the head of the document. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project brief You have been provided with some raw HTML for the homepage of an imaginary community college, plus some CSS that styles the page into a three column layout and provides some other rudimentary styling. You are to write your CSS additions below the comment at th...
The HTML5 input types - Learn web development
rticle). 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 current value of the input. Finally, an event listener is set t...
Example 2 - Learn web development
: 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>Apple</option> </select> <div class="select"> <span class="value">Cher...
Example 3 - Learn web development
ptList'); optList.classList.toggle('hidden'); } function highlightOption(select, option) { var optionList = select.querySelectorAll('.option'); optionList.forEach(function (other) { other.classList.remove('highlight'); }); option.classList.add('highlight'); }; // ------------- // // Event binding // // ------------- // window.addEventListener("load", function () { var form = document.querySelector('form'); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener('load', function () { var selectList = document.querySelectorAll('.select'); selectList.forEach(function (select) { var optionList = select.querySelectorAll('.option'); optionList.forEach(function (option) { option.addEventListener('mouseover', function ()...
Example 5 - Learn web development
selected', 'true'); nativeWidget.selectedIndex = index; value.innerHTML = optionList[index].innerHTML; highlightOption(select, optionList[index]); }; function getIndex(select) { var nativeWidget = select.previousElementSibling; return nativeWidget.selectedIndex; }; // ------------- // // Event binding // // ------------- // window.addEventListener("load", function () { var form = document.querySelector('form'); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener('load', function () { var selectList = document.querySelectorAll('.select'); selectList.forEach(function (select) { var optionList = select.querySelectorAll('.option'), selectedIndex = getIndex(select); select.tabIndex = 0; select.previousElementSibl...
How the Web works - Learn web development
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 server that the website lives on (you find the address of the shop). The browser sends an HTTP request message to the server, asking it to send a copy of the website to the client (yo...
Installing basic software - Learn web development
people, but some of you are reading this article on your phone or a library computer. For serious web development, it's better to invest in a desktop or laptop computer running Windows, macOS or Linux. A text editor, to write code in. This could be a text editor (e.g. Visual Studio Code, Notepad++, Sublime Text, Atom, GNU Emacs, or VIM), or a hybrid editor (e.g. Dreamweaver or WebStorm). Office document editors are not suitable for this use, as they rely on hidden elements that interfere with the rendering engines used by web browsers. Web browsers, to test code in. Currently, the most-used browsers are Firefox, Chrome, Opera, Safari, Internet Explorer and Microsoft Edge. You should also test how your site performs on mobile devices and on any old browsers your target audience may still be usin...
Publishing your website - Learn web development
tting started with the web Next Once you finish writing the code and organizing the files that make up your website, you need to put it all online so people can find it. This article explains how to get your simple sample code online with little effort. What are the options? Publishing a website is a complex topic because there are many ways to go about it. This article doesn't attempt to document all the possible methods. Instead, it explains the advantages and disadvantages of three approaches that are practical for beginners. Then it steps through one method that can work right away for many readers. Getting hosting and a domain name To have more control over content and website appearance, most people choose to buy web hosting and a domain name: Web hosting is rented file space on...
Add a hitmap on top of an image - Learn web development
Objective: Learn how to make different regions of one image link to different pages. This article discusses client-side image maps only. Do not use server-side image maps, which require the user to have a mouse. Image maps, and their drawbacks When you nest an image inside <a>, the entire image links to one webpage. ...
Use JavaScript within a webpage - Learn web development
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. ...
Using data attributes - Learn web development
hese 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 to camelCase). const article = document.querySelector('#electric-cars'); article.dataset.columns // "3" article.dataset.indexNumber // "12314" article.dataset.parent // "cars" Each property is a string and can be read and written. In the above case setting article.dataset.columns = 5 would change that attribute to "5". CSS access Note that, as data attributes are plain HTML attributes, you can even access them from CSS. For example...
Responsive images - Learn web development
w, 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, you can use Firefox DevTools'...
HTML table advanced features and accessibility - Learn web development
at adding the <tfoot> element has caused the "SUM" row to go down to the bottom of the table. Next, add a colspan attribute to make the "SUM" cell span across the first four columns, so the actual number appears at the bottom of the "Cost" column. Let's add some simple extra styling to the table, to give you an idea of how useful these elements are for applying CSS. Inside the head of your HTML document, you'll see an empty <style> element. Inside this element, add the following lines of CSS code: tbody { font-size: 95%; font-style: italic; } tfoot { font-weight: bold; } Save and refresh, and have a look at the result. If the <tbody> and <tfoot> elements weren't in place, you'd have to write much more complicated selectors/rules to apply the same styling. Note: We don't expect yo...
HTML table basics - Learn web development
Learn › HTML › Tables › Basics
set of data made up of rows and columns (tabular data). A table allows you to quickly and easily look up values that indicate some kind of connection between different types of data, for example a person and their age, or a day of the week, or the timetable for a local swimming pool. Tables are very commonly used in human society, and have been for a long time, as evidenced by this US Census document from 1800: It is therefore no wonder that the creators of HTML provided a means by which to structure and present tabular data on the web. How does a table work? The point of a table is that it is rigid. Information is easily interpreted by making visual associations between row and column headers. Look at the table below for example and find a Jovian gas giant with 62 moons. You can find th...
Functions — reusable blocks of code - Learn web development
t('hello'); } But you can also create a function that doesn't have a name: function() { alert('hello'); } This is called an anonymous function -- it has no name! It also won't do anything on its own. You generally use an anonymous function along with an event handler, for example the following would run the code inside the function whenever the associated button is clicked: const myButton = document.querySelector('button'); myButton.onclick = function() { alert('hello'); } The above example would require there to be a <button> element available on the page to select and click. You've already seen this structure a few times throughout the course, and you'll learn more about and see it in use in the next article. You can also assign an anonymous function to be the value of a variable, for...
Test your skills: Events - Learn web development
ents, 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. 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 yo...
Test your skills: Functions - Learn web development
ents, 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. Functions 1 For the first task, you have to create a simple function -- chooseName() -- that prints a random name from the provided array (names) to the provided paragraph (para), and then run it once. 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. Functions 2 For ...
Test your skills: Loops - Learn web development
ents, 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 provided myArray and prints them out on the screen inside list items (i.e., <li> elements), which are appended to the provided list. Download the starting point for this task to work in your own editor or in an online editor. Loops 2 In this next task, we want you...
Fetching data from the server - Learn web development
you may well recognize) via XHR when it's selected in the drop-down menu. Just inside the <script> element, add the following code. This stores a reference to the <select> and <pre> elements in constants and defines an onchange event handler function so that when the select's value is changed, its value is passed to an invoked function updateDisplay() as a parameter. const verseChoose = document.querySelector('select'); const poemDisplay = document.querySelector('pre'); verseChoose.onchange = function() { const verse = verseChoose.value; updateDisplay(verse); }; Let's define our updateDisplay() function. First of all, put the following beneath your previous code block -- this is the empty shell of the function. Note: Steps 4 - 9 will all be performed within this function. f...
Silly story generator - Learn web development
nsure whether the JavaScript is applied to your HTML properly, try removing everything else from the JavaScript file temporarily, adding in a simple bit of JavaScript that you know will create an obvious effect, then saving and refreshing. The following for example turns the background of the <html> element red -- so the entire browser window should go red if the JavaScript is applied properly: document.querySelector('html').style.backgroundColor = 'red'; Math.round() is a built-in JavaScript method that simply rounds the result of a calculation to the nearest whole number. There are three instances of strings that need to be replaced. You may repeat the replace() method multiple times, or you can use regular expressions. For instance, let text = 'I am the biggest lover, I love my love'; tex...
Handling text — strings in JavaScript - Learn web development
of variables and actual strings. Try this: let response = one + 'I am fine -- ' + two; response; Note: When you enter an actual string in your code, enclosed in single or double quotes, it is called a string literal. Concatenation in context Let's have a look at concatenation being used in action -- here's an example from earlier in the course: <button>Press me</button> const button = document.querySelector('button'); button.onclick = function() { let name = prompt('What is your name?'); alert('Hello ' + name + ', nice to see you!'); } Here we're using a window.prompt() function in line 4, which asks the user to answer a question via a popup dialog box then stores the text they enter inside a given variable -- in this case name. We then use a window.alert() function in line 5 t...
JavaScript object basics - Learn web development
albeit more complex ones than in our own basic custom examples. So when you used string methods like: myString.split(','); You were using a method available on an instance of the String class. Every time you create a string in your code, that string is automatically created as an instance of String, and therefore has several common methods and properties available on it. When you accessed the document object model using lines like this: const myDiv = document.createElement('div'); const myVideo = document.querySelector('video'); You were using methods available on an instance of the Document class. For each webpage loaded, an instance of Document is created, called document, which represents the entire page's structure, content, and other features such as its URL. Again, this means that it h...
CSS performance optimization - Learn web development
g a blank screen, with a trade-off being a flash of unstyled text. @font-face { font-family: someFont; src: url(/path/to/fonts/someFont.woff) format('woff'); font-weight: 400; font-style: normal; font-display: fallback; } The contain property The contain CSS property allows an author to indicate that an element and its contents are, as much as possible, independent of the rest of 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 per...
Web performance resources - Learn web development
ou do, have a backup plan for SEO (e.g render full page for bot traffic); for example, by using the loading attribute on the <img> element It is also crucial to realize what is really important to your users. It might not be absolute timing, but user perception. Quick Wins CSS Web performance is all about user experience and perceived 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 traditi...
Introduction to the server side - Learn web development
hich could then be displayed by the web browser. Static sites The diagram below shows a basic web server architecture for a static site (a static site is one that returns the same hard-coded content from the server whenever a particular resource is requested). When a user wants to navigate to a page, the browser sends an HTTP "GET" request specifying its URL. The server retrieves the requested document from its file system and returns an HTTP response containing the document and a success status (usually 200 OK). If the file cannot be retrieved for some reason, an error status is returned (see client error responses and server error responses). Dynamic sites A dynamic website is one where some of the response content is generated dynamically, only when needed. On a dynamic website HTML page...
Framework main features - Learn web development
text after being clicked 0, 1, and 2 times: import React from "react"; import { render, fireEvent } from "@testing-library/react"; import "@testing-library/jest-dom/extend-expect"; import CounterButton from "./CounterButton"; it("renders a semantic with an initial state of 0", () => { const { getByRole } = render(<CounterButton />); const btn = getByRole("button"); expect(btn).toBeInTheDocument(); expect(btn).toHaveTextContent("Clicked 0 times"); }); it("Increments the count when clicked", () => { const { getByRole } = render(<CounterButton />); const btn = getByRole("button"); fireEvent.click(btn); expect(btn).toHaveTextContent("Clicked 1 times"); fireEvent.click(btn); expect(btn).toHaveTextContent("Clicked 2 times"); }); Summary At this point you should have more of...
React interactivity: Events and state - Learn web development
edge 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. ...
React resources - Learn web development
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 to read and update the browser's location, and render certain user interfaces. This is called client-side routing. It's possible to create many unique routes for your application (such as...
Starting our Svelte Todo list app - Learn web development
this case we have a name prop being specified when we instantiate the App component inside src/main.js, which isn't used inside App. The console should currently give you a message along the lines of "<App> was created with unknown prop 'name'". To get rid of this, remove the name prop from src/main.js; it should now look like so: import App from './App.svelte' const app = new App({ target: document.body }) export default app Now if you check your testing server URL you'll see our Todos.svelte component being rendered: Adding static markup For the moment we will start with a static markup representation of our app, so you can see what it will look like. Copy and paste the following into our Todos.svelte component file, replacing the existing content: <!-- Todos.svelte --> <div clas...
TypeScript support in Svelte - Learn web development
ge used on GitHub. According to StackOverflow's 2019 Developer Survey it is the third most loved language, right behind Rust and Python. So TypeScript is going through a great phase of adoption. TypeScript's main advantages are: Early spotted bugs: The compiler checks types at compile time and provides error reporting. Readability: Static typing gives the code more structure, making it self-documenting and more readable. Rich IDE support: Type information allows code editors and IDEs to offer features like code navigation, autocompletion, and smarter hints. Safer refactoring: Types allows IDEs to know more about your code, and assist you while refactoring large portions of your code base. Type inference: Enables you to take advantage of many TypeScript features even without declaring vari...
Deployment and next steps - Learn web development
lte-todo/. You can check your page's URL in GitLab's UI -- see the Settings > Pages menu option. With this configuration, whenever you push changes to the GitLab repo, the application will be automatically rebuilt and deployed to GitLab Pages. Learning more about Svelte In this section we'll give you some resources and projects to go and check out, to take your Svelte learning further. Svelte documentation To go further and learn more about Svelte, you should definitely visit the Svelte homepage. There you'll find many articles explaining Svelte's philosophy. If you haven't already done it, make sure you go through the Svelte interactive tutorial. We already covered most of its content, so it won't take you much time to complete it -- you should consider it as practise! You can also consult ...
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
. Note: Svelte allows us to specify different options that affect how the compiler works. The <svelte:options immutable={true}/> option tells the compiler that you promise not to mutate any objects. This allows it to be less conservative about checking whether values have changed and generate simpler and more performant code. For more information on <svelte:options...>, check the Svelte options documentation. All of these solutions involve an assignment in which the updated variable is on the left side of the equation. Any of this techniques will allow Svelte to notice that our todos array has been modified. Choose one, and update your checkAllTodos() function as required. Now you should be able to check and uncheck all your todos at once. Try it! Finishing our MoreActions component We will...
Focus management with Vue refs - Learn web development
ory. Any updates are first performed on the in-memory nodes, and then all the changes that need to be made to the actual nodes on the page are synced in a batch. Since reading and writing actual DOM nodes is often more expensive than virtual nodes, this can result in better performance. However, it also means you often should not edit your HTML elements directly through native browser APIs (like Document.getElementById) when using frameworks, because it results in the VDOM and real DOM going out of sync. Instead, if you need to access the underlying DOM nodes (like when setting focus), you can use Vue refs. For custom Vue components, you can also use refs to directly access the internal structure of a child component, however this should be done with caution as it can make code harder to reason ...
Understanding client-side JavaScript frameworks - Learn web development
se and has gained a lot of recent popularity. There is a variety of reasons for this: They are popular choices that will be around for a while -- like with any software tool, it is good to stick with actively-developed choices that are likely to not be discontinued next week, and which will be desirable additions to your skill set when looking for a job. They have strong communities and good documentation. It is very important to be able to get help with learning a complex subject, especially when you are just starting out. We don't have the resources to cover all modern frameworks. That list would be very difficult to keep up-to-date anyway, as new ones appear all the time. As a beginner, trying to choose what to focus on out of the huge number of choices available is a very real problem. ...
Deploying our app - Learn web development
it to GitHub using these commands: git add . git commit -m 'simple netlify test' git push github master You should see your published site update with the change -- this might take a few minutes to publish, so have a little patience. That's it for Netlify. We can optionally change the name of the Netlify project or specify to use our own domain name, which Netlify offers some excellent documentation on. Now for one final link in our tool chain: a test to ensure our code works. Testing Testing itself is a vast subject, even within the realm of front end development. I'll show you how to add an initial test to your project and how to use the test to prevent or to allow the project deployment to happen. When approaching tests there's a good deal of ways to approach the problem: End-...
Chrome Worker Modules
Stack traces Unfortunately, the module loader doesn't play nicely with error stack traces. That is, the following will not show human-readable stacks: try { MyModule.foo(); } catch (ex) { log("Exception raised at " + ex.fileName) log("Stack: " + ex.stack); } Rather, you...
ChromeWorkers and the Chrome worker loader
Note: If you're contributing content to this section, create subpages using the "New sub-page" option in the "This page" menu. Once you've saved your new page, come back to this one and force-refresh this page. ...
Information for users
board support, available accessibility extensions like Fire Vox and other extensions. Assistive Technology Compatibility This is a wiki page which users can edit to provide up to date information on any issues related to compatibility with assistive technologies such as screen readers, screen magnifiers, voice input software and on screen keyboards. Planning Ahead for Accessibility This document is intended to help testers and designers understand and plan what still needs to be added to our UI for full usable accessibility. Please give us feedback on the discussion list! Firefox Accessibility skins and themes At the excellent Access Firefox website, you will find many valuable resources, including a list of Firefox themes that have been specially designed for those with low vision:...
Links and Resources
(WAI). The European Union is looking to base their upcoming accessibility regulations on these guidelines. WAI interest group - Discussion list for standards in web accessibility. Web Accessibility Checklist from IBM. IBM's Java accessibility checklist - guidelines to making Java accessibility. Accessibility Information Resource Center For Developers at Adobe - Flash MX accessibility, PDF document accessibility and ActionScript accessibility. Online Accessibility validators There are now a few available and excellent online accessibility validators which check single webpages according to checkpoints of WCAG guidelines and then reports errors or warnings. WebXACT(TM) from Watchfire(R) Corporation WebXACT(TM) is a free and complete online accessibility validation service that can te...
Accessible Toolkit Checklist
pe but even works on dialogs without Cancel button Alt+space opens window menu with Restore, Move, Size, Minimize, Maximize, Close The Move and Size options must be usable with the arrow keys on the keyboard In windows, initial focus goes to first focusable widget that is not a clickable tabbed property sheet label Making tab order definable. Default tab order should be in document order. Tab order must wrap, not have invisible items in tab order Dynamically added items must not corrupt the tab cycle or make it disorderly Tab cycle must be identical backwards and forwards The F6 and Shift+F6 key combinations should cycle through panes in a window Making focus visible on any widget, and focus must always be visible Shift+F10 or context men...
ZoomText
u will also need to install ZoomText 8.11.3. Happy testing! You may wish to read through the current issues on this page before reporting bugs. Send me email so that I'm aware that you're testing and let me know what bugs you're finding. My email address is aaronleventhal@moonset.net. Issues for AI Squared, from high to low priority DocReader and AppReader don't respect the structure of the document -- no support for columns. ZoomText text to speech doesn't always echo what it should -- need more details from testers. Mozilla issues Cannot tab into frames and iframes. Cannot customize the sidebar with the keyboard only. Comboboxes report incorrect bounds, causing ZoomText tracking to move to the wrong area of the screen. ...
Index
building that source code, where build processes render your extension's code hard to read. 684 Themes Add-ons, Look & Feel, Themes Themes allow you to change the look and feel of the user interface and personalize it to your tastes. Learn how to create and share themes! 685 Obsolete Add-ons, Archive, Look & Feel, Obsolete, Themes This page contains theme documents and resources that we don't expect will ever be updated, but which we're keeping for the time being as potential source material for updated docs. 686 Theme concepts Theme, add-on Themes developed using the WebExtensions API in Firefox enable you to change the look of the browser by adding images to the header area of the Firefox browser; this is the area behind the menu bar...
Obsolete
This page contains theme documents and resources that we don't expect will ever be updated, but which we're keeping for the time being as potential source material for updated docs. Creating a Skin for Firefox UUID contents.rdf install.rdf Theme changes in Firefox 2 Theme changes in Firefox 3 Theme changes in Firefox 3.5 Theme changes in Firefox 4 Building a Theme Common Theme Issues and Their Solutions Making Sure Your Theme Works with RTL Locales Creating a Skin for SeaMonkey 2 DOM Inspector InspectorWidget Force RTL Yet Another Theme Tutorial ...
Browser chrome tests
he test files are executed in the same scope as the browser window, conflicting variable names could cause trouble while running the tests. You should attempt to reduce the side effects of the testing code and "clean up" after yourself, to avoid influencing other tests. The comparison functions are identical to those supported by Mochitests, see how the comparison functions work in the Mochitest documentation for more details. The EventUtils helper functions are available on the EventUtils object defined in the global scope. The test file name must be prefixed with "browser_", and must have a file extension of ".js". Files that don't match this pattern will be ignored by the test harness. Using a descriptive file name is strongly encouraged instead of just using a bug number. You can collect co...
What to do and what not to do in Bugzilla
It explains what should and what should not be done in bugzilla.mozilla.org. Getting/Upgrading Bugzilla privileges If you want to get Bugzilla privileges (as described below), please see this page. It lists the requirements and the email to contact. If you need faster access to get canconfirm or editbugs, especially in order to triage bugs or to participate in a bug day, then you can ask in #bmo on irc, or you may create a bug requesting permissions. Include a link to your Bugzilla activity page in the bug description. Before you have canconfirm, you can still do good triaging by leaving comments with useful information on the bug that will help to confirm it. ...
Bugzilla
What to do and what not to do in Bugzilla Tips for how to use Bugzilla, as well as things you should avoid. Bugzilla etiquette A guide to etiquette; this guide will help you understand how best to conduct yourself on b.m.o. ...
Building Mozilla
In this article, we list documents that will guide you in building Firefox or other projects based upon Mozilla code. Build instructions Building on Windows with MSYS Building on Windows using the MSVC Toolkit Building on Fedora Core 5 Compiling Mozilla With Mingw Compiling Mozilla With clang on Windows SeaMonkey Building a SeaMonkey package ...
C++ portability guide
This document has migrated to Using C++ in Mozilla code. ...
Continuous Integration
TaskCluster and Treeherder TaskCluster, Mozilla's continuous integration (CI) system picks up changes pushed to Hg. TaskCluster generate binary builds for Firefox and Firefox for Android across a variety of operating sytems. After the builds are completed, they are used to run a series of correctness and performance tests. ...
Cookies Preferences in Mozilla
ie.prefsMigrated Default Value: false Migration pref for users with older profiles (before Mozilla 1.7). If you have the old-style prefs, they will be migrated when starting the application. (The old prefs are network.cookie.lifetime.enabled, network.cookie.lifetime.behavior, and network.cookie.warnAboutCookies.) true = prefs have been migrated false = migrate prefs on next startup Original Document Information Author(s): Mike Connor Last Updated Date: May 22, 2004 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Cookies in Mozilla
Creating a Cookie Log Steps to create and attach a cookie log in order to aid in triaging a bug in cookies. Cookies Preferences in Mozilla Documentation on what the preferences used by the cookies code actually do. Original Document Information Author(s): Mike Connor Last Updated Date: March 15, 2004 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Creating a Firefox sidebar
Add-on SDK. It's the easiest way to create an extension with a sidebar.Obsolete since Gecko 57 You can also build a restartless extension yourself without the SDK. A sample extension to add a Web panel is available as a starter.Obsolete since Gecko 57 If you'd like to have a deeper integration with the browser to offer more complex features, a traditional overlay extension can be an option. The document might be obsolete, though.Obsolete since Gecko 57 The Social API Obsolete since Gecko 57 (Firefox 57 / Thunderbird 57 / SeaMonkey 2.54)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. This content covers features introduced in Firefox 17. The window.sidebar API Obsolete since Gec...
Creating a Language Pack
To create a language pack, or a localization repack, you first need to go through the initial setup process. Pre-build steps In the .mozconfig, you want to have mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/obj-firefox-build ac_add_options --disable-compile-environment ac_add_options --with-l10n-base=../l10n-central # path relative to MOZ_OBJDIR ac_add_options --enable-application=[browser or mail] The given path should have your localization directory as child (i.e., a subdirectory ab-CD where ab-CD is your locale code). ...
Debugging Frame Reflow
pear at the exit of a routine this can cause display errors like stray lines. OS2 is very vulnerable to pixel alignment errors as text is drawn on pixel boundaries. GECKO_DISPLAY_REFLOW_INDENT_UNDISPLAYED_FRAMES Setting this option via set GECKO_DISPLAY_REFLOW_INDENT_UNDISPLAYED_FRAMES = 1 will cause an advance of the indent even for frames which are blocked via the reflow rules file. Original Document Information Author(s): Bernd Mielke Last Updated Date: December 4, 2004 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Debugging Table Reflow
nonymous=0 constraint=3 widths=360 540 -1 -1 -1 -1 -1 -1 540 465 **END COL DUMP** **START COL DUMP** colIndex=3 isAnonymous=0 constraint=0 widths=360 540 -1 -1 -1 -1 -1 -1 -1 465 **END COL DUMP** ***END TABLE DUMP*** The column dump is implemented in nsTableColFrame.cpp in the routine:void nsTableColFrame::Dump(PRInt32 aIndent). DEBUG_TABLE_REFLOW_TIMING needs to be written Original Document Information Author(s): Bernd Mielke Other Contributors: Bernd Mielke, Josh Soref Last Updated Date: November 20, 2005 ...
Debugging
Debugging a project as large as Mozilla can be a daunting task. Fortunately, over the years, Mozilla developers have come up with not just technologies and features to help you debug code, but have devised tips and techniques that can help too. Also available are assorted tools that you can use when debugging. Documentation topics Debugging on top of the Mozilla platform Debugging JavaScript code How to debug JavaScript code, with a focus on debugging code in the Mozilla project itself. Debugging a XULRunner application Tips and suggestions that will help you debug your XULRunner based application. Debugging update problems Learn how to debug update problems in Mozilla-based applications. Debugging the Mozilla platform ...
Configuring Build Options
Most of the time a mozconfig file is not required. The default options are the most well-supported, so it is preferable to add as few options as possible. Please read the following directions carefully before building, and follow them in order. Skipping any step may cause the build to fail, or the built software to be unusable. Build options, including options not usable from the command-line, may appear in "confvars.sh" files in the source tree. ...
Installing headers using EXPORTS
ine which typelib file is produced from the IDL files. ...
JAR Manifests
Documentation for JAR Manifests (jar.mn files) now lives here. ...
Linux build preparation
Documentation moved in-tree: https://firefox-source-docs.mozilla.org/setup/linux_build.html ...
Simple Firefox for Android build
Deprecated: This documentation has moved, please visit geckoview-quick-start for up-to-date documentation on building GeckoView for Android. ...
Building Firefox for Windows
Documentation moved in-tree: https://firefox-source-docs.mozilla.org/setup/windows_build.html ...
Windows SDK versions
: Windows 7 taskbar previews Windows 7 download taskbar progress Windows 7 jump lists You can download the SDK (v7.0 [web setup or ISO image] or unsupported v7.1 [web setup or ISO image]) from the Microsoft Download Center. Note that if you're running a 64 bit version of Windows you may require the "AMD" version of the SDK even if you have an Intel processor, and you may need to deselect the documentation component in the installer in order to avoid an installation error. (This was certainly the case for 64 bit Windows 7 on a late 2008 MacBook Pro.) Warning: Due to a bug in Windows 7 SDK, if you get "SDKSETUP encountered an error: Expecting path %SystemRoot% to represent a valid system volume" error you may require to set environmental variable %windir% to something like "C:\Windows" instea...
Callgraph
he C++ code: int foo() { return good(); } int good() { return evil() ? 0 : 1; } The callgraph would be foo() -> good() -> evil(). ...
Customizing Firefox
Firefox Enterprise documentation is now located on support.mozilla.org. ...
Eclipse CDT Manual Setup
e that should be integrated back into that page, but a large amount of it is now taken care of by the mach project generation code. For now it's stored here until that integration happens in order that the Eclipse CDT page isn't hugely cluttered with mostly redundant information, make setting up Eclipse look much more complicated than it is nowadays. Setup time Some points in the rest of this document below are old and taken care of by the mach commands described above (although some of the project configuration is not done automatically yet). Some of it like the section on building the index and usage tips are still relevant, and other parts still may provide useful background information to understand it in more detail on how Eclipse works. You can expect it to take an hour or so to work t...
Eclipse
There are versions of eclipse for several of the different languages that are used by Mozilla. For documentation on using Eclipse CDT for Mozilla C/C++ development, see the Eclipse CDT page. ...
Interface Compatibility
is 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 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 ...
Working with Mozilla source code
sing tool for accessing the source code. This isn't a good way to download the code, but is a great way to search it. Navigating the Mozilla source code Learn about the various folders in the Mozilla source tree, and how to find what you're looking for. Bugs for newcomers If you are new to the project and want something to work on, look here. Interface development guide Guidelines and documentation for how to create and update XPCOM interfaces. The Firefox codebase: CSS Guidelines This document contains guidelines defining how CSS inside the Firefox codebase should be written, it is notably relevant for Firefox front-end engineers. SVG Cleanup Guide Guidelines and best practices for shipping new SVGs. Try Servers Mozilla products build on at least three platforms. If you don't ha...
Multiple Firefox profiles
s 8/8.1/10 Press "Windows + R" on your keyboard. Type firefox --new-instance --ProfileManager. Linux If Firefox is already included in your Linux distribution, or if you have installed Firefox with the package manager of your Linux distribution: Open a Terminal emulator or your Shell's command prompt: Alt-F2 if you use GNOME Shell or KDE Plasma, consult your desktop environment documentation for other environments. Run firefox --new-instance --ProfileManager. macOS Run the Terminal application, which is found in Applications/Utilities. Type or paste in the path to Firefox, followed by .app/Contents/MacOS/firefox. For example, if Firefox is installed in the recommended location, you would enter /Applications/Firefox.app/Contents/MacOS/firefox. If you have the path t...
Frame script environment
ronous message to chrome. sendSyncMessage() Send a synchronous message to chrome. dump() Print a message to the console. atob() Base64 decode. btoa() Base64 encode. Components The usual Components object. In particular, note that a frame script accesses the DOM window using content, not window: // frame script var links = content.document.getElementsByTagName("a"); All the frame scripts running in a tab share this global. However, any top-level variables defined by a script are not stored on the global: instead, top-level variables are stored in a special per-script object that delegates to the per-tab global. This means you don't have to worry about global variables you define conflicting with global variables defined by another...
Limitations of frame scripts
nsISessionStore nsIWindowMediator <need more examples> Places API The Places API can't be used inside a frame script. For example: nsINavHistoryService nsINavBookmarksService Observers in the content process As noted in Observers in the chrome process, most observers should be registered in the chrome process and will not work in the content process. The exceptions are: content-document-global-created document-element-inserted outer-window-destroyed inner-window-destroyed dom-window-destroyed These must be registered in the content process. QI from content window to chrome window There's a particular pattern often used to get from a content window to the associated chrome window. It looks something like this: window.QueryInterface(Ci.nsIInterfaceRequestor) ...
Communicating with frame scripts
se Object { details: "they clicked", tag: "div" } <xul:browser anonid="initialBrowser" ... > { target: <div#searchContainer> } If your code requires access to a window (for example to run window.openDialog), and your message listener is run from somewhere without access to a window (e.g. an XPCOM component), you can access the window of the browser that sent the message with message.target.ownerDocument.defaultView. Synchronous messaging To send a synchronous message, the frame script uses the global sendSyncMessage() function: // frame script sendSyncMessage("my-addon@me.org:my-e10s-extension-message"); When a chrome script receives a synchronous message, it should return a value from its message listener: // chrome script messageManager.addMessageListener("my-addon@me.org:my-e10s-extensio...
Frame script environment
ronous message to chrome. sendSyncMessage() Send a synchronous message to chrome. dump() Print a message to the console. atob() Base64 decode. btoa() Base64 encode. Components The usual Components object. In particular, note that a frame script accesses the DOM window using content, not window: // frame script var links = content.document.getElementsByTagName("a"); All of the frame scripts running in a tab share this global. However, any top-level variables defined by a script are not stored on the global: instead, top-level variables are stored in a special per-script object that delegates to the per-tab global. This means you don't have to worry about global variables you define conflicting with global variables defined by anot...
Frame script loading and lifetime
ot remove any scripts which have been loaded earlier. Frame script lifetime Frame scripts are loaded as soon as loadFrameScript() is called. If you've set allowDelayedLoad, the script is loaded into a new tab as soon as it is created. Frame scripts are associated with a browser tab and not with a page. So once you load them, they will stay loaded until the tab is closed, even if you reload the document or navigate. If you want to limit a script to the lifetime of a page you can create a Sandbox instead, where the current content page is used as prototype. If you want a frame script to do something when a new document is loaded, you need to listen for an appropriate DOM event, generally DOMWindowCreated, DOMContentLoaded, or load. Unloading frame scripts Frame scripts are automatically unload...
Limitations of frame scripts
nsISessionStore nsIWindowMediator <need more examples> Places API The Places API can't be used inside a frame script. For example: nsINavHistoryService nsINavBookmarksService Observers in the content process As noted in Observers in the chrome process, most observers should be registered in the chrome process and will not work in the content process. The exceptions are: content-document-global-created document-element-inserted outer-window-destroyed inner-window-destroyed dom-window-destroyed These must be registered in the content process. QI from content window to chrome window There's a particular pattern often used to get from a content window to the associated chrome window. It looks something like this: window.QueryInterface(Ci.nsIInterfaceRequestor) ...
Message manager overview
Interfaces nsIFrameScriptLoader nsIMessageListenerManager nsIMessageBroadcaster How to access You can access it as a property of the browser window: // chrome script let windowMM = window.messageManager; Browser message manager Note that in this context, "browser" refers to the XUL <browser> object, which is a frame that hosts a single Web document. It does not refer to the more general sense of a Web browser. Description Finally, there's a browser message manager for every open content tab: three, in the diagram above. This corresponds one-to-one with a content tab. Scripts you load using a browser message manager are loaded only into that content tab, and messages you send are delivered only to that content tab. ...
Process scripts
s (for example, no file system access). process scripts stay loaded until their host process is closed. the environment for process scripts is similar to that for frame scripts. However, you don't get access to web content or DOM events from a process script. Retrieving the content frame message manager for a content window When an observer notification in a process script contains a content document or window it can be useful to not use talk through the child/parent process message managers but through the window's content frame message manager, e.g. if responses should be processed by a frame script instead of the process script. This can be achieved by traversing the docshell tree up to the top window and then retrieving its content message manager, as follows: function contentMMFromCont...
Message manager overview
le chrome code to: load a script into a frame in the content the content process using a loadFrameScript() function. These scripts are called "frame scripts". communicate with frame scripts using addMessageListener() and broadcastAsyncMessage() or sendAsyncMessage() functions. Note that in this context, "browser" refers to the XUL <browser> object, which is a frame that hosts a single Web document. It does not refer to the more general sense of a Web browser. Global message manager The global message manager operates on every <browser> (that is, every open content tab). loadFrameScript() loads the given script into every <browser> in every browser window. broadcastAsyncMessage() sends the message to every <browser> in every browser window. It's a ChromeMessageBroadcaster object,...
Privacy
This document lists privacy-related documentation. Storage access policy: Block cookies from trackersTracking Protection ...
Firefox and the "about" protocol
Lists all crashes, which happened during the runtime of Firefox (in case the user enabled the crash reporter) about:credits Lists all contributors to the Firefox project about:debugging Switches to the Developer Tools debugging page, which allows you to debug add-ons, tabs and Service Workers about:devtools Summarizes the developer tools and provides links to documentation for each tool about:downloads Displays all downloads done within Firefox about:home Start page of Firefox when opening a new window about:license Displays licensing information about:logo Firefox logo about:memory Provides a way to display memory usage, save it as report and run the GC and CC about:mozilla Special page s...
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
etc. should not reflect the frame hierarchy. API extensions: the API includes several new methods and events to manipulate and listen for changes to the embedded content's state, interited by the HTMLIFrameElement interface. Note: An iframe enhanced by the Browser API is commonly referred to as a "browser iframe". We'll be using this term throughout the current article, and other parts of the documentation. Demo To demonstrate basic usage of this API, we have created a simple Browser API demo that provides buttons allowing you to (re)load web pages, stop loading, move forward and back in history, and zoom in and out of the page. To run the demo, the best approach is to clone the GitHub repo locally (or just download it directly if you don't do GitHub), open WebIDE, open the repo as a Pac...
HTMLIFrameElement.addNextPaintListener()
<iframe>. This event provides information about what has been repainted. It is mainly used to investigate performance optimization. Note: The handler will receive the event once and then be thrown away. Syntax instanceOfHTMLIframeElement.addNextPaintListener(listener); Returns Void. Parameters listener A function handler to listen for a MozAfterPaint event. Examples var browser = document.querySelector('iframe'); function onNextPaint() { console.log("Paint has occured"); } browser.addNextPaintListener(onNextPaint); Specification Not part of any specification. ...
HTMLIFrameElement.download()
tions object allowing optional settings to be specified for the download. The available options are: filename: The filename to save the downloaded file as. If this is not specified, the filename used will be the original filename, as specified in the url. referrer: Specifies a referrer for the downloaded file. If this is not specified there will be no referrer. Examples var browser = document.querySelector('iframe'); var request = browser.download(fooURL, { filename: 'foo.bin' }); request.onsuccess = function() { console.log("File downladed"); } request.onerror = function() { console.log("Download error"); } Specification Not part of any specification. ...
HTMLIFrameElement.getActive()
behavior may change in the future. The getActive() method of the HTMLIFrameElement indicates whether the current browser <iframe> is the currently active frame. Syntax var amIActive = instanceOfHTMLIframeElement.getActive(); Returns A Boolean indicating whether the current browser <iframe> is the currently active frame (true) or not (false.) Parameters None. Example var browser = document.querySelector('iframe'); var amIActive = browser.getActive(); Specification Not part of any specification. ...
HTMLIFrameElement.getManifest()
Removed in Firefox 65. The getManifest() method of the HTMLIFrameElement interface retrieves the manifest of an app loaded in the browser <iframe> and returns it as JSON. Syntax instanceOfHTMLIframeElement.getManifest().then(function(json) { ... }); Parameters None. Return value A promise that resolves to a JSON object representation of the loaded app's manifest. Examples var browser = document.querySelector('iframe'); browser.addEventListener('mozbrowserloadend',function() { var request = browser.getManifest().then(function(json) { console.log(json); }); }); Specification Not part of any specification. ...
HTMLIFrameElement.getScreenshot()
mber representing the maximum height of the screenshot in device pixels. mimeType Optional A MIME type specifying the format of the image to be returned; if not specified, the default used is image/jpeg. Use image/png to capture the alpha channel of the rendered result by returning a PNG-format image. This lets you get a transparent background for the content <iframe>. Examples var browser = document.querySelector('iframe'); var request = browser.getScreenshot(100, 100); request.onsuccess = function() { var blob = request.result; var url = URL.createObjectURL(blob); } Specification Not part of any specification. ...
HTMLIFrameElement.getStructuredData()
er <iframe> and returns it as JSON. Syntax var instanceOfDOMRequest = instanceOfHTMLIframeElement.getStructuredData(); Returns A DOMRequest to handle the getStructuredData() request's success and error cases. If the request is successful, the request.result is a JSON object representation of all microdata contained on the page loaded in the browser. Parameters None. ...
HTMLIFrameElement.getVisible()
nt is used to request the current visible state of the browser <iframe>. Syntax instanceOfDOMRequest = instanceOfHTMLIframeElement.getVisible(); Returns A DOMRequest object to handle the getVisible() request's success and error cases. If the request is successful, the request's result is a Boolean indicating the visible state of the browser <iframe>. Parameters None. Example var browser = document.querySelector('iframe'); var request = browser.getVisible(); request.onsuccess = function() { console.log('The visible state is: ' + this.result ? 'true' : 'false'); } Specification Not part of any specification. ...
HTMLIFrameElement.getVolume()
me request. It has an onsuccess handler to handle the success case, and an onerror handler to handle the failure case. The volume value is available in the request.result property, and is a floating point number between 0 and 1. Promise version: A Promise that resolves with the volume value -- a floating point number between 0 and 1. Parameters None. Example Callback version: var browser = document.querySelector('iframe'); var request = browser.getVolume(); request.onsuccess = function() { console.log('The current browser volume is ' + request.result); } Promise version: var browser = document.querySelector('iframe'); browser.getVolume().then(function(volume) { console.log('The current browser volume is ' + volume); }); Specification Not part of any specification. ...
mozbrowseractivitydone
ubbles 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). ...
mozbrowseraudioplaybackchange
d 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 Boolean Indicates whether audio is playing in the browser. ...
mozbrowsercaretstatechanged
true) or not (false.) selectionEditable A Boolean indicating whether the current selection is editable (true) or not (false.) selectedTextContext A DOMString containing the currently-selected text content. sendDoCommandMsg A method allowing you to issue a command via an anonymouse function, i.e. function(command). Possible values are cut, copy, paste and selectAll. ...
mozbrowserclose
Property Type Description target Read only EventTarget The event target (the topmost target in the DOM tree). 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. ...
mozbrowsererror
onnectionFailure netInterrupt netTimeout cspBlocked phishingBlocked malwareBlocked unwantedBlocked offline malformedURI redirectLoop unknownSocketType netReset notCached isprinting deniedPortAccess proxyResolveFailure proxyConnectFailure contentEncodingFailure remoteXUL unsafeContentType corruptedContentError certerror other Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowsererror", function( event ) { console.log("An error occurred:" + event.detail); }); Related Events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrows...
mozbrowserfindchange
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. activeMatchOrdinal A number indicating the position of the currently highlighted search result, e.g. 3 out of 5. ...
mozbrowserfirstpaint
Property Type Description target Read only EventTarget The event target (the topmost target in the DOM tree). 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. ...
mozbrowsericonchange
s 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. ...
mozbrowserloadend
n shown on the stop/reload button between stop (x) and reload (R), as appropriate. In addition, the background of the controls UI bar is changed to the background color of the site that has just loaded, to provide a more integrated experience. When the front page of https://developer.mozilla.org is loaded, for example, the e.detail.backgroundColor value reported is rgb(0, 83, 159). ...
mozbrowserloadstart
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. Example In this example the mozbrowserloadend and mozbrowserloadstart events are used to change the icon shown on the stop/reload button between stop (x) and reload (R), as appropriate. ...
mozbrowserlocationchange
he 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 always display the correct URL for the current location. ...
mozbrowsermanifestchange
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. ...
mozbrowsermetachange
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, removed, or undefined. lang Optional A DOMString representing the <meta> name attribute value, if included. If not included, the value returned is undefined. Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowsermetachange", function(event) { console.log("A meta tag has been " + event.details.type + ". Its name is " + event.details.name + ", and its content is " + event.details.content + "."); }); Related Events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart ...
mozbrowseropensearch
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. ...
mozbrowseropenwindow
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 representing the new browser <iframe> that will embed the new content. Example var browser = do...
mozbrowserresize
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. ...
mozbrowserscroll
ails 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. ...
mozbrowserscrollareachanged
ble 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. ...
mozbrowserscrollviewchange
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. ...
mozbrowsersecuritychange
ed from loading. extendedValidation A Boolean indicating if the current SSL certificate is an Extended Validation certificate (true) or not (false). trackingContent A Boolean indicating if tracking content is present on the current page (true) or not (false). mixedContent A Boolean indicating if mixed content is present on the current page (true) or not (false). ...
mozbrowserselectionstatechanged
e child frame. This is unitless and represents a percentage increase/decrease, e.g. 1.1 is a 10% zoom in, and 0.9% is a 10% zoom out. isCollapsed A Boolean Indicating whether the current selection is collapsed (true) or not (false). visible A Boolean Indicating whether the current selection is visible (true) or not (false). states The current state of the selection. ...
mozbrowsershowmodalprompt
be called when the iframe is unblocked. Note that if the embedder calls preventDefault() on this event, the iframe is blocked until unblock() is called. Obsolete properties of details msg_name A string representing the type of message. For that event, it's always showmodalprompt. initialValue A string representing the initial value for the window.prompt() methods. ...
mozbrowserusernameandpasswordrequired
he 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 needs to take two parameters -- the username and password to authenticate. cancel() A function that is called to cancel the authentication. ...
mozbrowservisibilitychange
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). ...
HTMLIFrameElement.mute()
Mozilla › Gecko › Chrome › API › Browser API › mute
ack. 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 mute() method of the HTMLIFrameElement mute any audio playing in the browser <iframe>. Syntax instanceOfHTMLIframeElement.mute(); Returns Void. Parameters None. Example var browser = document.querySelector('iframe'); browser.mute(); Specification Not in a specification. ...
HTMLIframeElement.removeNextPaintListener()
Warning: Removed in Firefox 65. The removeNextPaintListener() method of the HTMLIFrameElement interface is used to remove a handler previously set with the addNextPaintListener method. Syntax instanceOfHTMLIframeElement.removeNextPaintListener(listener); Returns Void. Parameters listener A function handler previously set with addNextPaintListener. Examples var browser = document.querySelector('iframe'); function onNextPaint() { console.log("Paint has occured"); } browser.addNextPaintListener(onNextPaint); browser.removeNextPaintListener(onNextPaint); Specification Not part of any specification. ...
HTMLIFrameElement.sendMouseEvent()
performed. modifiers A number representing a key pressed at the same time the mouse button was clicked: 1 : Alt 2 : Ctrl 4 : Shift 8 : Meta 16 : Alt Gr 32 : Caps Lock 64 : Fn 128 : Num Lock 256 : Scroll 512 : Symbol Lock 1024 : Win Note: You can specify multiple key modifiers separated by a pipe symbol, for example 1 | 1014. Examples var browser = document.querySelector('iframe'); browser.sendMouseEvent("mousemove", x, y, 0, 0, 0); browser.sendMouseEvent("mousedown", x, y, 0, 1, 0); browser.sendMouseEvent("mouseup", x, y, 0, 1, 0); Specification Not part of any specification. ...
HTMLIFrameElement.sendTouchEvent()
performed. modifiers A number representing a key pressed at the same time the mouse button was clicked: 1 : Alt 2 : Ctrl 4 : Shift 8 : Meta 16 : Alt Gr 32 : Caps Lock 64 : Fn 128 : Num Lock 256 : Scroll 512 : Symbol Lock 1024 : Win Note: You can specify multiple key modifiers separated by a pipe symbol, for example 1 | 1014. Examples var browser = document.querySelector('iframe'); browser.sendTouchEvent("touchstart", [1], [x], [y], [2], [2], [20], [0.5], 1, 0); Specification Not part of any specification. ...
HTMLIFrameElement.setActive()
the future. The setActive() method of the HTMLIFrameElement sets the current <iframe> as the active frame, which has an effect on how it is prioritized by the process manager. Syntax instanceOfHTMLIframeElement.setActive(boolean); Returns Void. Parameters boolean A Boolean that indicates whether the iframe is to be the active frame (true) or not (false). Example var browser = document.querySelector('iframe'); browser.setActive(); Specification Not part of any specification. ...
HTMLIFrameElement.setVisible()
equestAnimationFrame will be called as often as necessary. However, if the visible state is set to false, window.requestAnimationFrame will be called only when there are free resources to do it. Syntax instanceOfHTMLIframeElement.setVisible(visible); Returns Void. Parameters visible A Boolean that indicates if the browser <iframe> visible state is true or false. Examples var browser = document.querySelector('iframe'); browser.setVisible(true); Specification Not part of any specification. ...
HTMLIFrameElement.setVolume()
s between implementations and the behavior may change in the future. The setVolume() method of the HTMLIFrameElement sets the current volume of the browser <iframe>. Syntax instanceOfHTMLIframeElement.setVolume(number); Returns Void. Parameters number A floating point number representing the volume you want to set -- this can have a value between 0 and 1. Example var browser = document.querySelector('iframe'); browser.setVolume(0.5); Specification Not part of any specification. ...
HTMLIFrameElement.unmute()
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 unmute() method of the HTMLIFrameElement unmutes any audio playing in the browser <iframe>. Syntax instanceOfHTMLIframeElement.unmute(); Returns Void. Parameters None. Example var browser = document.querySelector('iframe'); browser.unmute(); Specification Not part of any specification. ...
HTMLIFrameElement.zoom()
Mozilla › Gecko › Chrome › API › Browser API › zoom
. This is particularly useful for zooming in/out on non-touch-enabled devices. Syntax var instanceOfDOMRequest = instanceOfHTMLIframeElement.zoom(zoomFactor); Returns Void. Parameters zoomFactor A unitless number value representing the amount to zoom in or out. It acts like a percentage, so for example 1.1 would zoom in by 10%, whereas 0.9 would zoom out by 10%. Examples var browser = document.querySelector('iframe'); var zoomFactor = 1; zoomIn.addEventListener('touchend',function() { zoomFactor += 0.1; browser.zoom(zoomFactor); }); zoomOut.addEventListener('touchend',function() { zoomFactor -= 0.1; browser.zoom(zoomFactor); }); Specification Not part of any specification. ...
:-moz-lwtheme-brighttext
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 :-moz-lwtheme-brighttext pseudo-class matches in chrome documents when :-moz-lwtheme is true and a lightweight theme with a bright text color is selected. ...
:-moz-lwtheme-darktext
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 :-moz-lwtheme-darktext pseudo-class matches in chrome documents when :-moz-lwtheme is true and a lightweight theme with a dark text color is selected. ...
:-moz-lwtheme
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 :-moz-lwtheme pseudo-class matches in chrome documents when the root element's lightweightthemes attribute is true and a theme is selected. ...
MozBeforePaint
re frames than that anyway. Limiting the frame rate avoids wasting work, thereby saving CPU usage and power and improving overall system performance. Example This example performs a simple animation, moving a box a short distance after a short period of time. ...
Chrome-only Events reference
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. ...
Embedding Mozilla
Gecko allows third-party developers to use the same technology as found in Mozilla. That means you can embed a web browser inside a third-party application, open channels and streams through the network backend, walk through the DOM and so on. You can even construct whole new applications using chrome. Documentation Gecko Embedding Basics An introduction to embedding the Gecko rendering engine. Embedding Tips Some frequently asked questions about embedding. Mozilla embedding APIs overview Introduction to the Mozilla embedding APIs. Embedding the Editor This document describes the current state of editor embeddability, problems with the existing implementation, some possible embedding scenarios that we need to deal with, and an...
Gecko SDK
o install libidl with the +universal flag. Once that's done, you should perform the following command: ln -s /opt/local/lib/libintl.8.dylib /opt/local/lib/libintl.3.dylib This should fix the problem. Building the SDK To build the SDK, you should build XULRunner (the Gecko SDK is built as part of the XULRunner build process, which is why it's sometimes called the XULRunner SDK). See the Build Documentation for complete details. After the XULRunner build is complete running make sdk from your object directory will create a package of the sdk in dist. Contents of the SDK The SDK contains the following: 1.9.2 IDL files for frozen interfaces (under idl/) Header files for frozen interfaces, XPCOM functions, and NSPR functions (under include/) Import libraries or shared libraries (under lib/...
Gecko Keypress Event
e US QWERTY keyboard layout temporary. Gecko uses the character from this keyboard layout for the Ctrl key also. However, when Ctrl is down, Gecko 1.9 currenly only replaces the charCode only when the key corresponds to a basic Latin letter. This behavior is a bug, this behavior will be changed in a future major release (bug 432951). Alternative charCodes for internal key handling This section documents only Gecko internal keypress event handling, so Web application developers can ignore this section. Gecko replaces the charCode of DOM keypress events for accelerator key handling, but that is not enough. Problem 1 The Zoom-in shortcut handler in Firefox is defined as <key key="+" modifiers="accel"/>. However, the Shift key must be used to enter '+' on US keyboard layout, and so the state of ...
Script security
safely with untrusted web content. From the point of view of chrome code, the script security model in Gecko is intended to provide that help to make writing secure, system-privileged JavaScript a realistic expectation. Security policy Gecko implements the following security policy: Objects that are same-origin are able to access 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. Objects that are cross-origin get highly restricted access to each other, according to the same-origin policy. For example, code served from https://example.org/ trying to access objects from https://somewhere-else.org/ will have restricted access. Objects in a privilege...
Gecko
, JavaScript, and render it on the user's screen or print it. 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. Documentation Chrome This page contains information specific to browser chrome (not Google Chrome) code running in Gecko. Gecko FAQ Frequently asked questions about Gecko. Gecko DOM reference Reference to the DOM. Gecko event reference Reference to events used within Gecko and Mozilla applications; for web-standard DOM events, see the DOM event ref...
Gecko's "Almost Standards" Mode
also trigger "almost standards" mode. Recommendations For authors who are attempting to migrate to validated markup using either HTML 4.01 or XHTML 1.0, and who are still using image-in-table design concepts, make sure to use a DOCTYPE that will trigger "almost standards" mode. Also On MDC Images, Tables, and Mysterious Gaps Mozilla's DOCTYPE sniffing Mozilla's Quirks Mode Original Document Information Author(s): Eric A. Meyer, Netscape Communications Last Updated Date: Published 08 Nov 2002 Copyright Information: Copyright (C) 2001-2003 Netscape. All rights reserved. Note: This reprinted article was originally part of the DevEdge site. ...
Getting from Content to Layout
Gecko maintains two separate representations of a document in memory: the content tree and the frame tree. Changes to a document originate in the content tree (from DOM modification by scripting, insertion of elements from the parser, etc.) and are propogated to the layout tree through magic that primarily resides in //github.com/RealityRipple/UXP/blob/master/layout/base/nsCSSFrameConstructor.cpp The frame constructor implements nsIMutationObserver which allows it to "watch" the content tree. nsCSSFrameConstructor gets notified from the document's PresShell (which implements nsIDocumentObserver and observes the document) about all nodes in the document. The frame constructor takes these notifications and does the following: Dispatches "restyle events" which trigger the reprocessing ...
IPDL Best Practices
Lifetime Management Ensure IPDL deletes your protocol All protocols must be deleted. Period. Are you sending the __delete__ message to trigger protocol deletion? This one is easy to miss, as the corresponding Recv__delete__ function has a stub implementation automatically generated in the base class. Simply calling delete on a pointer to an actor is not enough. ...
Extending a Protocol
actually implement everything in C++. It's quite involved and, unfortunately, all steps need to be done before we can successfully recompile. We will try to compile our code as we go, noting what we need to do along the way. To be sure, IPDL looks like a crazy mix of WebIDL, C++ header files, and ES6. The syntax should hopefully be fairly obvious though. Unfortunately, it's not really fully documented anywhere - and the IPDL parser gets easily confused (hence us excluding comments below). Creating the protocol PEcho.ipdl Let's start by saving the following file to ./dom/ipc/PEcho.ipdl. We will explain what all the parts mean below. Note that the file's name and the protocol name must match. include protocol PWindowGlobal; namespace mozilla { namespace dom { async refcounted protocol...
IPDL Tutorial
s PluginChild : public PPluginChild { protected: void RecvInit(const nsCString& pluginPath) { mPluginLibrary = PR_LoadLibrary(pluginPath.get()); SendReady(); } void RecvShutdown() { PR_UnloadLibrary(mPluginLibrary); } private: PRLibrary* mPluginLibrary; }; Launching the subprocess and hooking these protocol actors into our IPC "transport layer" is beyond the scope of this document. See IPDL Processes and Threads for more details. Because protocol messages are represented as C++ methods, it's easy to forget that they are in fact asynchronous messages: by default the C++ method will return immediately, before the message has been delivered. The parameters of the Recv* methods (const nsCString& pluginPath in the example) are references to temporary objects, so copy them if ...
Internationalized Domain Names (IDN) Support in Mozilla Browsers
is a global trend and is likely to be adopted by a large number of sites making it easier for average Internet users to find web sites. ...
JavaScript libraries from Mozilla projects
There are no subpages at this time. ...
Dict.jsm
ct() 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 before being used, so they're documented here as if they were a string parameter. In Firefox 19 and above, you may also pass a JSON String to initialize the dictionary: var someJSON = '{key1: "foo", key2: {}}'; var newDict = new Dict(someJSON); Note: Any String you pass will be assumed to be JSON. Method overview Dict copy(); boolean del(String aKey); Object get(String aKey, [optional] Object aDefault)...
DownloadSource
Properties Attribute Type Description url Read only string The URI for the download source. isPrivate Read only boolean Indicates whether the download originated from a private window. This determines the context of the network request that is made to retrieve the resource. ...
DownloadTarget
ty's value will always match the actual size of the file on disk, while the Download.totalBytes property, when available, may indicate the size of the data as encoded for transfer instead. For downloads of multiple files, such as downloading a web page and its required media to disk, the meaning of this property is undefined. It currently indicates the size of the main file (such as the HTML document) rather than the sum of all of the files' sizes, but you must not rely upon this behavior, as it is subject to change. This is a dynamic property, which is updated when the download finishes or whenever the Download.refresh() method is called. You can use this value from the front-end to reduce file I/O that would be required to check the file directly. Methods refresh() Updates...
Downloads.jsm
loadList. The start() method can be used to restart a failed download. Handling of downloads that have been paused is also different. While some of the legacy methods and properties have an equivalent in Downloads.jsm, there might be subtle differences in behavior. For example, the properties that handle progress are now more detailed and don't use the special value -1 anymore. You may see the documentation of the new methods and properties for details. Using it in a XUL app In a XUL standalone application (running with XULRunner or firefox --app), you have to do additionnal things in order to use the new download manager. By default it is not enabled. It will be enabled when the bug 851471 will be closed. If you don't activate it, you could use Downloads.jsm, but your view will not be called...
Examples
romise.then(function onFulfill(aValue) { console.log("Fulfilled with this value: " + aValue); }, function onReject(aReason) { console.log("Rejected with this reason: " + aReason); }); // Unexpected errors should always be reported at the end of a promise chain. newPromise.then(null, Components.utils.reportError); Note: More examples for consuming promises are available in the Promise object documentation. Make user defined promise return after multiple images finish loading (Promise.all and Promise.defer) This example shows how to use Promise.all to wait to create multiple promises with Promise.defer() and return at the end of it. Components.utils.import("resource://gre/modules/Promise.jsm"); var myPromise = myUserDefinedPromise(); myPromise.then( function(aSuccessReason) { alert('...
Promise
ently associated with the promise. This may be any value, including undefined, though it is generally an Error object, like in exception handling. Note: You should always handle, forward, or report errors (rejection reasons). If you see the message "A promise chain failed to handle a rejection", there is likely something to be fixed in the code. See handling errors and common pitfalls below. Documentation conventions In documentation, the type of the fulfillment value is usually specified between angular brackets. For example, the OS.File.exists function returns a promise that will eventually fulfill with a boolean: Promise<boolean> exists(string path); The rejection reason may be specified separately in the function's documentation, and is considered to be an Error object unless otherwis...
PromiseUtils.jsm
ject this Promise. 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. See the Deferred documentation for details. ...
Sqlite.jsm
he database is rolled back to its state before the transaction started. This function receives the following arguments: func The function defining the transaction body. type The type of transaction to perform. This must be one of the TRANSACTION_* constants on the opened connection instance. Valid values are TRANSACTION_DEFERRED, TRANSACTION_IMMEDIATE, TRANSACTION_EXCLUSIVE. See the SQLite documentation for their meaning. The default is TRANSACTION_DEFERRED. The passed function is a Task.jsm compatible generator function. When called, the function receives as its argument the current connection instance. This generator function is expected to yield promises, likely those returned by calling executeCached() and execute(). If we reach the end of the generator function without error, the tr...
Task.jsm
The Task.jsm JavaScript code module implements a subset of Task.js to make sequential, asynchronous operations simple, using the power of JavaScript's yield operator. To use it, you first need to import the code module into your JavaScript scope: Components.utils.import("resource://gre/modules/Task.jsm"); Introduction For an introduction to tasks, you may start from the Task.js documentation, keeping in mind that only the core subset is implemented in this module. 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. Task.spawn() returns a promise that is resolved when the task completes successfully, or is rejected if an exc...
JavaScript code modules
pics 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. Mozilla Labs JS Modules This page features a list of JavaScript modules, along with download links and documentation, that extension developers can use in their code. 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. Assert.jsm Implements the CommonJS Unit Testing specification version 1.1, which provides a basic standardized interface for performing in-code logical assertions with...
Localization: Frequently asked questions
How do I preserve whitespace in an entity? Do you really want to preserve whitespace or are you looking for a no-break space, you can add that via a &ua0; or \ua0 to DTD and properties files, resp. ...
Localization notes
It's important to follow the format as closely as possible. ...
Localizing XLIFF files for iOS
-locale-code/ You should now see the firefox-ios project in your selected directoy with the firefox-ios.xliff file in it. Translating the XLIFF file Open the firefox-ios.xliff file in your favorite text editor. In the <file> tag, add the target-language attribute with your locale code as the value (e.g., target-language="xx-XX"). Be aware that there may be many <file> tags within one XLIFF document. Each <file> tag requires the target-language attribute with your locale code as the value (e.g., target-language="xx-XX"). Strings are located within <trans-unit> tags. Source English strings are contained in <source> child tags. Here is an example of such a <trans-unit> <trans-unit id="Add to Bookmarks"> <source>Add to Bookmarks</source> </trans-unit> Your translations must be contain...
Creating localizable web applications
ons or for clarity. Cheatsheet Don't hardcode English text, formats (numbers, dates, addresses, etc.), word order or sentence structure. Don't put text or numbers in images. Don't forget about right-to-left locales. Take advantage of printf() (or equivalents) and use variables in the English strings. Write semantic code (e.g. don't use text and <img/> for decorations; instead, use CSS). Document your code so that localizers know what they're translating (e.g. in gettext use comments and contexts). App Logic Detect the locale correctly Be smart about detecting the user's locale correctly. You can use one or more of the following techniques: HTTP Accept-Language headers, the UA string, IP geolocation. See examples of the addons.mozillaorg code at /addons/trunk/site/app/config/la...
Creating localizable web content
Text content Check that the text is factually correct for an international audience (e.g., mentions of en-US specific product pieces like specific search engines or dictionary should be adapted) Look for strings that are likely hard to translate because they are unclear, use play on words or colloquialisms. Depending on context, find alternate strings or document an explanation of the string for localizers Check that we don't link in new pages to sub-pages with anchors. E.g.: a new page is announced with only 100 words but it is actually content added to an existing page in English. Happens for things like Faq, or video pages for example. For video, use the code to display the video in an overlayed video player on the page instead of linking to a video section in English. Per-locale c...
Web Localizability
How to choose the right localization format. How to create localizable web applications. How to set up the infrastructure for localization. ...
gettext
Plurals gettext lets you define and use singular and plural forms of a string. To take advantage of this functionality, you need to use a different keyword (i.e. different gettext function name) for string which are supposed to support plurals. For instance, in PHP the default keyword for regular messages is gettext() and _(). For messages with plural support, the default keyword is ngettext(). ...
Extras
> <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.addEventListener("load", init); ...
MathML3Testsuite
ing bug for the MathML testsuite. Characters Blocks Symbols Variants EntityNames NumericRefs UTF8 General Clipboard GenAttribs Math Presentation CSS DynamicExpressions GeneralLayout ScriptsAndLimits TablesAndMatrices TokenElements Topics Accents BiDI ElementaryMathExamples EmbellishedOp LargeOp LineBreak Nesting StretchyChars WhiteSpace TortureTests ErrorHandling Original Document Information Author(s): Frederic Wang Other Contributors: Last Updated Date: May 26, 2010 Copyright Information: Portions of this content are (C) 2010 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
MathML In Action
addEventListener("click", zoomToggle, false); } window.addEventListener("load", load, false); Consider an interesting markup like this { u t + f ( u ) x = 0 u ( 0 , x ) = { u - if x < 0 u + if x > 0 or other complex markups like these Ell ^ Y ( Z ; z , ? ) := ? Y ( ? l ( y l ...
Mozilla MathML Status
Not implemented. See bug 534967. mscarry Not implemented. See bug 534967. msline Not implemented. See bug 534967. Other elements Element [- attribute] Notes mglyph Not implemented. See bug 297465. maction Implemented. maction - tooltip Not implemented. See bug 544001. semantics Implemented. Original Document Information Author(s): Frederic Wang Other Contributors: Copyright Information: Portions of this content are (C) 2010 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
MathML Demo: <mo> - operator, fence, separator, or accent
l as the top row of the column vector, but this is difficult to achieve. This problem can be solved using aligned arrays, as follows a b c d a b c d However, all reasonable attempts to fence the column vector will fail because LaTeX fences are symmetric. In MathML, operators that are used for fencing are never symmetric and are always stretchy by default. (i.e., as documented in the suggested Operator Dictionary). Hence <mo symmetric="true"> must be scripted if the intent is to emulated LaTeX fence behavior. The commands \big, \Big, \bigg and \Bigg produce a discreet set of increasingly taller fences, | 1 + | 2 + | 3 + | 4 + | . | + 5 | + 6 | + 7 | + 8 | . Here's the same expression in a display | 1 + | 2 + | 3 + | 4 + | . | + 5 | + 6 ...
Using the viewport meta tag to control layout on mobile browsers
0px for example, media queries that kick in at 640px or 480px or less will never be used, limiting the effectiveness of such responsive design techniques. To mitigate this problem, Apple introduced the "viewport meta tag" in Safari iOS to let web developers control the viewport's size and scale. Many other mobile browsers now support this tag, although it is not part of any web standard. Apple's documentation does a good job explaining how web developers can use this tag, but we had to do some detective work to figure out exactly how to implement it in Fennec. For example, Safari's documentation says the content is a "comma-delimited list," but existing browsers and web pages use any mix of commas, semicolons, and spaces as separators. Learn more about viewports in different mobile browsers in A...
Mozilla Port Blocking
y you need to add preferences to either user.js or all.js. See bug 85601. Per protocol port blocking/enabling preferences. Better User Interface Allow the user to decide if the blocking is really required. Some kind of way to manage the ports which are blocked. More Information nsIOService.cpp gbadPortList bug 83401 Vulnerability Note VU#476267 dougt@netscape.com Original Document Information Author(s): Doug Turner Last Updated Date: August 15, 2007 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Mozilla Development Tools
of already-reported bugs. Doctor Doctor is a web interface to CVS. It lets developers and others edit pages on the mozilla.org web site without having to use CVS. Doctor lets you edit pages in WYSIWYG mode if the pages contain the <?doctor enable_wysiwyg_mode ?> processing instruction. Access Doctor by clicking the "Edit this Page" link at the bottom of any mozilla.org web page. Original Document Information Author(s): Myk Melez Last Updated Date: November 8, 2005 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Mozilla external string guide
...
Mozilla projects on GitHub
is a great place to start looking for any projects 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. bugzill...
Activity Monitor, Battery Status Menu and top
This article describes the Activity Monitor, Battery Status Menu, and top -- three related tools available on Mac OS X. Note: The power profiling overview is worth reading at this point if you haven't already. It may make parts of this document easier to understand. Activity Monitor This is a built-in OS X tool that shows real-time process measurements. It is well-known and its "Energy Impact" measure is likely to be consulted by users to compare the power consumption of different programs. (Apple support documentation specifically recommends it for troubleshooting battery life problems.) Unfortunately "Energy Impact" is not a good measure for either users or software developers and it should be avoided. Activity Monitor can still be useful, however. Power-related measurements Activ...
Adding a new Telemetry probe
...
Intel Power Gadget
The main strengths of this tool are (a) it works on Windows, unlike most other power-related tools, and (b) it shows this data in graph form, which is occasionally useful. ...
Power profiling overview
e mobile device. That in turn depends on the software running on the device. Web browsers are popular applications and can be power-intensive, and therefore can significantly affect battery life. As a result, it is worth optimizing (i.e. reducing) the power consumption caused by Firefox and Firefox OS. Intel processor basics Processor layout The following diagram (from the Intel Power Governor documentation) shows how machines using recent Intel processors are constructed. The important points are as follows. The processor has one or more packages. These are part of the actual processor that you buy from Intel. Client processors (e.g. Core i3/i5/i7) have one package. Server processors (e.g. Xeon) typically have two or more packages. Each package contains multiple cores. Each core typica...
Profiling with Instruments
In the top left, next to the record and pause button, there will be a "[machine name] > All Processes". Click "All Processes" and select "firefox" from the "Running Applications" section. Click the record button (red circle in top left) Wait for the amount of time that you want to profile Click the stop button Command line tools There is instruments and iprofiler. ...
Profiling with Xperf
...
dtrace
Invocation dtrace must be invoked as the super-user. A good starting command for profiling wakeups is the following. ...
perf
Energy estimates perf can access the Intel RAPL energy estimates. The following example shows how to invoke it for this purpose. ...
powermetrics
powermetrics is a Mac-only command-line utility that provides many high-quality power-related measurements. It is most useful for getting CPU, GPU and wakeup measurements in a precise and easily scriptable fashion (unlike Activity Monitor and top) especially in combination with rapl via the mach power command. This document describes the version of powermetrics that comes with Mac OS 10.10. The one that comes with 10.9 is less powerful. Note: The power profiling overview is worth reading at this point if you haven't already. It may make parts of this document easier to understand. Quick start powermetrics provides a vast number of measurements. The following command encompasses the most useful ones: sudo powermetrics --samplers tasks --show-process-coalition --show-process-gpu -n 1 -...
tools/power/rapl
d-line utility in the Mozilla tree that periodically reads and prints all available Intel RAPL power estimates. These are machine-wide estimates, so if you want to estimate the power consumption of a single program you should minimize other activity on the machine while measuring. Note: The power profiling overview is worth reading at this point if you haven't already. It may make parts of this document easier to understand. Invocation First, do a standard build of Firefox. Mac On Mac, rapl can be run as follows. $OBJDIR/dist/bin/rapl Linux On Linux, rapl can be run as root, as follows. sudo $OBJDIR/dist/bin/rapl Alternatively, it can be run without root privileges by setting the contents of /proc/sys/kernel/perf_event_paranoid to 0. Note that if you do change this file, its contents m...
turbostat
turbostat is a Linux command-line utility that prints various measurements, including numerous per-CPU measurements. This article provides an introduction to using it. Note: The power profiling overview is worth reading at this point if you haven't already. It may make parts of this document easier to understand. Invocation turbostat must be invoked as the super-user: sudo turbostat If you get an error saying "turbostat: no /dev/cpu/0/msr", you need to run the following command: sudo modprobe msr The output is as follows: Core CPU Avg_MHz %Busy Bzy_MHz TSC_MHz SMI CPU%c1 CPU%c3 CPU%c6 CPU%c7 CoreTmp PkgTmp Pkg%pc2 Pkg%pc3 Pkg%pc6 Pkg%pc7 PkgWatt CorWatt GFXWatt - - 799 21.63 3694 3398 0 12.02 3.16 1.71 61.48 49 ...
A brief guide to Mozilla preferences
ults specific to the installed language of Firefox. None of the other preference files contain locale-specific preferences. Config. file A configuration file, usually with .cfg extension, may be called from a default pref file via the general.config.filename preference. This file allows preference locking via the lock_pref() function. Details on the config file is beyond the scope of this document. User pref. files In the profile directory are two user pref files: prefs.js and user.js. prefs.js is automatically generated by the application and should not be edited manually, whereas user.js is an optional file the user can create to override preferences initialized by other preferences files. Preferences Loading and Resolution On application launch, the application loads prefe...
javascript.options.strict
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 ...
Preferences
XUL School: Handling preferences The XUL School tutorial chapter on preferences. Mozilla preference reference A reference guide to all Mozilla preferences; currently a work in progress. ...
Crash reporting
ta in either SQL summary or using mapreduce on the storage cluster. ...
JSHydra
JSHydra is a static analysis tool that is capable of performing analysis of general JavaScript code. It is inspired by the Dehydra and Treehydra tools, which can perform similar tasks in C++ code. In its back-end, it uses the parse tree created by the SpiderMonkey engine. All analysis is performed by running JavaScripts. Documentation Installing JSHydra Download, installation and dependency info for JSHydra Community View JSHydra Forums... Mailing list Newsgroup RSS feed #static on irc.mozilla.org Blogs Joshua Cranmer Related topics Dehydra, Treehydra, SpiderMonkey Categories Interwiki Language Links ...
About NSPR
entation supports Macintosh (PPC), WIN-32 (WinNT, Win9x) and 20 versions of UNIX and is still expanding. The basic API is stable and expected to remain that way. ...
Creating a Cookie Log
. Once you have reproduced the bug, shut down Firefox. Close out of the command prompt/shell/Terminal, and then launch Firefox normally. Finally, attach the cookie-log.txt file to the bug where it was requested (by clicking on Create New Attachment). It should be in C:\temp on Windows, your home directory on Linux, or the Desktop on Mac OS X. Thanks for helping us make Firefox better! Original Document Information Author(s): Mike Connor Last Updated Date: December 4, 2004 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
NSPR's Position On Abrupt Thread Termination
ll of their benefit. Threads are an implementation strategy to provide the illusion of concurrency within a process. They are alternatives to large state machines with mostly non-blocking library functions. When the latter is used to provide concurrency, calling exit() will terminate the entire process. Why would anyone expect a thread to behave differently? Threads are not processes. Original Document Information Author: Alan O. Freier Last Updated Date: December 1998 ...
Nonblocking IO In NSPR
connection on that socket has been closed (end of stream). ...
Optimizing Applications For NSPR
pthreads version of Linux (which is not the default) uses the same signals that NSPR uses to suspend threads in preparation for garbage collection. No solution in hand. OS/2 The OS/2 port is not functional in its current state due to the requirement to remove some files that could not be shipped under the NPL. This problem has been resolved and an update will be appearing shortly. Original Document Information Author: larryh@netscape.com Last Updated Date: December 1, 2004 ...
Process Forking in NSPR
Freier Last Updated Date: 1998 ...
Dynamic Library Linking
ou are done. Platform Notes To use the dynamic library loading functions on some platforms, certain environment variables must be set at run time, and you may need to link your executable programs using special linker options. This section summarizes these platform idiosyncrasies. For more information, consult the man pages for ld and dlopen (or shl_load on HP-UX) for Unix, and the LoadLibrary documentation for Win32. Dynamic Library Search Path Exporting Symbols from the Main Executable Program Dynamic Library Search Path The dynamic library search path is the list of directories in which to look for a dynamic library. Each platform has its own standard directories in which to look for dynamic libraries, plus a customizable list of directories specified by an environment variable. On...
I/O Types
pes Used with Socket Options Functions Type Used with Memory-Mapped I/O Offset Interpretation for Seek Functions Directory Type PRDir File Descriptor Types NSPR represents I/O objects, such as open files and sockets, by file descriptors of type PRFileDesc. This section introduces PRFileDesc and related types. PRFileDesc PRIOMethods PRFilePrivate PRDescIdentity Note that the NSPR documentation follows the Unix convention of using the termfiles to refer to many kinds of I/O objects. To refer specifically to the files in a file system (that is, disk files), this documentation uses the termnormal files. PRFileDesc has an object-oriented flavor. An I/O function on a PRFileDesc structure is carried out by invoking the corresponding "method" in the I/O methods table (a structure of typ...
Introduction to NSPR
ered, so no attempt is made to do so. If the logic of a program allows for timing of waits on conditions, then the clock must be treated as part of the monitored data and the amount of time elapsed re-asserted when the call returns. Philosophically, timeouts should be treated as explicit notifications, and therefore require the testing of the monitored data upon resumption. NSPR Sample Code The documents linked here present two sample programs, including detailed annotations: layer.html and switch.html. In addition to these annotated HTML versions, the same samples are available in pure source form. ...
Network Addresses
es the NSPR types and functions used to manipulate network addresses. Network Address Types and Constants Network Address Functions The API described in this chapter recognizes the emergence of Internet Protocol Version 6 (IPv6). To facilitate the transition to IPv6, it is recommended that clients treat all structures containing network addresses as transparent objects and use the functions documented here to manipulate the information. If used consistently, this API also eliminates the need to deal with the byte ordering of network addresses. Typically, the only numeric declarations required are the well-known port numbers that are part of the PRNetAddr structure. Network Address Types and Constants PRHostEnt PRProtoEnt PR_NETDB_BUF_SIZE Network address functions Initializing a ne...
PRIOMethods
file descriptor. getpeername Get peer's network address. getsockopt Get current setting of specified socket option. setsockopt Set value of specified socket option. Description You don't need to know the type declaration for each function listed in the method table unless you are implementing a layer. For information about each function, see the corresponding function description in this document. For example, the write method in PRIOMethods implements the PR_Write function. For type definition details, see prio.h. The I/O methods table provides procedural access to the functions of the file descriptor. It is the responsibility of a layer implementor to provide suitable functions at every entry point (that is, for every function in the I/O methods table). If a layer provides no functiona...
NSPR
NSPR API Reference The reference describes each API public macro, structure and function in the NSPR API. NSPR build instructions How to checkout and build from source. NSPR release process How to prepare an NSPR release. ...
Deprecated SSL functions
he new SSL shared libraries. Applications that want to use the SSL shared libraries must convert to calling the new replacement functions listed below. Each function name is linked to its entry in the old SSL Reference. The Mozilla Cross Reference (MXR) link for each function provides access to the function definition, prototype definition, and source code references. ...
4.3.1 Release Notes
2 Binary releases are no longer available on mozilla. JSS is a JNI library we provide the jss4.jar but expect you to build the JSS's matching JNI shared library. We provide the jss4.jar in case you do not want to obtain your own JCE code signing certificate. JSS is a JCE provider and therefore the jss4.jar must be signed. ftp://ftp.mozilla.org/pub/mozilla.org/security/jss/releases/JSS_4_3_1_RTM. Documentation Documentation for JSS 4.3.1 is available as follows: Build Instructions for JSS 4.3.1 Javadoc [online] [zipped] Read the instructions on using JSS. Source may be viewed with a browser (via the MXR tool) at http://mxr.mozilla.org/mozilla/source/security/jss/ The RUN TIME behavior of JSS can be affected by the NSS Environment Variables. Platform Information You can check out the source f...
4.3 Release Notes
ar.bz2 Binary releases are no longer available on mozilla. JSS is a JNI library we provide the jss4.jar but expect you to build the JSS's matching JNI shared library. We provide the jss4.jar in case you do not want to obtain your own JCE code signing certificate. JSS is a JCE provider and therefore the jss4.jar must be signed. https://archive.mozilla.org/pub/security/jss/releases/JSS_4_3_RTM/ Documentation Documentation for JSS 4.3 is available as follows: Build Instructions for JSS 4.3 Javadoc [online] [zipped] Read the instructions on using JSS. Source may be viewed with a browser (via the MXR tool) at http://mxr.mozilla.org/mozilla/source/security/jss/ The RUN TIME behavior of JSS can be affected by the NSS Environment Variables. Platform Information JSS 4.3 works with JDK ve...
JSS Provider Notes
The provider's name is "Mozilla-JSS". It implements cryptographic operations in native code using the NSS libraries. Contents Signed JAR file Installing the Provider Specifying the CryptoToken Supported Classes What's Not Supported Signed JAR file JSS 3.2 implements several JCE (Java Cryptography Extension) algorithms. These algorithms have at various times been export-controlled by the US government. ...
Mozilla-JSS JCA Provider notes
The provider's name is "Mozilla-JSS". It implements cryptographic operations in native code using the NSS libraries. Contents Signed JAR file Installing the Provider Specifying the CryptoToken Supported Classes What's Not Supported Signed JAR file JSS implements several JCE (Java Cryptography Extension) algorithms. These algorithms have at various times been export-controlled by the US government. JRE therefore requires that JAR files implementing JCE algorithms be digitally signed by an approved organization. ...
JSS 4.4.0 Release Notes
cks up work done downstream for Fedora and RHEL and used by various Linux distributions with includes:. Support for IPv6. Support for TLS v1.1 and TLS v1.2 via NSS though JSS. Bugs fixed in JSS 4.4.0 This Bugzilla query returns all the bugs fixed in NSS 4.4.0: https://bugzilla.mozilla.org/buglist.cgi?product=JSS&target_milestone=4.4&target_milestone=4.4&bug_status=RESOLVED&resolution=FIXED Documentation Build instructions for JSS at https://hg.mozilla.org/projects/jss/file/tip/README Platform Information You can check out the source from mercurial via hg clone -r 055aa3ce8a61 https://hg.mozilla.org/projects/jss JSS 4.4.0 works with OpenJDK versions 1.7 or higher we suggest the latest - OpenJDK 1.8. JSS 4.4.0 requires NSS 3.12.5 or higher though NSS 3.28.3 is recommended. JS...
NSS 3.17 release notes
VER_ECDHE_KEY option defaults to PR_TRUE, which means the server's ephemeral ECDH key is reused for multiple handshakes. This option does not affect the TLS client code, which always generates a fresh ephemeral ECDH key for each handshake. New Macros in ssl.h SSL_REUSE_SERVER_ECDHE_KEY Notable Changes in NSS 3.17 The manual pages for the certutil and pp tools have been updated to document the new parameters that had been added in NSS 3.16.2. On Windows, the new build variable USE_STATIC_RTL can be used to specify the static C runtime library should be used. By default the dynamic C runtime library is used. Bugs fixed in NSS 3.17 This Bugzilla query returns all the bugs fixed in NSS 3.17: https://bugzilla.mozilla.org/buglist.cgi?resolution=FIXED&classification=Components&query_fo...
NSS 3.31.1 release notes
This notice will be removed when completed. Introduction The Network Security Services (NSS) team has released NSS 3.31.1, which is a patch release for NSS 3.31. Distribution information The hg tag is NSS_3_31_1_RTM. NSS 3.31.1 requires Netscape Portable Runtime (NSPR) 4.15, or newer. NSS 3.31.1 source distributions are available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_31_1_RTM/src/ New in NSS 3.31.1 No new functionality is introduced in this release. Bugs fixed in NSS 3.31.1 Bug 1381784 - Potential deadlock when using an external PKCS#11 token. ...
NSS 3.35 release notes
ermanent in a later NSS release, no change to code is necessary. (Only APIs exported in *.def files are stable APIs.) New experimental functionality provided Below are descriptions of experimental functionality, which might not be available in future releases of NSS. Users of TLS are now able to provide implementations of TLS extensions, through an experimental custom extension API. See the documentation in sslexp.h for SSL_InstallExtensionHooks for more information on this feature. Several experimental APIs were added in support of TLS 1.3 features: TLS servers are able to send session tickets to clients on demand, using the experimental SSL_SendSessionTicket function. This ticket can include arbitrary application-chosen content. An anti-replay mechanism was added for 0-RTT, thro...
NSS Developer Tutorial
eview is usually enough for the review to pass. For critical code reviews, such as a patch release of a stable branch, two reviews may be more reasonable. For new features, especially those that appear controversial, try to find a reviewer from a different company or organization than your own, to avoid any perceptions of bias. Update NSS in mozilla-inbound and mozilla-central The procedure is documented at https://developer.mozilla.org/docs/Updating_NSPR_or_NSS_in_mozilla-central. If it is necessary to apply private patches, please document them in <tree>/security/patches/README. ...
nss tech note1
tes. The number of required templates is determined by the type of the first template.When multiple templates are required, the pointer must point to a NULL-terminated array of templates. The syntax of these templates is identical for both decoders, except where noted. A "NULL Template" is a template that is all zeros, having a zero kind.+ The term "NULL-terminated array", as used throughout this document, means an array of templates, the last of which is a NULL template. void* dest is a pointer to the target area. This is where the decoder stores its output. The type is undefined as it is completely dependent on the content of the decoder templates.+ This typically points to a struct that is described (or partially described) by the templates. PRArenaPool* arena is a pointer to an NSPR aren...
nss tech note3
All About Certificate Extensions NSS Technical Note: 3 09 May 2002 Nelson B. Bolyard This week at least 5 different people came to me with variants of the same question: What certificate extensions do I have to put into my cert for NSS to allow it to be used for purpose <x>?? This message attempts to answer that question, and to document NSS's approach to validating certificates for certain purposes. When NSS is asked to verify the validity of a certificate chain, it verifies the validity of that cert chain for a particular purpose, known as a SECCertUsage, as of a specific date and time. The list of known SECCertUsages is short: certUsageSSLClient ........... An SSL client authentication cert certUsageSSLServer ........... An ordinary SSL server cert certUsageSSLServerWithStepU...
nss tech note5
Using NSS to perform miscellaneous cryptographic operations NSS Technical Note: 5 NSS Project Info is at http://www.mozilla.org/projects/security/pki/nss/ You can browse the NSS source online at http://lxr.mozilla.org/mozilla/source/security/nss/ and http://lxr.mozilla.org/security/ Be sure to look for sample code first for things you need to do. Note: This document contains code snippets that focus on essential aspects of the task and often do not illustrate all the cleanup that needs to be done. Also, this document does not attempt to be an exhaustive survey of all possible ways to do a certain task; it merely tries to show a certain way. Encrypt/Decrypt Include headers #include "nss.h" #include "pk11pub.h" Make sure NSS is initialized.The simplest Init function,...
NSS Tech Notes
TN1: How to use the NSS ASN.1 and QuickDER decoders. TN2: Using the PKCS #11 Module Logger. TN3: All About Certificate Extensions. TN4: Pulling certificate extension information out of SSL certificates. TN5: Using NSS to perform miscellaneous cryptographic operations. ...
NSS release notes template
or Network Security Services (NSS) 3.XX.y is a patch release for NSS 3.XX. The bug fixes in NSS 3.XX.y are described in the "Bugs Fixed" section below. Distribution Information The HG tag is NSS_3_XX_RTM. NSS 3.XX requires NSPR 4.XX or newer. NSS 3.XX source distributions are available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_XX_RTM/src/ (make a link) New in NSS 3.XX New Functionality either: No new functionality is introduced in this release. This is a patch release to fix ... or: ... ...
Notes on TLS - SSL 3.0 Intolerant Servers
URL. The server software will appear next to Server under SSL Certificate Information. For instance, to check https://bugzilla.mozilla.org/, then visit http://toolbar.netcraft.com/site_rep...a.mozilla.org/. Add the information on such a server (software, URL) to bug 59321 at Bugzilla. (Note: You will be asked to provide your email address before you can file a bug at Bugzilla.) Original Document Information Author : Katsuhiko Momoi Last Updated Date: January 27th, 2003 Copyright (C) 2001-2003 Netscape. All rights reserved. ...
Overview of NSS
s one). The NSS libraries passed the NISCC TLS/SSL and S/MIME test suites (1.6 million test cases of invalid input data). Complete Software Development Kit In addition to libraries and APIs, NSS provides security tools required for debugging, diagnostics, certificate and key management, cryptography module management, and other development tasks. NSS comes with an extensive and growing set of documentation, including introductory material, API references, man pages for command-line tools, and sample code. NSS is available as source and shared (dynamic) libraries. Every NSS release is backward compatible with previous releases, allowing NSS users to upgrade to the new NSS shared libraries without recompiling or relinking their applications. Open-Source Licensing and Distribution NSS is avail...
PKCS 12 functions
The public functions listed here perform PKCS #12 operations required by some of the NSS tools and other applications. The Mozilla Cross Reference (MXR) link for each function provides access to the function definition, prototype definition, and source code references. The NSS version column indicates which versions of NSS support the function. ...
PKCS 7 functions
The public functions listed here perform PKCS #7 operations required by mail and news applications and by some of the NSS tools. The Mozilla Cross Reference (MXR) link for each function provides access to the function definition, prototype definition, and source code references. The NSS version column indicates which versions of NSS support the function. ...
Migration to HG
ity/dbm into the new directory lib/dbm. Besides the new layout, the build system hasn't changed. Most parts of the NSS build instructions remain valid, especially the instructions about setting environment variables. Updated instructions for building NSS with NSPR can be found at: /docs/NSS_reference/Building_and_installing_NSS/Build_instructions It's best to refer to the above document to learn about the various environment variables that you might have to set to build on your platform (this part hasn't changed). However, below is a brief summary that shows how to checkout the source code and build both NSPR and NSS: mkdir workarea cd workarea hg clone https://hg.mozilla.org/projects/nspr hg clone https://hg.mozilla.org/projects/nss cd nss # set ...
NSS_Initialize
initialize NSS. Syntax SECStatus NSS_Initialize(const char *configdir, const char *certPrefix, const char *keyPrefix, const char *secmodName, PRUint32 flags); Parameters NSS_Initialize has five parameters: configdir [in] the directory where the certificate, key, and module databases live. To-do: document the "sql:" prefix. certPrefix [in] prefix added to the beginning of the certificate database, for example, "https-server1-". keyPrefix [in] prefix added to the beginning of the key database, for example, "https-server1-". secmodName [in] name of the security module database, usually "secmod.db". flags [in] bit flags that specify how NSS should be initialized. Description NSS_Initialize initializ...
NSS cryptographic module
onList function returns pointers to the functions that implement the default mode of operation. To enable the FIPS mode of operation, use the function FC_GetFunctionList instead to get pointers to the functions that implement the FIPS mode of operation. The NSS cryptographic module also exports the function NSC_ModuleDBFunc for managing the NSS module database secmod.db. The following sections document the data types and functions. PKCS #11 data types PKCS #11 functions in the non-FIPS (default) mode of operation PKCS #11 functions in the FIPS mode of operation NSC_ModuleDBFunc ...
NSS tools : certutil
It can specifically list, generate, modify, or delete certificates, create or change the password, generate new public and private key pairs, display the contents of the key database, or delete key pairs within the key database. Certificate issuance, part of the key and certificate management process, requires that keys and certificates be created in the key database. This document discusses certificate and key database management. For information on the security module database management, see the modutil manpage. Options and Arguments Running certutil always requires one and only one command option to specify the type of certificate operation. Each option may take arguments, anywhere from none to multiple arguments. The command option -H will lis...
NSS tools : ssltab
her than the SSL server to which you are trying to connect, the browser will complain that the host name you are trying to connect to is different from the certificate. If you are using the default BadCert callback, you can still connect through a dialog. If you are not using the default BadCert callback, the one you supply must allow for this possibility. See Also The NSS Security Tools are also documented at [1]http://www.mozilla.org/projects/security/pki/nss/. Additional Resources NSS is maintained in conjunction with PKI and security-related projects through Mozilla dn Fedora. The most closely-related project is Dogtag PKI, with a project wiki at [2]http://pki.fedoraproject.org/wiki/. For information specifically about NSS, the NSS project wiki is located at [3]http://www.mozilla.org/projects/...
NSS tools : ssltap
her than the SSL server to which you are trying to connect, the browser will complain that the host name you are trying to connect to is different from the certificate. If you are using the default BadCert callback, you can still connect through a dialog. If you are not using the default BadCert callback, the one you supply must allow for this possibility. See Also The NSS Security Tools are also documented at [1]http://www.mozilla.org/projects/security/pki/nss/. Additional Resources NSS is maintained in conjunction with PKI and security-related projects through Mozilla dn Fedora. The most closely-related project is Dogtag PKI, with a project wiki at [2]http://pki.fedoraproject.org/wiki/. For information specifically about NSS, the NSS project wiki is located at [3]http://www.mozilla.org/projects/...
gtstd.html
This page is part of the SSL Reference that we are migrating into the format described in the MDN Style Guide. If you are inclined to help with this migration, your help would be very much appreciated. Upgraded documentation may be found in the Current NSS Reference Getting Started With SSL Chapter 2 Getting Started With SSL This chapter describes how to set up your environment, including certificate and key databases. SSL, PKCS #11, and the Default Security Databases Setting Up the Certificate and Key Databases Building NSS Programs SSL, PKCS #11, and the Default Security Databases The basic relationships among the NSS libraries are described in Introduction to Network Security Services. Before running the sample programs, it's important to unde...
pkfnc.html
In particular, these functions are used for obtaining certificates, keys, and passwords. ...
sslcrt.html
This page is part of the SSL Reference that we are migrating into the format described in the MDN Style Guide. If you are inclined to help with this migration, your help would be very much appreciated. Upgraded documentation may be found in the Current NSS Reference Certificate Functions Chapter 5 Certificate Functions This chapter describes the functions and related types used to work with a certificate database such as the cert7.db database provided with Communicator. Validating Certificates Manipulating Certificates Getting Certificate Information Comparing SecItem Objects Validating Certificates CERT_VerifyCertNow CERT_VerifyCertName CERT_CheckCertValidTimes NSS_CmpCertChainWCANames CERT_VerifyCertNow Checks that the current dat...
sslerr.html
In addition to the error codes defined by NSPR, PR_GetError retrieves the error codes described in this chapter. ...
sslfnc.html
This page is part of the SSL Reference that we are migrating into the format described in the MDN Style Guide. If you are inclined to help with this migration, your help would be very much appreciated. Upgraded documentation may be found in the Current NSS Reference SSL Functions Chapter 4 SSL Functions This chapter describes the core SSL functions. SSL Initialization Functions SSL Export Policy Functions SSL Configuration Functions SSL Communication Functions SSL Functions Used by Callbacks SSL Handshake Functions NSS Shutdown Function Deprecated Functions SSL Initialization Functions This section describes the initialization functions that are specific to SSL. For a complete list of NSS initialization functions, see Initialization. Note that at...
sslkey.html
This page is part of the SSL Reference that we are migrating into the format described in the MDN Style Guide. If you are inclined to help with this migration, your help would be very much appreciated. Upgraded documentation may be found in the Current NSS Reference Key Functions Chapter 6 Key Functions This chapter describes two functions used to manipulate private keys and key databases such as the key3.db database provided with Communicator. SECKEY_GetDefaultKeyDB SECKEY_DestroyPrivateKey SECKEY_GetDefaultKeyDB Returns a handle to the default key database opened by NSS_Init. Syntax #include <key.h> #include <keyt.h> SECKEYKeyDBHandle *SECKEY_GetDefaultKeyDB(void); Returns The function returns a handle of type SECKEYKeyDBHandle. Descri...
ssltyp.html
This page is part of the SSL Reference that we are migrating into the format described in the MDN Style Guide. If you are inclined to help with this migration, your help would be very much appreciated. Upgraded documentation may be found in the Current NSS Reference Selected SSL Types and Structures Chapter 3 Selected SSL Types and Structures This chapter describes some of the most important types and structures used with the functions described in the rest of this document, and how to manage the memory used for them. Additional types are described with the functions that use them or in the header files. Types and Structures Managing SECItem Memory Types and Structures These types and structures are described here: CERTCertDBHandle CERTCertifi...
S/MIME functions
The public functions listed here perform S/MIME operations using the S/MIME Toolkit. The Mozilla Cross Reference (MXR) link for each function provides access to the function definition, prototype definition, and source code references. The NSS version column indicates which versions of NSS support the function. ...
modutil-tasks.html
NSS Security Tools: modutil Tasks Newsgroup: mozilla.dev.tech.crypto Task List The jar installation script is very fragile with respect to platform definitions (especially version numbers). A fix was made for "HPUX B.11.00," but issues may still arise for platforms like "Linux 2.2.12-20." Documentation needs to be explicit about the use of Fo ...
NSS Tools certutil
ape Communicator cert8.db and key3.db database files. It can also list, generate, modify, or delete certificates within the cert8.db file and create or change the password, generate new public and private key pairs, display the contents of the key database, or delete key pairs within the key3.db file. Starting from NSS 3.35, the database format was upgraded to support SQLite as described in this document. It means that cert9.db and key4.db files may be targeted instead. The key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database. This document discusses certificate and key database management. For information security module database management, see Using the Security Module Database To...
NSS Tools crlutil
e, modify, or delete CRLs within the NSS security database file(s) and list, create, modify or delete certificates entries in a particular CRL. The key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database(see certutil tool) and continues with certificates expiration or revocation. This document discusses certificate revocation list management. For information on security module database management, see Using the Security Module Database Tool. For information on certificate and key database management, see Using the Certificate Database Tool. Availability See the release notes for the platforms this tool is available on. Syntax To run the Certificate Revocation List Management ...
NSS Tools modutil-tasks
NSS Security Tools: modutil Tasks Newsgroup: mozilla.dev.tech.crypto Task List The jar installation script is very fragile with respect to platform definitions (especially version numbers). A fix was made for "HPUX B.11.00," but issues may still arise for platforms like "Linux 2.2.12-20." Documentation needs to be explicit about the use of Fo ...
certutil
or delete certificates within the database, create or change the password, generate new public and private key pairs, display the contents of the key database, or delete key pairs within the key database. The key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database. This document discusses certificate and key database management. For information security module database management, see the modutil manpages. Options and Arguments Running certutil always requires one (and only one) option to specify the type of certificate operation. Each option may take arguments, anywhere from none to multiple arguments. Run the command option and -H to see the argumen...
NSS tools : crlutil
Mozilla › Projects › NSS › tools › crlutil
e CRLs within the NSS security database file(s) and list, create, modify or delete certificates entries in a particular CRL. The key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database(see certutil tool) and continues with certificates expiration or revocation. This document discusses certificate revocation list management. For information on security module database management, see Using the Security Module Database Tool. For information on certificate and key database management, see Using the Certificate Database Tool. To run the Certificate Revocation List Management Tool, type the command crlutil option [arguments] where options and argument...
NSS tools : modutil
Mozilla › Projects › NSS › tools › modutil
ile. Use this command with the -installdir and -tempdir arguments. The JAR file uses the NSS PKCS #11 JAR format to identify all the files to be installed, the module's name, the mechanism flags, and the cipher flags, as well as any files to be installed on the target machine, including the PKCS #11 module library file and other files such as documentation. This is covered in the JAR installation file section in the man page, which details the special script needed to perform an installation through a server or with modutil. -list [modulename] Display basic information about the contents of the secmod.db file. Specifying a modulename displays detailed information about a pa...
NSS tools : ssltap
Mozilla › Projects › NSS › tools › ssltap
ver to which you are trying to connect, the browser will complain that the host name you are trying to connect to is different from the certificate. If you are using the default BadCert callback, you can still connect through a dialog. If you are not using the default BadCert callback, the one you supply must allow for this possibility. See Also The NSS Security Tools are also documented at [1]http://www.mozilla.org/projects/security/pki/nss/. Additional Resources NSS is maintained in conjunction with PKI and security-related projects through Mozilla dn Fedora. The most closely-related project is Dogtag PKI, with a project wiki at [2]http://pki.fedoraproject.org/wiki/. For information specifically about NSS, the NSS project wiki is located at [3]http://www.
Necko Architecture
...
Necko FAQ
...
Necko Interfaces Overview
...
Multithreading in Necko
rm dependent. For example, on XP_WIN an invisible window is created with a message pump on a background thread for processing WSA asynchronous DNS events. In this way, Necko takes advantage of the platforms specific routines for DNS lookups. The default implementation does not spawn a worker thread, and instead simply calls PR_GetIPNodeByName (essentially equivalent to gethostbyname). Original Document Information Author(s): Darin Fisher Last Updated Date: December 10, 2001 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Necko walkthrough
URI(nsIURI) creates 2 nsIInputStream for read response from; passes them with URI to ... nsDocShell::InternalLoad nsDocShell::DoURILoad opens the nsIChannel for the URI (NS_NewChannel) if "http:", it will be an nsIHttpChannel nsDocShell::DoChannelLoad nsURILoader::OpenURI passes an nsIStreamListener pointer, 'loader' to nsURILoader::OpenChannel - it creates an nsDocumentOpenInfo object, which implements nsIStreamListener, i.e. has OnStartRequest, OnStopRequest, OnDataAvailable, the three functions in which channel responses are received asynchronously. nsHttpChannel::AsyncOpen called from OpenURI; OpenChannel isn't named the best, since the opening happens in the context of OpenURI, its calling function. This is where it hits Necko code. But the...
Proxies in Necko
arting with Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6), proxy servers are not used when accessing hosts with no dots in their names, if manual proxy configuration is used and "<local>" is added to the "No proxy for:" text field field. To be written XXX missing paragraphs are about PAC, and more details about HTTP proxying, and maybe some more details about SOCKS proxies. Original Document Information Author(s): Christian Biesinger Last Updated Date: April 8, 2005 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Pork
ld be possible to make it work on other systems. Note: Pork is not presently used at Mozilla. Please refer to the oink link below for a more up-to-date toolchain. Pork is based on the Elsa (and Oink) tool chain, and the MCPP preprocessor. As of October 2009 Oink incorporates the Pork functionality into its standard distribution; look for files and tests having the prefix "xform". Documentation Installing Pork Download, installation and dependency info for Pork Pork Tools Description of rewriting tools Pork Tool Development in progress page... Old Pork Page Pork details that haven't been moved to MDC Renaming With Pork Sample pork application TODOs Pork 1.0 release tracking bug Pork releases Download Pork h...
Rhino community
There is a much older group, mozilla.dev.tech.js-engine.rhino, that is no longer actively used. Please use the new group instead, but the old one may be of historical interest. The mozilla.dev.tech.js-engine newsgroup answers questions about the C implementation of JavaScript, and was also used for answering questions about Rhino until September 27, 2007. To view archived messages earlier than September 27, 2007, try Google group for the earlier newsgroup. ...
Rhino Examples
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. 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 JavaS...
Rhino license
, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDI...
Rhino overview
Introduction Most people who have used JavaScript before have done so by adding scripts to their HTML web pages. However, Rhino is an implementation of the core language only and doesn't contain objects or methods for manipulating HTML documents. Rhino contains All the features of JavaScript 1.7 Allows direct scripting of Java A JavaScript shell for executing JavaScript scripts A JavaScript compiler to transform JavaScript source files into Java class files A JavaScript debugger for scripts executed with Rhino Language The JavaScript language itself is standardized by Standard ECMA-262 ECMAScript: A general purpose, cross-platform programming language. Rhino 1.3 and greater conform to Edition 3 of the Standard. Rhino 1.6 and greater implement ECMA-357 ECMAScript for XML (E4X).
The JavaScript Runtime
3"] will invoke the get(int, Scriptable) method even though the property name was presented in the script as a string. Similarly, values of numbers that do not fix in integers (like 1.1 and 0x100000000) must be converted to strings. Defining Host Objects Host objects are JavaScript objects that provide special access to the host environment. For example, in a browser environment, the Window and Document objects are host objects. The easiest way to define new host objects is by using ScriptableObject.defineClass(). This method defines a set of JavaScript objects using a Java class. Several of the examples define host objects this way. If the services provided by defineClass are insufficient, try other methods of ScriptableObject and FunctionObject, such as defineProperty and defineFunctionPrope...
Rhino serialization
ion f is compiled to a Java class, but that class is then made available in the classpath so serialization works. This isn't that interesting an example since compiling a function to a class and then loading it accomplishes the same as serializing an interpreted function, but it becomes more relevant if you wish to serialize JavaScript objects that have references to compiled functions. Original Document Information Author: Norris Boyd Last Updated Date: November 15, 2006 Copyright Information: Portions of this content are (C) 1998-2006 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Rhino
Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users. It is embedded in J2SE 6 as the default Java scripting engine. Rhino downloads How to get source and binaries. Rhino documentation Information on Rhino for script writers and embedders. Rhino help Some resources if you get stuck. ...
Rebranding SpiderMonkey (1.8.5)
For example the default brand for SpiderMonkey 1.8.5 is 'mozjs185'. mkdir build-$BRAND-release cd build-$BRAND-release Configure this build of SpiderMonkey with the desired options. For example: ../configure --enable-ctypes --with-system-nspr Note: Your desired configuration may be different. ...
Future directions
Whenever practical, new code and changes should move code closer to the ideal future. And of course, the idea of the future is always evolving in time as things change and we learn more. Concurrent and wasm GC We are working towards a concurrent collector. We would also like to allow WebAssembly to interact with GC-managed data. Parallelism Most machines that run SpiderMonkey have multiple cores, so parallelism is almost certainly part of our future. ...
Tracing JIT
The tracing JIT in SpiderMonkey consists of a generic, low level component called nanojit which is co-maintained between Adobe and Mozilla, and a SpiderMonkey-specific high level component called jstracer. The nanojit component is language agnostic, and contains no knowledge about SpiderMonkey or any other part of the Mozilla codebase. The jstracer component consists of a monitor and a recorder. The monitor watches the executing SpiderMonkey interpreter. When the monitor determines that the interpreter has entered a region of code that would benefit from native compilation, the monitor activates the recorder. ...
JIT Optimization Outcomes
General Outcomes General outcomes shared between various optimization strategies. GenericFailure The optimization attempt failed, and the reason was not recorded. GenericSuccess Optimization succeeded. ...
JS::CompileOptions
iption JSObject *element() const Returns the DOM element to which this source code belongs, if any, or NULL if it belongs to no DOM element. Source belongs to a DOM element in the following cases: Source belongs to a <script> element if it is the element's text content (that is, it is written out as the body of the <script> element in the markup text), or is the source document referenced by its src attribute. Source belongs to a DOM element if it is an event handler content attribute (that is, if it is written out in the markup text as an attribute value). Source belongs to a DOM element if it was assigned to one of the element's event handler IDL attributes as a string. (Note that one may assign both strings and functions to DOM elements' event handler IDL a...
JS::Evaluate
::ReadOnlyCompileOptions &options, const char *filename, JS::MutableHandleValue rval); Name Type Description cx JSContext * The context in which to run the script. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The scope in which to execute the script. This parameter is documented in detail at JS_ExecuteScript. Obsolete since JSAPI 39 scopeChain JS::AutoObjectVector &amp; The scope in which to execute the script. This parameter is documented in detail at JS_ExecuteScript. options JS::ReadOnlyCompileOptions &amp; Compile options. srcBuf JS::SourceBufferHolder &amp; Source buffer containing the script to compile and execute. ...
JSFunction
ons created by running JavaScript code containing function declarations or function-expressions-the relationship between the JSFunction * and the JSObject * is not well-defined. Different closures (Function objects) generated from the same source code may share the same JSFunction. As a result, some APIs (such as JS_CallFunction) that operate on JSFunctions do not work properly with closures. The documentation for each affected API contains a warning about the problem. If the application can't be sure that a given function JSObject is either native or JSAPI-compiled, it must not use the affected APIs. Instead of using JS_CallFunction, for example, it must call JS_CallFunctionValue. Function objects created by calling JS_NewFunction have two reserved slots for the application's use. See JS_NewFunct...
JSNative
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 macros providing equivalent ...
JSObjectOps.enumerate
See bug 408416 for details. The JSObjectOps.enumerate callback implements iteration over object properties. The type of the callback is JSNewEnumerateOp. For native objects, the enumerate callback first checks the JSCLASS_NEW_ENUMERATE flag of the object's class. If the flag is present, enumerate simply delegates the call to JSClass.enumerate. ...
JSScript
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. ...
JS_AddExternalStringFinalizer
ction, described below. The JS engine will automatically call this function each time a string created by JS_NewExternalString is garbage-collected. Callback syntax typedef void (*JSStringFinalizeOp)(JSContext *cx, JSString *str); Name Type Description cx JSContext * Pointer to a JSContext which the finalizer may use for certain very limited operations (not documented). Since the JSStringFinalizeOp callback is called during garbage collection, it must avoid most JSAPI functions. (Is cx guaranteed to be non-NULL?) str JSString * The string being finalized. This is always a string that the application previously created by calling JS_NewExternalString. The callback may use JS_GetStringChars(str) to get a pointer to the character buffer, which is...
JS_BeginRequest
ltithreaded application wants to use a JSContext, it must use JS_BeginRequest and JS_EndRequest to bracket maximal non-blocking hunks of native code that call the JSAPI. This "request model" is necessary to interlock with the global garbage collector. In a JS_THREADSAFE build, many JSAPI functions must only be called from within a request. In this reference, the cx parameter of such functions is documented with the phrase "Requires request", like this: Name Type Description cx JSContext * The context to use. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. In a DEBUG build, this is enforced with assertions. Requests constrain garbage collection. If any thread is in a requests, garbage collection can happen only...
JS_EvaluateScript
const jschar *src, unsigned int length, const char *filename, unsigned int lineno, jsval *rval); Name Type Description cx JSContext * The context in which to run 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. This parameter is documented in detail at JS_ExecuteScript. src const char * or const jschar * String containing the script to compile and execute. length unsigned int The length of src, in characters. filename const 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 t...
JS_EvaluateScriptForPrincipals
s, unsigned int length, const char *filename, unsigned int lineno, jsval *rval, JSVersion version); Name Type Description cx JSContext * The context in which to run 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. This parameter is documented in detail at JS_ExecuteScript. principals JSPrincipals * Pointer to the structure holding the security information for this script. src / bytes / chars const char * or const jschar String containing the script to compile and execute. length unsigned int The length of src, in characters. filename const char * Name of file or URL contain...
JS_ExecuteScriptPart
cuteScriptPart( 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. This parameter is documented in detail at JS_ExecuteScript. script JSScript * The compiled script to execute. part JSExecPart The part of script to execute. rval jsval * Out parameter. On success, *rval receives the value from the last executed expression statement in the script. Description JS_ExecuteScriptPart executes part of a previously compiled script, script. The pa...
JS_GetGlobalObject
for the application to stash the global object, where it is automatically protected from garbage collection and the application can easily access it. ...
JS_LookupProperty
y name appeared to the right of a dot, as in alert(obj.name). JSRESOLVE_ASSIGNING Behave as though the property name appeared on the left-hand side of an assignment. JSRESOLVE_DETECTING Behave as though the name appeared in an idiom like "if (obj.name) ..." or "obj.name ? ... : ...". Objects may pretend that the property does not exist when this flag is set. For example, Mozilla's document.all property is hidden in this way. JSRESOLVE_DECLARING Behave as though the name were being declared in a var, const, or function declaration. JSRESOLVE_CLASSNAME Search for the initial value of a standard class such as Object, Array, or Error. Do not automatically infer and enable other flags by looking at the currently executing bytecode. Notes JS_LookupProperty does not disti...
JS_THREADSAFE
quest. In this reference, these JSAPI functions are marked with the words "Requires request", like this: Name Type Description cx JSContext * The context to use. Requires request. In 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. ...
Parser API
n 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 node implements. The loc field represents the source location information of the node. If the parser produced no information about the node's source location, the field is null; otherwise it is an object consisting of a start position (the position of the first character of the parsed source...
Profiling SpiderMonkey
xpcshell], since the host environments differ. Here are some instrumented tests to work from: media:Profiling-ammo.zip 3.) Once you have some changes you'd like to try, you can just rebuild the js/src directory, since it produces its own shared library, even in libxul and static builds. make -C my-obj-dir/js/src Other Ways To Profile For Linux, there are global jprof functions available. See the documentation on the --enable-jprof mozconfig option. We're working to add support for other profilers, such as OProfile, Intel VTune, and Callgrind. When we have JS scriptable profiling options available for all tier 1 platforms, we'll look at adding global start/stop profiling functions. If you'd like to profile something at a higher level of detail than the JS Shark functions allow, there are correspon...
SpiderMonkey 1.8.5
andatory. JSNative, JSFastNative Previous versions of JSAPI supported two types of native functions -- JSNative and JSFastNative. The so-called "Slow Natives" are no longer supported; as such JSFastNative has been renamed to JSNative and relevant interfaces have been updated accordingly. Embedders converting functions from old-JSNative to new-JSNative (JSFastNative) should study the JSFastNative documentation thoroughly, and pay particular that they do not reference negative indices of argv in SpiderMonkey 1.8.5; the JS_CALLEE, JS_THIS, etc. macros must be used instead. See bug 581263. Global Objects Global objects have been specialized, and must be be created with either JS_NewGlobalObject or JS_NewCompartmentAndGlobalObject. JS_NewObject and JS_NewObjectWithGivenProto remain the correct APIs f...
SpiderMonkey 1.8.7
andatory. JSNative, JSFastNative Previous versions of JSAPI supported two types of native functions -- JSNative and JSFastNative. The so-called "Slow Natives" are no longer supported; as such JSFastNative has been renamed to JSNative and relevant interfaces have been updated accordingly. Embedders converting functions from old-JSNative to new-JSNative (JSFastNative) should study the JSFastNative documentation thoroughly, and pay particular that they do not reference negative indices of argv in SpiderMonkey 1.8.5; the JS_CALLEE, JS_THIS, etc. macros must be used instead. See bug 581263. Global Objects Global objects have been specialized, and must be be created with either JS_NewGlobalObject or JS_NewCompartmentAndGlobalObject. JS_NewObject and JS_NewObjectWithGivenProto remain the correct APIs f...
SpiderMonkey 31
as JS::Value or JS::Value*, to JS::Handle and JS::MutableHandle template types that encapsulate access to the provided value/string/object or its location. The JS::Handle<JS::Value> and JS::MutableHandle<JS::Value> classes have been specialized to implement the same interface as JS::Value, for simplicity and to ease migration pain. Changes to introduce handles to the JSAPI are not individually documented, because of the breadth of the changes involved. The following features in earlier versions of SpiderMonkey have been dropped. XXX list removed features here SpiderMonkey 31 is not binary-compatible with previous releases, nor is it source-code compatible. Many JSAPI types, functions, and callback signatures have changed, though most functions that have changed still have the same names a...
SpiderMonkey 38
as JS::Value or JS::Value*, to JS::Handle and JS::MutableHandle template types that encapsulate access to the provided value/string/object or its location. The JS::Handle<JS::Value> and JS::MutableHandle<JS::Value> classes have been specialized to implement the same interface as JS::Value, for simplicity and to ease migration pain. Changes to introduce handles to the JSAPI are not individually documented, because of the breadth of the changes involved. The following features in earlier versions of SpiderMonkey have been dropped. XXX list removed features here SpiderMonkey 38 is not binary-compatible with previous releases, nor is it source-code compatible. Many JSAPI types, functions, and callback signatures have changed, though most functions that have changed still have the same names a...
Running Parsemark
SpiderMonkey front-end. The intent is to run a dozen or so large-payload JS sites globbed up from across the web. Yes, it includes GMail. Here's how you get your mitts on it. The test files are not checked into the source tree because they're non-Mozilla JS code. Download the suite of parse tests from Bug 548621 and decompress them. Within js/src/tests, run python parsemark.py -h to see help documentation. Generally you'll want to capture JSON results for your baseline and compare them to the results for the "current" version of your shell. A typical run can be done like so: cd js/src/tests python parsemark.py /path/to/baseline/js /path/to/parse-tests-dir/ -q > /tmp/baseline.json python parsemark.py /path/to/current/js /path/to/parse-tests-dir/ -q > /tmp/current.json python compare_bench.
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 t...
Mozinfo
...
Exploitable crashes
ble crashes Exploitable crashes are most often discovered through normal testing and usage, when developers recognize a crash stack in gdb or submitted to a bug as exploitable. Additionally, Mozilla developers make heavy use of two tools in particular to find exploitable situations before they show up as exploitable crash reports. The first tool is AddressSanitizer (ASAN). There is an MDN article documenting its use with Mozilla projects. The other tool is Valgrind. There is an MDN article documenting its use with Mozilla projects. Next steps Once you've determined that a crash is potentially exploitable, take the following steps. If you need help with any of the steps (e.g. perhaps you lack necessary bugzilla privileges) please email security@mozilla.org. Make sure a bug is on file. Mark the b...
Setting up an update server
Obtaining an update MAR Updates are served as MAR files. There are two common ways to obtain a MAR to use: download a prebuilt one, or build one yourself. Downloading a MAR Prebuilt Nightly MARs can be found here on archive.mozilla.org. Be sure that you use the one that matches your machine's configuration. For example, if you want the Nightly MAR from 2019-09-17 for a 64 bit Windows machine, you probably want the MAR located at https://archive.mozilla.org/pub/firefox/nightly/2019/09/2019-09-17-09-36-29-mozilla-central/firefox-71.0a1.en-US.win64.complete.mar. Prebuilt MARs for release and beta can be found here. ...
Supported build targets
Page moved to the in-tree documentation: https://firefox-source-docs.mozilla.org/build/buildsystem/supported-configurations.html ...
Task graph
, and so on, appear attached to each task when it completes. These are viewable in the Task Inspector. All of this is controlled from within the Gecko source code, through a process called task-graph generation. This means it's easy to add a new job or tweak the parameters of a job in a try push, eventually landing that change on an integration branch. The details of task-graph generation are documented in the source code itself, including a some quick recipes for common changes. ...
Gecko object attributes
bars with list items that are formatted with CSS display: inline. Applied to: any object that supports the hypertext interface Note: deprecated, use display attribute instead line-number The current line number of the caret, whether simply because the "browse with caret" option is on, or the caret used for editing text. The line number is relative to the top of the currently focused area (the document, a rich text editable area, or an input control). Applied to: any focusable accessible text object margin-bottom Specifies how much vertical space there will be after the bottom of the last line of content in a text accessible (see the CSS margin-bottom property). margin-left Specifies how much horizontal space there will be before the beginning of each line of content in a text accessi...
AT Development
s gives access to MSAA and IAccessible2. References AT APIs Implementation References Shows how Gecko handles ATK, IAccessible2, MSAA and Universal Access API Accessible Web Specifications References Provides the map of reflecting web specification to AT APIs. This page includes: ARIA References - W3C specification reflecting ARIA mapping into AT APIs. XForms References - Gecko documentation showing how XForms controls are mapped to AT APIs. ...
Accessibility API Implementation Details
We provide for them the support of these products on Windows, Linux/Unix and OS X platforms.AT DevelopmentThe accessibility of computer software has seen drastic improvements over the past two decades. This article (from 2007) reviews the progress and technology as it has developed. ...
Mork
Mozilla › Tech › Mork
You pass in a file to ParseFile, select the tables, and then pass in callback functions for the meta-row and row enumeration functions. GetTableIDs is provided for convenience's sake, and is mostly expected to be used only by the morkreader tests. All data stored internally will be destroyed when the MorkReader goes out of scope. More detail about individual functions can be found by reading the documentation included in MorkReader.h. There is in the test directory a program called TestMorkReader. If you wish to just display a mork file, most of the code in this file can be copied to display it to you. ...
The Places database
Places is designed to be a complete replacement for the Firefox bookmarks and history systems using Storage. The places schema looks like so: Core URL table moz_places: This is the main table of URIs and is managed by the history service (see also History service design). Any time a Places component wants to reference a URL, whether visited or not, it refers to this table. Each entry has an optional reference to the moz_favicon table to identify the favicon of the page. No two entries may have the same value in the url column. moz_hosts: One entry in this table is created each time you visit a new host. ...
History Service Design
Places is designed to be a complete replacement for the Firefox bookmarks and history systems using Storage. This system provides additional performance, flexibility, and querying capabilities over the old one, for both end users and extensions developers. View the service interface definition: nsINavHistoryService.idl. ...
Retrieving part of the bookmarks tree
Bookmarks are retrieved using the Places query system. For more basic bookmarks examples, see Manipulating bookmarks using Places. Get the query and options objects All querying is done through the history service. First, you need to get an empty query and options objects from the history service: var historyService = Components.classes["@mozilla.org/browser/nav-history-service;1"] .getService(Components.interfaces.nsINavHistoryService); var options = historyService.getNewQueryOptions(); var query = historyService.getNewQuery(); Find the folder you want to get Known folder IDs are retrieved from the bookmarks service. ...
Fun With XBL and XPConnect
arch. ...
Generic factory
...
XPCOM array guide
Mozilla › Tech › XPCOM › Guide › Arrays
The standard array classes are: nsIArray - a scriptable container for scriptable XPCOM objects. ...
How to build an XPCOM component in JavaScript
nents = [HelloWorld]; and replace NSGetFactory/NSGetModule to use this array and XPCOMUtils: if ("generateNSGetFactory" in XPCOMUtils) var NSGetFactory = XPCOMUtils.generateNSGetFactory(components); // Firefox 4.0 and higher else var NSGetModule = XPCOMUtils.generateNSGetModule(components); // Firefox 3.x So the total simplified version of your component now looks like (of course documentation and comments aren't a bad thing, but as a template something smaller is nice to have): Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); function HelloWorld() { } HelloWorld.prototype = { classDescription: "My Hello World JavaScript XPCOM Component", classID: Components.ID("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractID: "@dietrich.ganx4.com/hell...
XPCOM changes in Gecko 2.0
Several changes that affect XPCOM component compatibility are taking place in Gecko 2. This article details those changes, and provides suggestions for how 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, si...
An Overview of XPCOM
a memory allocation fails. NS_ERROR_FACTORY_NOT_REGISTERED Returned when a requested class is not registered. << 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 derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. ...
Component Internals
houldn't have to link to the XPCOM library to create a XPCOM component - in fact, if your component has to, then something is wrong. << 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 derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. ...
Creating the Component Code
} return rv; } Note: non-null-out The CreateInstance method guarantees that if the out variable is non-null, it is valid. << 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 derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. ...
Packaging WebLock
tion of the DOM of a web page. In other words, the fragment initInstall() from the script is equivalent to Install.initInstall(). << 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 derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. ...
Resources
XPIDL xpidl Compiler Reference General Development Resources The World Wide Web Consortium URL specification at the W3 GNU Make << Previous 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 derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. ...
Setting up the Gecko SDK
) -o $@ -Wl,-soname=$(MODULE).so $(CPPSRCS:%.cpp=%.o) $(GECKO_LDFLAGS) chmod +x $@ build: $(MODULE).so clean: rm $(MODULE).so << 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 derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. ...
XPCOM Stream Guide
Mozilla › Tech › XPCOM › Guide › Streams
tStream, it is also a seekable stream...so we could go to * the beginning if we wanted to.) */ var str1 = store.newInputStream(0); var d1 = new InputStream(str1); // d1 has a complete copy of baseInputStream's original contents. var d2 = new InputStream(store.newInputStream(0)); // d2 has a complete copy of baseInputStream's original contents. }); } Parsing a DOM document from an input stream ...
How to build a binary XPCOM component using Visual Studio
gecko-sdk-win32-msvc-1.8.0.4.zip. Extract the SDK to a folder. The tutorial assumes the folder is called xulrunner-1.8.0.4, but you can call yours whatever you want. You also need a couple of pre-built libraries (glib-1.2.dll & libIDL-0.6.dll) from the wintools.zip archive. Copy glib-1.2.dll & libIDL-0.6.dll into the bin subfolder of gecko-sdk. Note: wintools.zip seems old and lots of newer MDC documentation refers to moztools.zip archive, but the version of xpidl.exe that comes with the gecko-sdk crashes with the DLL's from moztools. Recap: Use the right Gecko SDK for your XULRunner release Use a Microsoft compiler Use pre-built glib-1.2.dll & libIDL-0.6.dll libraries from wintools.zip Download the sample project Here is what the folder structure looks like: Create a VC++ Project Visu...
Components.classes
stance() method for you. You still have to provide the interface name each time you create an instance, which is not necessary when using Components.Constructor. Determining if a component has to be instantiated or used as a service In the general case it is not possible to programmatically determine if a given component has to be instantiated or used as a service. Often, this is stated in the documentation of the component you want to use. If this is not the case, you might want to try and find example usages of that component within MXR. ...
Components.utils.Sandbox
nodePrincipal property of a DOM node as an nsIDOMWindow, such as that returned by the DOM window property as a string URI like "http://www.example.com/" (discouraged) When possible, specify a window or an nsIPrincipal object instead of using a string URI. Window objects and nsIPrincipal carry additional information such as origin attributes and same-origin privilege changes caused by setting document.domain. Example of obtaining content principal from the window: var principal = gBrowser.selectedTab.linkedBrowser.contentPrincipal; var sandbox = Components.utils.Sandbox(principal); Expanded principal An expanded principal is specified as an array of the principals it subsumes. Each item in the array should be an nsIPrincipal, a DOM window, or a URI. So this can be simply an array with a s...
Components.utils.evalInSandbox
f 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
.getService(Components.interfaces.mozIJSSubScriptLoader); loader.loadSubScript(someURL, obj1); loader.loadSubScript(someURL, obj2); assert(obj2 === obj1); ...returns false. This means Components.utils.import is better suited for efficient sharing of code (and data?) between JS scripts running in different scope. Additional Resources Components.utils bug 238324 The documentation in xpccomponents.idl The tests in js/xpconnect/tests/unit/ Importing SDK/CommonJS modules into other code ...
Components.utils.unload
d to load the script. ...
Components.utils.unwaiveXrays
o; // undefined // you can waive Xray vision for an object var waived = Components.utils.waiveXrays(gBrowser.contentWindow); isXray = Components.utils.isXrayWrapper(waived); // false foo = waived.foo; // "I'm an expando" // waiving is transitive isXray = Components.utils.isXrayWrapper(waived.document); // false // use unwaiveXrays to undo the waiver var unwaived = Components.utils.unwaiveXrays(waived); isXray = Components.utils.isXrayWrapper(unwaived); // true foo = unwaived.foo; // undefined // unwaiving is transitive isXray = Components.utils.isXrayWrapper(unwaived.document); // true ...
Components.utils.waiveXrays
o; // undefined // you can waive Xray vision for an object var waived = Components.utils.waiveXrays(gBrowser.contentWindow); isXray = Components.utils.isXrayWrapper(waived); // false foo = waived.foo; // "I'm an expando" // waiving is transitive isXray = Components.utils.isXrayWrapper(waived.document); // false ...
JavaXPCOM
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 on how to embed Gecko or init XPCOM from within Java. Embedding Mozilla in a Java Application using JavaXPCOM XULRunner ships w...
PyXPCOM
-XPCOM bridge) or XPConnect (JavaScript-XPCOM bridge). Mozilla defines many external interfaces available to embeddors and component developers. PyXPCOM provides access to these interfaces as Python interfaces. PyXPCOM also contains several classes that provide access to functions for initializing and shutting down XPCOM and Gecko from Python, as well as some XPCOM helper functions. Documentation Building PyXPCOM The instructions for building PyXPCOM. Creating a Python XPCOM component An example of how to create a simple XPCOM component with Python. Getting to know PyXPCOM PyXPCOM is a bridging technology between XPCOM and Python. This article gives you a head start to PyXPCOM. N...
XPConnect wrappers
For practical advice on dealing with wrappers, see Safely accessing content DOM from chrome. Developers in the know understand that wrappers play a large role in XPConnect, and that we have a lot of them. Less informed developers understand that wrappers exist and are somehow important, but they don't know when they should use what wrappers, or if 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. ...
nsIProfile
...
nsIRegistry
It works like this. var Cc = Components.classes; var Ci = Components.interfaces; var rc = Cc["@mozilla.org/registry;1"]; var rs = rc.getService(Ci.nsIRegistry); Now you have the registry service. rs.openWellKnownRegistry(2); // 2 signifies the ApplicationRegistry, if I understand right var st = rs.enumerateAllSubtrees(2); // 2 signifies "common", see libreg source (reg.h) for info Now you have an nsIEnumerator that can report the subtrees. ...
XPConnect
Using components How to talk with XPCOM components. XPConnect and XPIDL FAQ A FAQ about using XPConnect and XPIDL. ...
NS_InitXPCOM2
ify that the current working directory should be used. aAppFileLocationProvider [in] The object to be used by XPCOM to locate application specific directories and files (e.g., the user profile, the component registry, etc.). This parameter may be nsnull. Return Values The NS_InitXPCOM2 function returns NS_OK if successful. Otherwise, it returns an error code. Some of the possible errors are documented below: NS_ERROR_NOT_INITIALIZED Indicates that static globals were not yet initialized, which may happen if this method is called before XPCOM's static initialization code executes. This error may also occur if XPCOM is being initialized after NS_ShutdownXPCOM has been called. Remarks You must call NS_InitXPCOM2 (or NS_InitXPCOM3) before proceeding to use XPCOM in a process. The one excep...
NS_InitXPCOM3
etc.). This parameter may be nsnull. aStaticModules [in] An array of nsStaticModuleInfo objects. Passing null causes the default (built-in) static modules to be registered, if present. aStaticModuleCount [in] The number of elements in aStaticModules. Return Values The NS_InitXPCOM3 function returns NS_OK if successful. Otherwise, it returns an error code. Some of the possible errors are documented below: NS_ERROR_NOT_INITIALIZED Indicates that static globals were not yet initialized, which may happen if this method is called before XPCOM's static initialization code executes. This error may also occur if XPCOM is being initialized after NS_ShutdownXPCOM has been called. Remarks You must call NS_InitXPCOM3 (or NS_InitXPCOM2) before proceeding to use XPCOM in a process. The one excep...
IAccessibleRelation
ationType Return value S_OK. nTargets() Returns the number of targets() for this relation. [propget] HRESULT nTargets( [out] long nTargets ); Parameters nTargets Return value S_OK. relationType() Returns the type of the relation. [propget] HRESULT relationType( [out] BSTR relationType ); Parameters relationType The strings returned are defined @ref grpRelations "in this section of the documentation". Return value S_OK. target() Returns one accessible relation target. [propget] HRESULT target( [in] long targetIndex, [out] IUnknown target ); Parameters targetIndex 0 based index. target Return value E_INVALIDARG if bad [in] passed, [out] value is null. S_FALSE if there is nothing to return, [out] value is null. S_OK. targets() Returns multiple accessible relation targets. [propge...
IAccessibleTable
the data depends on how the server manages the life cycle of its objects. Also, note that the server may have different life cycle management strategies for controls depending on whether or not a control manages its children. Lists, trees, and tables can have a large number of children and thus it's possible that the child objects for those controls would only be created as needed. Servers should document their life cycle strategy as this will be of interest to assistive technology or script engines accessing data out of process or from other threads. Servers only need to save the most recent row and column values associated with the change and a scope of the entire application is adequate. [propget] HRESULT modelChange( [out] IA2TableModelChange modelChange ); Parameters modelChange A struct ...
IAccessibleTable2
the data depends on how the server manages the life cycle of its objects. Also, note that the server may have different life cycle management strategies for controls depending on whether or not a control manages its children. Lists, trees, and tables can have a large number of children and thus it's possible that the child objects for those controls would only be created as needed. Servers should document their life cycle strategy as this will be of interest to assistive technology or script engines accessing data out of process or from other threads. Servers only need to save the most recent row and column values associated with the change and a scope of the entire application is adequate. [propget] HRESULT modelChange( [out] IA2TableModelChange modelChange ); Parameters modelChange A struct ...
imgIContainer
er Attempts to create an ImageContainer (and Image) containing the current frame. Only valid for RASTER type images. ImageContainer getImageContainer(); Parameters None. Return value Missing Description Exceptions thrown Missing Exception Missing Description Violates the XPCOM interface guidelines GetRootLayoutFrame() If this image is TYPE_VECTOR, that is really an embedded SVG document, and this method returns a pointer to the root nsIFrame of that document. If not (or if the root nsIFrame is not available for some reason), this method returns nsnull. "notxpcom" for convenience, since we have no need for nsresult return-val. nsIFrame GetRootLayoutFrame(); Parameters None. Return value Missing Description Exceptions thrown Missing Exception Missing Description Viol...
mozIStorageConnection
e method was called on a thread other than the one that 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 transaction...
mozIStorageStatementParams
Enumeration of properties You can also enumerate all the properties on this object with a for..in enumeration: // valuesToBind is an object that contains key-value pairs // to bind to the statement before executing it. for (let param in statement.params) statement.params[param] = valuesToBind[param]; ...
mozIStorageValueArray
storage/public/mozIStorageValueArray.idlScriptable Please add a summary to this article. ...
mozIThirdPartyUtil
l, determine whether it is foreign with respect to aURI, and return. Find the URI of the channel and determine whether it is third party with respect to the URI of the channel. If so, return. Obtain the bottommost nsIDOMWindow, and its same-type parent if it exists, from the channel's notification callbacks. Then: If the parent is the same as the bottommost window, and the channel has the LOAD_DOCUMENT_URI flag set, return false. This represents the case where a toplevel load is occurring and the window's URI has not yet been updated. (We have already checked that aURI is not foreign with respect to the channel URI.) Otherwise, return the result of isThirdPartyWindow() with arguments of the channel's bottommost window and the channel URI, respectively. Therefore, both the channel's URI and e...
nsIAbCard
Properties aren't stored anymore on the card, except for a handful of them. Complex properties are expected to be accessed through a call to getProperty. See //github.com/RealityRipple/UXP/blob/master//mailnews/addrbook/public/nsIAbCard.idl for more details. ...
GetAccessibleRelated
Return value Returns an accessible which is related to the one provided by the given relation type. ...
GetRelation
AccessibleRelation getRelation( in unsigned long aIndex ); Parameters aIndex[in] The index for which relation is to be retrieved. Return value Returns nsIAccessibleRelation object for this accessible. Exception thrown NS_ERROR_INVALID_ARG Indicates that the given index is invalid. Remark Currently we do not support multiple relations so the zero index may be valid only. Refer to relations documentation for more info. See Also nsIAccessible.relationsCount nsIAccessible.getRelations() nsIAccessible.getAccessibleRelation() ...
GetState
<< nsIAccessible Page Summary This method retrieves states of the accessible. void getState( out unsigned long aState, out unsigned long aExtraState ); Parameters aState[out] The first bit field (See STATE_* constants in states documentation).aExtraState[out] The second bit field (See EXT_STATE_* constants in states documentation). Exceptions thrown NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. Remarks Accessible states are stored as bit fields which describe boolean properties of node. Many states are only valid given a certain role attribute that supports them. Refer to states documentation for more information. ...
Role
attribute unsigned long role; ...
DeleteText
Documentation is now located at nsIAccessibleEditableText.DeleteText(). ...
nsIAppShellService
These windows are generally shown in the Windows taskbar...
nsIArray
ctionality for retrieving elements at a specific position, searching for elements. Indexes are zero-based, such that the last element in the array is stored at the index length-1. For an array which can be modified, see nsIMutableArray. Neither interface makes any attempt to protect the individual elements from modification. The convention is that the elements of the array should not be modified. Documentation within a specific interface should describe variations from this convention. It is also convention that if an interface provides access to an nsIArray, that the array should not be QueryInterfaced to an nsIMutableArray for modification. If the interface in question had intended the array to be modified, it would have returned an nsIMutableArray! null is a valid entry in the array, and as suc...
nsIBidiKeyboard
use GTK+ API instead. ...
nsIBrowserBoxObject
s article. Inherits from: nsIContainerBoxObject Last changed in Gecko 1.9 (Firefox 3) The boxObject belonging to a XUL browser element implements this interface. Note: Please consider using nsIContainerBoxObject instead. Attributes Attribute Type Description docShell nsIDocShell Read only. Obsolete since Gecko 1.9 The nsIDocShell object that manages the contained document. The browser.xml binding uses this property to gain access to the webNavigation, contentDocument, contentWindow, webBrowserFind, webProgress and sessionHistory properties. ...
nsICacheService
along with the creating of cache sessions and creation of temporary client IDs operations for offline caching. 66 Introduced Gecko 1.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) This interface is no longer supported and planned to be removed soon: use nsICacheStorageService instead. At the time of writing there is no documentation for nsICacheStorageService but comments are available in the source. Note: Starting in Gecko 2.0, cache I/O is handled asynchronously. Method overview nsICacheSession createSession(in string clientID, in nsCacheStoragePolicy storagePolicy, in boolean streamBased); ACString createTemporaryClientID(in nsCacheStoragePolicy storagePolicy); Obsolete since Gecko 1.9.2 ...
nsIChromeRegistry
chrome/public/nsIChromeRegistry.idlScriptable Provides access to the chrome registry; you can use this to get information about chrome documents that have been registered. Inherits from: nsISupports Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Implemented by: @mozilla.org/chrome/chrome-registry;1 as a service: var chromeRegistry = Components.classes["@mozilla.org/chrome/chrome-registry;1"] .getService(Components.interfaces.nsIChromeRegistry); Method overview void canonify(in nsIURI aChromeURL); Obsolete since Gecko 1.8 void checkForNewChrome(); nsIURI convertChromeURL(in nsIURI aChromeURL); boolean wrappersEnabled(in nsIURI aURI); Violates the XPCOM interface guidelines Constants Co...
nsICommandController
Inherits from: nsISupports Last changed in Gecko 1.7 Implemented by: @mozilla.org/embedcomp/base-command-controller;1. ...
nsIComponentManager
aIID, [iid_is(aIID),retval] out nsQIResult result); void removeBootstrappedManifestLocation(in nsILocalFile aLocation); Methods addBootstrappedManifestLocation() Loads a "bootstrapped" chrome.manifest file from the specified directory or XPI file. A "bootstrapped" chrome manifest supports some of the instructions allowed in a regular chrome manifest, see the Chrome Registration documentation for details. This method was introduced in Gecko 8 to let bootstrapped add-ons provide content at chrome:// URIs. Until Gecko 10 you had to call this method manually from within the add-on's startup() method (with a matching removeBootstrappedManifestLocation() call in the add-on's shutdown() method). If you're targeting Gecko 10 or higher there should be no need to call this method, since...
nsIContainerBoxObject
rBoxObject.idlScriptable Please add a summary to this article. 1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) The boxObject belonging to a XUL browser, editor or iframe element implements this interface. Attributes Attribute Type Description docShell nsIDocShell Read only. The nsIDocShell object that manages the contained document. The browser.xml, editor.xml and general.xml bindings use this property to gain access to other properties such as webNavigation, contentDocument and contentWindow. ...
nsIContentFrameMessageManager
SyncMessageSender This interface provides the environment for scripts that are loaded into content frames using the nsIFrameScriptLoader interface. It enables these scripts to receive messages from the chrome process and send messages back to the chrome process. Frame scripts can send either synchronous or asynchronous messages to the chrome process: for details on these messaging APIs see the documentation for the nsIContentFrameMessageManager's parent classes nsISyncMessageSender and nsIMessageSender. Methods void dump(in DOMString aStr); DOMString atob(in DOMString aAsciiString); DOMString btoa(in DOMString aBase64Data); dump() Prints the specified string to standard output. Parameters Name Type Description aStr String ...
nsIContentViewManager
See Getting access to content views for details. ...
nsIController
Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void doCommand(in string command); boolean isCommandEnabled(in string command); void onEvent(in string eventName); boolean supportsCommand(in string command); Methods doCommand() When this method is called, your implementation should execute the command with the specified name. void doCommand( in string command ); Parameters command The name of the command to execute. isCommandEnabled() Implement this method to indicate whether or not the specified command is enabled. ...
nsIControllers
Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) This interface is used to manage instances of the nsIController interface. Windows and text inputs have default controllers that allow commands such as cmd_copy to act on the focused element or window. XUL elements can also have controllers, although they do not have any default controllers. Implemented by: @mozilla.org/xul/xul-controllers;1. You should not normally need to create an instance, as you normally need to alter the window or element's existing list of controllers. ...
nsIDBChangeListener
e message that is changing. aPreChange True on first call before change, false on second call after change. aStatus The storage location provided by calling routine for status. aInstigator The caller who added the header. This can be used to filter out events that you yourself started. aInstigator may also be null. onEvent() Generic notification for extensibility. Common events should be documented here so we have a hope of keeping the documentation up to date. Current events are: DBOpened When a pending listener becomes real. This can happen when the existing db is force closed and a new one opened. Only registered pending listeners are notified. void onEvent(in nsIMsgDatabase aDB, in string aEvent); Parameters aDB The nsIMsgDatabase that is changing. aStrin...
nsIDOMChromeWindow
); Parameters aCycleCount The maximum number of times to animate the window per system conventions. If set to -1, cycles indefinitely until window is brought into the foreground. This behavior is same as getAttention method. maximize() Maximizes the window. void maximize(); Parameters None. minimize() Minimizes the window. void minimize(); Parameters None. notifyDefaultButtonLoaded() When a document has been loaded, the document can notify the default button of the document to the window by using this method. When this method is called on Windows, Gecko moves the mouse cursor to center of the button if the auto cursor snap setting is enabled on the system. However, when the window isn't active at that time, the cursor isn't moved. On other systems, this method doesn't have any reaction curre...
nsIDOMElement
dom/interfaces/core/nsIDOMElement.idlScriptable This interface represents an element in an HTML or XML document. Inherits from: nsIDOMNode Last changed in Gecko 1.7 Method overview DOMString getAttribute(in DOMString name); nsIDOMAttr getAttributeNode(in DOMString name); nsIDOMAttr getAttributeNodeNS(in DOMString namespaceURI, in DOMString localName); DOMString getAttributeNS(in DOMString namespaceURI, in DOMString localName); nsIDOMNodeList getElementsByTagName(in DOMString name); nsIDOMNodeList getElementsByTagNameNS(in DOMString namespaceURI, in DOMString localName); boolean hasAttribute(in DOMString name); boolean hasAttributeNS(in DOMString namespaceURI, in DOMString localName); void removeAttribute(in DOMString name) nsIDOMAttr removeAttributeNode(in nsID...
nsIDOMEventTarget
dom/interfaces/events/nsIDOMEventTarget.idlScriptable This interface is the interface implemented by all event targets in the Document Object Model. Inherits from: nsISupports Last changed in Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) See the EventTarget documentation. ...
nsIDOMFile
See also nsIDOMFileList nsIDOMFileException DataTransfer Drag and drop ...
nsIDOMFileList
See also FileList DataTransfer Drag and Drop ...
nsIDOMFileReader
mmary to this article. Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Inherits from: nsISupports Implemented by: @mozilla.org/files/filereader;1. To create an instance, use: var FileReader = Components.classes["@mozilla.org/files/filereader;1"].createInstance(Components.interfaces.nsIDOMFileReader); This interface implements the DOM FileReader object; see that documentation for details. Examples OS.File for the main thread - Example - Save Canvas to Disk See also File API Specification Working Draft nsIDOMFile nsIDOMFileList nsIDOMFileException ...
nsIDOMGlobalPropertyInitializer
cko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) An XPCOM component implementing this interface can be exposed to web content as a property on the window. See Custom window properties are a snap in Firefox blog post for details. An alternative way to expose an object to the web content is to add the property in response to the content-document-global-created notification. Method overview jsval init(in nsIDOMWindow window); Methods init() jsval init( in nsIDOMWindow window ); Parameters window The window to which the global property is being attached. Return value The initialized global property. Ensure that you never return any internal XPCOM objects to untrusted code. It is also recommended to use __expose...
nsIDOMJSWindow
One of the interfaces implemented by the window DOM object. This is only a magic interface to provide the JS implementation of a dom window and it should never be used by embedders, the ordinary DOM documentation should cover the rest. The interface is defined in dom/interfaces/base/nsIDOMJSWindow.idl. page composed by Sebastian Gurin <sgurin@(nospam)montevideo.com.uy ...
nsIDOMUserDataHandler
ata method. 1.0 66 Introduced Gecko 1.5 Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) Method overview void handle(in unsigned short operation, in DOMString key, in nsIVariant data, in nsIDOMNode src, in nsIDOMNode dst); Constants Constant Value Description NODE_CLONED 1 The node was cloned. NODE_IMPORTED 2 The node was cloned into a new document. NODE_DELETED 3 Unimplemented NODE_RENAMED 4 Unimplemented NODE_ADOPTED 5 The node was adopted into a new document. Methods handle() This method is a callback which will be called if a node with user data is being cloned, imported or adopted. void handle( in unsigned short operation, in DOMString key, in nsIVariant data, in nsIDOMNode src, in nsIDOMNode dst ); Parameters ope...
nsIDOMWindow2
Inherits from: nsIDOMWindow Last changed in Gecko 1.9 (Firefox 3) Because nsIDOMWindow is frozen, this interface was introduced in Firefox 3 (Gecko 1.9) to allow DOM windows to take on new features. DOM windows implement nsIDOMWindow2, which is a subclass of nsIDOMWindow. ...
nsIDOMXPathException
s 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 ...
nsIDragService
he image is drawn, it is offset up and left the amount so that the cursor appears at that location within the image. If aImage is null, aImageX and aImageY are not used and the image is instead determined from the source node aDOMNode, and the offset calculated so that the initial location for the image appears in the same screen position as where the element is located. The node must be within a document. Currently, supported images are all DOM nodes. If this is an HTML <image> or <canvas> element, the drag image is taken from the image data. If the element is in a document, it will be rendered at its displayed size, otherwise, it will be rendered at its real size. For other types of elements, the element is rendered into an offscreen buffer in the same manner as it is currently displayed. The d...
nsIDragSession
dragAction unsigned long Sets the action (copy, move, link and so on) for the current drag. (See nsIDragService) numDropItems unsigned long Get the number of items that were dropped. Read only. onlyChromeDrop boolean Indicates if the drop event should be dispatched only to chrome. This allows chrome to handle a drag that was refused by content. sourceDocument nsIDOMDocument The document where the drag was started, which will be null if the drag originated outside the application. Useful for determining if a drop originated in the same document. Read only. sourceNode nsIDOMNode The DOM node that was originally dragged to start the session, which will be null if the drag originated outside the application. Read only. target...
nsIEditorBoxObject
is article. Inherits from: nsIContainerBoxObject Last changed in Gecko 1.9 (Firefox 3) The boxObject belonging to a XUL editor element implements this interface. Note: Please consider using nsIContainerBoxObject instead. Attributes Attribute Type Description docShell nsIDocShell Read only. Obsolete since Gecko 1.9 The nsIDocShell object that manages the contained document. The editor.xml binding uses this property to gain access to the webNavigation, contentDocument, contentWindow, webBrowserFind, editingSession and commandManager properties. ...
nsIEditorDocShell
d internally. Inherits from: nsISupports Last changed in Gecko 1.7 Use nsIEditingSession.makeWindowEditable() and nsIEditingSession.getEditorForWindow() from out side. Method overview void makeEditable(in boolean inWaitForUriLoad); Attributes Attribute Type Description editable boolean This docShell is editable. Read only. editor nsIEditor Gets or sets the editor for the content document. hasEditingSession boolean This docShell has an editing session. Read only. Methods makeEditable() Make this docShell editable, setting a flag that causes an editor to get created, either immediately, or after a url has been loaded. void makeEditable( in boolean inWaitForUriLoad ); Parameters inWaitForUriLoad true to wait for a URI before creating the editor. ...
nsIFaviconDataCallback
d 3.3 / SeaMonkey 2.1) Method overview void onComplete(in nsIURI aURI, in unsigned long aDataLen, [const,array,size_is(aDataLen)] in octet aData, in AUTF8String aMimeType); Methods onComplete() Called when the required favicon's information is available. It's up to the invoking method to state if the callback is always invoked, or called on success only. Check the method documentation to ensure that. The caller will receive the most information we can gather on the icon, but it's not guaranteed that all of them will be set. For some method we could not know the favicon's data (it could just be too expensive to get it, or the method does not require we actually have any data). It's up to the caller to check aDataLen > 0 before using any data-related information like mime-t...
nsIFeedContainer
gories nsIArray An array of the categories found in a feed or entry. Note: The returned array will contain nsIFeedCategory objects, except that interface has not been implemented yet. contributors nsIArray An array of nsIFeedPerson objects describing contributors to the feed or entry. fields nsIWritablePropertyBag2 Provides access to all the fields found in the document. Common Atom and RSS fields are normalized, including some namespaced extensions such as "dc:subject" and "content:encoded". Consumers can avoid normalization by checking the feed type and accessing specific fields. Common namespaces are accessed using prefixes, such as get("dc:subject");. See nsIFeedResult.registerExtensionPrefix() for more information about prefixes. id AStr...
nsIFile
tion. Therefore, you must not use the native form unless it is guaranteed that the path passed to a native form function is always ASCII. To create an nsIFile from a path you can use FileUtils.jsm: var FileUtils = Cu.import("resource://gre/modules/FileUtils.jsm").FileUtils var nsifile = new FileUtils.File( fileName ) Note: nsILocalFile was merged with this interface in Gecko 14. Much of the documentation has not been updated to reflect this change. Method overview void append(in AString node); void appendNative(in ACString node); Native code only! void appendRelativeNativePath(in ACString relativeFilePath); void appendRelativePath(in AString relativeFilePath); nsIFile clone(); boolean contains(in nsIFile inFile); void copyTo(in...
nsIFileInputStream
ld happen during the first read. Also, the file is not locked when init is called, so it might be deleted before we try to read from it. Methods init() void init( in nsIFile file, in long ioFlags, in long perm, in long behaviorFlags ); Parameters file File to read from (must QI to nsILocalFile) ioFlags The file status flags define how the file is accessed. See PR_Open documentation for more details. If set to -1 the file will be opened in default mode (PR_RDONLY). perm File mode bits are described in the PR_Open documentation. If set to -1 the default value 0 will be used. behaviorFlags Flags specifying various behaviors of the class (see enumerations in the class). See also nsIFileOutputStream ...
nsIFileOutputStream
set would happen during the first write, and if the file is to be created, it will not appear on the disk until the first write. Methods init() void init( in nsIFile file, in long ioFlags, in long perm, in long behaviorFlags ); Parameters file File to write to (must QI to nsILocalFile) ioFlags File open flags listed are listed in the PR_Open() documentation. Use -1 to open the file in default mode (PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE). perm File mode bits are described in the PR_Open documentation. If set to -1 the default permissions (0664) will be used. behaviorFlags Flags specifying various behaviors of the class; see Behavior flag constants above. See also nsIFileInputStream ...
nsIFilePicker
This attribute has no effect if private browsing mode is in effect. defaultExtension AString The extension for the type of files you want to work with. On some platforms, this is automatically appended to filenames the user enters, if required. Specify it without a leading...
nsIFileStreams
henever Seek(0) occurs. If the file is already open and the seek occurs, it will happen naturally. (The file will only be reopened if it is closed for some reason.) Methods init() void init( in nsIFile file, in long ioFlags, in long perm, in long behaviorFlags ); Parameters file File to read from (must QI to nsILocalFile). ioFlags File open flags listed in prio.h (see PR_Open documentation) or -1 to open the file in default mode (PR_RDONLY). perm File mode bits listed in prio.h or -1 to use the default value (0). behaviorFlags Flags specifying various behaviors of the class (see enumerations in the class). See also nsIFileOutputStream ...
nsIFileView
s an appropriate id is passed, nsIFileView relies on the treecols section --> <treecol id="FilenameColumn" label="Name" flex="1" primary="true"/> <treecol id="LastModifiedColumn" label="Date" flex="1"/> <treecol id="Size" label="Size" flex="1"/> </treecols> <treechildren/> </tree> <script> var DIR="/home/"; //The directory to be opened var ftree = document.getElementById("ftree"); //The XUL tree element var lfile = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); lfile.initWithPath(DIR); // Open the directory var fview = Components.classes["@mozilla.org/filepicker/fileview;1"] .createInstance(Components.interfaces.nsIFileView); //Create an instance of the component tvie...
nsIFrameLoader
the mouse. aY The Y coordinate of the mouse. aButton Which button was clicked, if any. aClickCount The number of clicks comprising the mouse button event, if any. aModifiers The modifier keys in effect at the time of the event. aIgnoreRootScrollFrame Optional Whether or not to ignore the root scroll frame. Native code only!updatePositionAndSize Updates the position and size of the subdocument loaded by this frameloader. void updatePositionAndSize( in nsIFrame aIFrame ); Parameters aIFrame The nsIFrame for the content node that owns this frameloader. See also Content process event handling nsIFrameLoaderOwner nsIFrameMessageListener nsIChromeFrameMessageManager nsIDOMWindowUtils ...
nsIFrameScriptLoader
rue); This will load a separate instance of the frame script into every tab open in the window associated with this window message manager. As the user opens new tabs in this window, copies of the script will be loaded into these new tabs, as well. Frame scripts are essentially per-tab, so they don't get reloaded when the user navigates. If you want a frame script to do something whenever a new document is loaded, you can listen for the document-element-inserted notification. Parameters Name Type Description aURL String URL for the script to load. aURL must be the absolute URL. data: URLs are also supported. For example data:,dump("foo\n"); aAllowDelayedLoad Boolean If true, this flag means that the frame script will be loaded into any new frame...
nsIHttpChannelInternal
HttpUpgradeListener aListener); void setCookie(in string aCookieHeader); void setupFallbackChannel(in string aFallbackKey); Attributes Attribute Type Description canceled boolean Returns true if and only if the channel has been canceled. Read only. channelIsForDownload boolean External handlers may set this to true to notify the channel that it is open on behalf of a download. documentURI nsIURI An HTTP channel can own a reference to the document URI. forceAllowThirdPartyCookie boolean Force relevant cookies to be sent with this load even if normally they would not be. localAddress AUTF8String The local IP address to which the channel is bound, in the same format produced by PR_NetAddrToString(). This may be either an IPv4 or IPv6 address. Note: If Network Address Transla...
nsIIFrameBoxObject
is article. Inherits from: nsIContainerBoxObject Last changed in Gecko 1.9 (Firefox 3) The boxObject belonging to a XUL iframe element implements this interface. Note: Please consider using nsIContainerBoxObject instead. Attributes Attribute Type Description docShell nsIDocShell Read only. Obsolete since Gecko 1.9 The nsIDocShell object that manages the contained document. The general.xml binding uses this property to gain access to the webNavigation, contentDocument and contentWindow properties. ...
nsIJumpListBuilder
formed by users within the application. A task can be represented by an application shortcut and associated command line parameters or a URI. Task lists should generally be static lists that do not change often, if at all - similar to an application menu. Tasks are given the highest priority of all lists when space is limited. JUMPLIST_CATEGORY_RECENT 1 Recent lists are based on Window's recent document lists. The lists are generated automatically by Windows. Applications that use recent or frequent lists should keep document use tracking up to date by calling the SHAddToRecentDocs shell api. JUMPLIST_CATEGORY_FREQUENT 2 Frequent lists are based on Window's recent document lists. The lists are generated automatically by Windows. Applications that use recent or frequent lists should keep docume...
nsIMsgCompFields
char * forceMsgEncoding PRBool forcePlainText PRBool from AString hasRecipients PRBool readonly New in Thunderbird 23 Indicates whether something is filled in in the to, cc, or bcc attribute. (bug 68784) messageId char * needToCheckCharset PRBool Indicates whether we need to check if the current DocumentCharset can represent all the characters in the message body. It should be initialized to true and set to false when 'Send Anyway' is selected by a user. (bug 249530) newsgroups AString newshost char * newspostUrl char * organization AString otherRandomHeaders AString No longer exists - see https://groups.google.com...
nsINavHistoryContainerResultNode
e node whose index is to be returned. Return value The index of the specified node into the list of immediate children of the container. Exceptions thrown NS_ERROR_NOT_AVAILABLE The container isn't open (that is, containerOpen is false). NS_ERROR_INVALID_ARG The specified node isn't a direct child of this container. Remarks There are a number of untested methods on this interface that are not documented at present, and are disabled in the idl file. See also nsINavHistoryResultNode, nsINavHistoryService ...
nsIObserverService
...
nsIPrompt
, inout wstring username, inout wstring password, in wstring checkMsg, inout boolean checkValue); boolean select(in wstring dialogTitle, in wstring text, in PRUint32 count, [array, size_is(count)] in wstring selectList, out long outSelection); Constants The button flags defined in nsIPrompt are the same as those defined in nsIPromptService.Constants. Example usage is also documented: Using the button Flags See Also nsIPromptService ...
nsIScriptableIO
g and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. nsIScriptableIO provides a convenient API for creating files and streams, as well as for reading and writing data to them. For your convenience, this API is published through a global IO object. For more...
getNext
Documentation is now located at nsISimpleEnumerator.getNext(). ...
hasMoreElements
Documentation is now located at nsISimpleEnumerator.hasMoreElements(). ...
AddRef
Documentation is now located at nsISupports.AddRef(). ...
Release
Documentation is now located at nsISupports.Release(). ...
data
Documentation is now located at nsISupportsVoid.data(). ...
toString
Documentation is now located at nsISupportsVoid.toString(). ...
nsITaskbarPreview
The controller provides the behavior and appearance for the taskbar preview, and is responsible for determining the size and contents of the preview, which buttons are displayed, and how the application responds to user actions on the preview. The controller is not allowed to be null. Note: Neither nsITaskbarTabPreview or nsITaskbarWindowPreview makes full use of the controller; see the documentation for each interface for details on which controller methods are used. tooltip DOMString A string containing the text displayed in the tooltip above the preview when the user hovers over it. By default, this is an empty string. visible boolean Indicates whether or not the preview is visible; by default, this is false. Not...
nsITelemetry
Clear out the registered histograms and keys. ...
nsITextInputProcessorCallback
s called when Gecko requests or notifies something to IME. boolean onNotify(in nsITextInputProcessor aTextInputProcessor, in nsITextInputProcessorNotification aNotification); Parameters aTextInputProcessor The instance which receives the notification. If the handler needs to do something with composition, you can use this. aNotification A notification or request. See the document of nsITextInputProcessorNotification for the details. Return value If this handles the notification normally or does nothing, it should return true. Otherwise, false. ...
nsITreeBoxObject
idateCell(in long row, in nsITreeColumn col); void invalidateRange(in long startIndex, in long endIndex); void invalidateColumnRange(in long startIndex, in long endIndex, in nsITreeColumn col); getRowAt() A hit test that can tell you what row the mouse is over. Returns -1 for invalid mouse coordinates. The coordinate system is the client coordinate system for the document this boxObject lives in, and the units are CSS pixels. long getRowAt(in long x, in long y); Parameters x The x coordinate y The y coordinate getCellAt() A hit test that can tell you what cell the mouse is over. Returns -1 for invalid mouse coordinates. The coordinate system is the client coordinate system for the document this boxObject lives in, and the units are CSS pixels. ...
nsIURI
IPv6 addresses are not enclosed in square brackets. hostPort AUTF8String The "host:port" part of the URI (or simply the host, if port is -1). Exceptions thrown NS_ERROR_FAILURE If hostPort is not applicable to the URI scheme (e.g. about:blank) Note: Characters are not escaped. originCharset ACString The charset of the document from which this URI originated. An empty value implies UTF-8. If this value is something other than UTF-8 then the URI components (for example spec, prePath, username, and so on) are all fully URL-escaped. Otherwise, the URI components may contain unescaped multibyte UTF-8 characters. Read only. password AUTF8String The optional password, assuming the preHost consists of "...
nsIWebContentHandlerRegistrar
registerProtocolHandler Summary of registerProtocolHandler void registerProtocolHandler( in DOMString protocol, in DOMString uri, in DOMString title, in nsIDOMWindow contentWindow ); Parameters protocol The protocol the site wishes to handle, specified as a string. uri The URI to the handler as a string. You must include "%s" to indicate where to insert the escaped URI of the document to be handled. Otherwise NS_ERROR_DOM_SYNTAX_ERR will be thrown. This string must also be of either the http or https schemes. title The title of the handler presented to the user as a string. contentWindow The DOM content window from which the method has been called. Note: Script must execute from same domain as uri or else it will throw permission error. Can bypass this by opening about:...
nsIWebPageDescriptor
face allows content being displayed in one window to be loaded into another window without refetching it from the network. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void loadPage(in nsISupports aPageDescriptor, in unsigned long aDisplayType); Attributes Attribute Type Description currentDescriptor nsISupports Retrieves the page descriptor for the current document. Read only. Constants Display type constants Constant Value Description DISPLAY_AS_SOURCE 0x0001 Generates an optionally syntax-highlighted (for XML/HTML documents) source of the original page. DISPLAY_NORMAL 0x0002 Just refetches the existing page. Note that if the descriptor is that of the source of another page, this keeps the source view, but uses the current syntax highlighting pre...
nsIWinTaskbar
esponding nsITaskbarWindowPreview. These don't have to correspond to tabs within the application; they can vary in size, shape, and location. They don't even have to represent actual GUI elements on the window. Unlike window previews, tab previews require most of the functionality of the nsITaskbarPreviewController interface be implemented. Warning: This API has undergone changes that are not yet documented. Among these is the addition of the method getOverlayIconController(). This method is currently known to crash if used under certain conditions. See bug 744992 for details and to track progress on a fix. Implemented by: @mozilla.org/windows-taskbar;1. To create an instance, use: var winTaskbar = Components.classes["@mozilla.org/windows-taskbar;1"] .getService(Components.interfa...
nsIWindowsRegKey
SS_NOTIFY ACCESS_WRITE ACCESS_BASIC | ACCESS_SET_VALUE | ACCESS_CREATE_SUB_KEY ACCESS_ALL ACCESS_READ | ACCESS_WRITE WOW64_32 0x00000200 WOW64_64 0x00000100 Type constants Values for the type of a registry value. The numeric values of these constants are taken directly from WinNT.h in the MS Platform SDK. The Microsoft documentation should be consulted for the exact meaning of these value types. This interface is somewhat restricted to using only these value types. There is no method that is directly equivalent to RegQueryValueEx or RegSetValueEx. In particular, this interface does not support the REG_MULTI_SZ and REG_EXPAND_SZ value types. It is still possible to enumerate values that have other types (that is, getValu...
nsIXFormsModelElement
extensions/xforms/nsIXFormsModelElement.idlScriptable Defines scriptable methods for manipulating instance data and updating computed and displayed values. 1.0 66 Introduced Gecko 1.8 Obsolete Gecko 1.9.1 Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method overview nsIDOMDocument getInstanceDocument(in DOMString instanceID); void rebuild(); void recalculate(); void refresh(); void revalidate(); Methods getInstanceDocument() nsIDOMDocument getInstanceDocument( in DOMString instanceID ); Parameters instanceID The ID of the instance element to be returned. Return value An nsIDOMDocument. Exceptions thrown DOMException If there is no matching instance data. rebuild() Signals the X...
nsIXFormsNSInstanceElement
lement is implemented by all XForms <instance/> elements, defining Mozilla extensions. extensions/xforms/nsIXFormsNSInstanceElement.idlScriptable Please add a summary to this article. Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Interface Code [scriptable, uuid(80669b92-8331-4f92-aaf8-06e80e6827b3)] interface nsIXFormsNSInstanceElement : nsISupports { nsIDOMDocument getInstanceDocument(); }; Methods getInstanceDocument nsIDOMDocument getInstanceDocument(); getInstanceDocument returns a DOM Document that corresponds to the instance data associated with the instance element. Essentially it is just a shortcut to nsIXFormsModelElement::getInstanceDocument() for the given instance element. Related Interfaces nsIXFormsModelElement Example Code None. ...
nsIXFormsNSModelElement
s. It defines Mozilla extensions to the nsIXFormsModelElement interface. extensions/xforms/nsIXFormsNSModelElement.idlScriptable Please add a summary to this article. Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Interface Code [scriptable, uuid(85fd60c7-1db7-40c0-ae8d-f723fdd1eea8)] interface nsIXFormsNSModelElement : nsISupports { nsIDOMNodeList getInstanceDocuments(); }; Methods getInstanceDocuments nsIDOMNodeList getInstanceDocuments(); getInstanceDocuments returns a nsIDOMNodeList containing all the instance documents for the model, making it possible to enumerate over instances in the model without knowing their names. Related Interfaces nsIXFormsModelElement Example Code None. ...
nsIXMLHttpRequest
ure 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. nsIXMLHttpRequest along with nsIJSXMLHttpRequest and nsIXMLHttpRequestEventTarget are Mozilla's implementation details of the DOM XMLHttpRequest object. Note: If you're a web developer or a Mozilla add-on developer, please refer to the XMLHttpRequest documentation instead. This page contains documentation, specific to Mozilla application and add-on developers. The interface definition: //github.com/RealityRipple/UXP/blob/master/dom/xhr/nsIXMLHttpRequest.idl Elevated Privileges As mentioned in the "Non-Standard Properties" the property of channel was read-only. When using the XPCOM interface, as seen below in Example 2, we can get access to this. T...
nsIXULBrowserWindow
erWindow 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 setJSDefaultStatus(in AString status); void setJSStatus(in AString status); void setOverLink(in AString link, in nsIDOMElement element); Methods onBeforeLinkTraversal() Called before traversing a link to d...
nsIXULTemplateBuilder
urce nsISupports The opaque datasource object that is used for the template. This object is created by the getDataSource method of the query processor. May be null if the datasource has not been loaded yet. Set this attribute to use a different datasource and rebuild the template. For an RDF datasource, this will be the same as the database. For XML this will be the nsIDOMNode for the datasource document or node for an inline reference (such as #name). Other query processors may use other types for the datasource. database nsIRDFCompositeDataSource Readonly: The composite datasource that the template builder observes and uses to create content. This is used only for RDF queries and is maintained for backwards compatibility. It will be the same object as the datasource property. For non-RDF que...
nsIAbCard/Thunderbird3
The nsIAbCard interface is used to represent and manipulate cards in the address book. In a big change from the original nsIAbCard, properties are now stored in a hash table instead of as attributes on the interface, allowing it to be more flexible. ...
XPCOM reference
XPCOM glue library. The contents herein are oriented primarily toward extension developers and people embedding XPCOM in other projects. If you're working on a module in the Mozilla codebase that's compiled with the MOZILLA_INTERNAL_API flag set, some of these APIs -- the string functions and classes in particular -- are not the ones you should be using. See the XPCOM internal string guide for documentation of the internal string API used within the Mozilla codebase. Core XPCOM functionsXPCOM provides a number of global functions which are used to initialize and shut down the XPCOM library, as well as to allocate memory, get access to services, and to instantiate interfaces.FoldersThe folder classes all implement the nsIMsgFolder interface. There are currently three folder classes - nsLo...
Getting Started Guide
e. It holds a stake in the underlying object. That object cannot go away until the owning reference has relinquished its claim. Not all references need to be owning references. In fact, if two objects somehow end up owning each other (even transitively) it becomes difficult for either of those object to be reclaimed without adding some `out-of-band' mechanism for breaking the ownership cycle. The document Some COM Ownership Guidelines provides some hints on when ownership is needed. The following lists are good starting point, but by no means complete. You use an owning reference when you created the object; you got the object from a function that might have created it, e.g., any `getter' function, such as QueryInterface, or CreateInstance. All good getters AddRef the interface pointers they ...
Reference Manual
nt operators. By following the optimization tips in this section, you will write code that generates fewer bytes of object than you might with raw pointers. Even if you don't follow these suggestions, your nsCOMPtr code may still end up smaller, or at worst only negligibly bulkier than the raw pointer version. See Code Bloat [LONG, summary at top] for details, though the recommendations from that document are re-iterated here. Time [[More time-performance measurements are needed.]] In places where two or more subroutines calls are required, i.e., of AddRef, Release, and QueryInterface, some nsCOMPtr routines are factored, and hence, require additional time corresponding to invoking a subroutine. This time is negligable, especially in the face of work done by QueryInterface, and the work that may b...
Status, Recent Changes, and Plans
o make using nsIWeakReferences easier. Plans for nsCOMPtr bug 59212: as soon as we test on more compilers, start recommending already_AddRefed as a function result. bug 59414: making operator& private may help prevent some leaks caused by casting Move the factored nsCOMPtr routines into their own library, to reduce nsCOMPtr clients' dependency on the XPCOM library. Recent changes to this document Removed the statement that == and != between an nsCOMPtr and a raw pointer or literal 0 does not work on some compilers since it is no longer true. Added an entire section to the Getting Started Guide on nsCOMPtrs in function signatures Added references to recent bugs influencing the use of nsCOMPtr machinery: bug 59212, and bug 59414 Fixed comparisons 1 and 3, as per comments by Morten Wel...
Using nsIClassInfo
t? If you're writing JavaScript code which uses a C++ class implementing nsIClassInfo, you don't need to do anything to activate the auto-interface magic which makes calling QueryInterface unnecessary. 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. Original Document Information Authors: Mike Shaver, Justin Lebar Last Updated Date: July 25, 2011 Copyright Information: Portions of this content are (C) 1998-2011 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
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 + ' = ...
XPCOM ownership guidelines
, however, parents point to their children with owning-pointers, children point back to their parents with non-owning-pointers. Containers own the things they contain (and not the reverse). Use nsCOMPtrs to implement owning-pointers. It's explicit, efficient, and fairly bullet-proof. It's easier to write `getter's and `setter's; and you don't need to put anything in your destructor. Original Document Information Author: Scott Collins Last Updated Date: May 8, 2003 Copyright Information: Copyright(C) 1999 by Netscape; use is subject to the NPL. Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
wrappedJSObject
wrappedJSObject is a property sometimes available on XPConnect wrappers. When available, it lets you access the JavaScript object hidden by the wrapper. 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. The rest of this article demonstrates what XPConnect wrappers do and how wrappedJSObject can be used to bypass them. Example co...
xptcall FAQ
ny platform that does not do xptcall is in trouble. ...
XPIDL Syntax
Mozilla › Tech › XPIDL › Syntax
It is more focused on XPIDL syntax and grammar. See XPIDL Main Page for more links and introductory content. Simplifications, conventions and notation The syntax is specified according to ABNF as defined by RFC 5234, although a few productions use prose for clarity of understanding. Lexically, tokens are delimited by whitespace (defined here as spaces, tabs, vertical tabs, form feeds, line feeds, and carriage returns, or [ \t\v\f\r\n] in regular expression form). ...
pyxpidl
...
XPIDL
Buffers must be deallocated with NS_Free, and interface pointers must be Release'd. Afterwards, the above rules for out apply. Shared out-parameters should not be freed, as they are intended to refer to constant string literals. Resources (mostly outdated) Some unsorted notes including a keyword list xpidl is a tool for generating C++ headers, Java interfaces, XPConnect typelibs, and HTML documentation from XPIDL files Generating xpt files on Windows A Google groups post with instructions on how to use variable-length argument lists using XPIDL. ...
XTF
Mozilla › Tech › XTF
XTF Home The XTF home (outdated). XTF: When XBL Just Won't Cut It More recent primer to XTF by Alex Vincent. ...
Xray vision
l my money?"); // calls the redefined implementation // chrome code var waivedWindow = gBrowser.contentWindow.wrappedJSObject; var transfer = waivedWindow.confirm("Transfer all my money?"); // calls the redefined implementation Waivers are transitive: so if you waive Xray vision for an object, then you automatically waive it for all the object's properties. For example, window.wrappedJSObject.document gets you the waived version of document. To undo the waiver again, call Components.utils.unwaiveXrays(waivedObject): var unwaived = Components.utils.unwaiveXrays(waivedWindow); unwaived.confirm("Transfer all my money?"); // calls the native implementation Xrays for DOM objects The primary use of Xray vision is for DOM objects: that is, the objects that represent parts of the web page. In Gec...
Fuzzing Interface
Documentation moved in-tree: https://firefox-source-docs.mozilla.org/tools/fuzzing/fuzzing_interface.html ...
Measuring Code Coverage on Firefox
Documentation moved in-tree: https://firefox-source-docs.mozilla.org/tools/code-coverage/index.html ...
Testing Mozilla code
e, you have to test it, and larger patches have to have automated tests. These articles will help you master (and continue to excel at) testing Mozilla code. ASan Nightly ProjectThe ASan Nightly Project involves building a Firefox Nightly browser with the popular AddressSanitizer tool and enhancing it with remote crash reporting capabilities for any errors detected.Clang static analysisThis document is split in two parts. The first part will focus on the modern and robust way of static-analysis and the second part will present the build-time static-analysis.Debugging Mozilla with ValgrindThis page describes how to use Valgrind (specifically, its Memcheck tool) to find memory errors.Firefox and Address SanitizerAddress Sanitizer (ASan) is a fast memory error detector that detects use-after-fr...
Buddy icons in mail
r Mozilla is now able to show icons in the message header area and the addressbook card pane. For the message pane, the icon we will show is on disk at: <profile home>/NIM/<value of pref aim.session.screenname>/picture/<screenname for sender email address>.gif When trying to determine the screenname for the sender, we search the addressbook that we are using for collection. (See this document for info about that.) For the addressbook card pane, the icon will show is on disk at: <profile home>/NIM/<value of pref aim.session.screenname>/picture/<screenname for card>.gif If aim.session.screenname is not set, the icon will not appear. If there is no card matching the email, the icon will not appear. If there is a card, but no screenname, the icon will not appear. And finall...
MailNews fakeserver
following API to the handler: <caption> Server API </caption> Name Arguments Returns Description closeSocket none nothing Closes the socket and stops the test. setMultiline the new value of multiline nothing The value is a boolean, with true invoking multiline mode. It is off by default. Extending a handler to provide different mechanisms is a process not defined here; please check the documentation of the corresponding handler for instructions. Using fakeserver in xpcshell tests Since there are three different components of fakeserver, a total of four objects need to be set up in a fakeserver test on top of other testing. The outline of a test looks like this: var daemon = setupDaemon(); // Check with your local fakeserver docs var handlers = [ /* Some set of handlers */ ]; for (var ...
Mailnews and Mail code review requirements
Thunderbird and SeaMonkey are the primary users of the code in mozilla/mailnews. Thunderbird's front-end code is stored in mozilla/mail. (A fair amount of this code is forked from code in the mailnews/ directory). Mailnews and Mail review rules Patches affecting Thunderbird User Experience or Interfaces Note: It is recommended that when working on bugs that affect user experience or interfaces, that ui-review is obtained at an early stage in the patch development process. Getting early ui-reviews this reduces the chance that work is rejected due to needing further user experience changes, and hence is aimed at saving time for the developer and reviewers. ...
Adding items to the Folder Pane
rray of folder-tree-items. Listening for Folder Pane rebuilds Every time the Folder Pane rebuilds, it fires a "mapRebuild" event, which is the ideal opportunity for extensions to step in and modify the display data. The following code snippet listens for that event: let gNumbersExt = { load: function gne_load() { window.removeEventListener("load", gNumbersExt.load, false); let tree = document.getElementById("folderTree"); tree.addEventListener("mapRebuild", gNumbersExt._insert, false); }, _insert: function gne__insert() { // This function is called when a rebuild occurs } }; window.addEventListener("load", gNumbersExt.load, true); The structure of folder-tree-items The Folder Pane stores its current display data in a property called _rowMap. This property is an array ...
Building a Thunderbird extension 1: introduction
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 community has a mailing list with an extensive searchable archive with an extensive searchable archive. You can also talk w...
Building a Thunderbird extension 2: extension file layout
Extension# Localization /chrome/skin/ /defaults/preferences/ //Building an Extension# Defaults Files The following tutorial pages will explain how to write each of these files (except locale/ and defaults/) and package them into an XPI (zippy) file. You can find information about the locale/ and defaults/ folders in the more general "Building an Extension" documentation. To start with the tutorial, manually create the initial directory structure for the extension as it is depicted above in a folder called myfirstext@jen.zed. This directory could be created anywhere on your filesystem. << Previous Next >> ...
Finding the code for a feature
Tags are applied using the message database property "keyword". ...
Access StringBundle from Overlay
dding them to your XUL overlay. ...
Add New Tab
var aURL = "chrome://myext/mytab.xul"; let tabmail = getMail3Pane().document.getElementById("tabmail"); tabmail.openTab("chromeTab", { chromePage: aUrl }); ...
Detect Opening Folder
Some actions require execution every time you open a folder (for example, registering a custom column handler. To do this you need to capture the select event of the folder [[XUL:tree|tree]] whose id is (conveniently) folderTree like so: window.document.getElementById('folderTree').addEventListener("select", testColumns, false); ...
Use SQLite
memory (BLOB) storage of 2Mb: var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024); var msg; db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")'); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")'); msg = '<p>Log message created and row inserted.</p>'; document.querySelector('#status').innerHTML = msg; }); db.transaction(function (tx) { tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { var len = results.rows.length, i; msg = "<p>Found rows: " + len + "</p>"; document.querySelector('#status').innerHTML += msg; for (i = 0; i < len; i++){ msg = "<p><b>" + results.rows.item(i).log + "</b></p>"; document.querySelecto...
customDBHeaders Preference
If the .msf file is rebuilt, all ...
Toolkit version format
This format is used by the Extension Manager, Software Update, and other parts of the platform. Versions in at least the following places must conform to this format: Addon's and target application's version in install and update manifests. The following preferences: app.extensions.version, extensions.lastAppVersion Versions returned by nsIXULAppInfo. application.ini in XULRunner applications appversion flag in chrome manifests. You can use nsIVersionComparator to compare versions from your application. See Older version formats below for description of the older version format used in Firefox/Thunderbird 1.0. ...
Using tab-modal prompts
Prior to Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1), prompts (that is, alerts and other modal prompts) were window modal. That is, when an alert occurred, it blocked the user interface on all tabs in the window until the user dismissed the prompt. Window-modal alert. Gecko 2.0 introduces tab modal prompts, which only block the tab with which they're associated. Only the window.alert() method gets this by default; you get this by default. Tab-modal alert. ...
Using the Mozilla symbol server
The Mozilla project runs a symbol server for trunk Firefox nightly and release builds on Windows. Symbols are available for at least 30 previous days worth of nightly builds, and Firefox releases from 2.0.0.4. This allows debugging of those builds without forcing all users to download large debugging files. The server functions like Microsoft's symbol server so the documentation there can be useful. Note that because Mozilla release builds are heavily optimized, debugging is not always easy. The debugger will not be able to show you the content of all variables and the execution path can seem strange because of inlining, tail calls, and other compiler optimizations. The only workaround is to build an unoptimized local build. The official symbol server URL for Firefox is https://symbols.m...
Using Objective-C from js-ctypes
about blocks. To create a block with js-ctypes, use the function: function createBlock(aFuncTypePtr) { /** * Creates a C block instance from a JS Function. * Blocks are regular Objective-C objects in Obj-C, and can be sent messages; * thus Block instances need are creted using the core.wrapId() function. */ // Apple Docs :: Working with blocks - https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.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 Blo...
js-ctypes
this is elaborated on in the JNI.jsm section and not the js-ctypes section due to the JSM abstracting away all of the js-ctypes. Unlike binary XPCOM components, it allows developers to ship a single binary for use with multiple versions of Firefox. Note: js-ctypes is only available from chrome code; that is, ctypes is not available to websites, only application and extension code. Documentation If you are brand new to js-ctypes, and have no idea about it, the pages you should read first is - ctypes.open followed by Standard OS Libraries. Using JS-Ctypes ctypes.open Custom Native File Standard OS Libraries Finding window handles Working with Data Working with A...
PKCS #11 Netscape Trust Objects - Network Security Services
PKCS #11 is a standard that defines ways to store certificates, keys and perform crypto operations. It does not specify a way to store trust objects. Trust objects are used to assign an explicit level of trust to a certificate. Examples of trust assertions are certificate authority root certificates. This document outlines the way in which NSS stores trust objects via PKCS#11. This is not a new design, but documentation of the method already in use. Trust Objects A trust object describes a level of trust in a certificate for a given usage or purpose. Conceptually a trust object contains the following: Certificate Reference Purpose + Level of trust (multiple) Purpose + Level of Trust A trust object ultimately denotes a level of trust in a certificate. The trust is expressed for a specif...
Drawing and Event Handling - Plugins
or refresh part of its drawing area, a windowless plug-in must first invalidate the area with either of these browser methods: NPN_InvalidateRect or NPN_InvalidateRegion. Both methods perform the same operations: They invalidate the specified drawing area prior to repainting or refreshing. They pass an update event or a paint message to the plug-in. The browser redraws invalid areas of the document and windowless plug-ins at regularly timed intervals. To force a paint message, the plug-in can call NPN_ForceRedraw after calling one of the invalidate methods. If a plug-in calls one of these methods, it receives a paint message asynchronously. void NPN_InvalidateRect(NPP instance, NPRect *invalidRect); void NPN_InvalidateRegion(NPP instance, NPRegion invalidRegion); The instance parameter r...
Plug-in Side Plug-in API - Plugins
lemented by the plug-in and called by the browser. For an overview of how these two sides of the plug-in API interact, see the How Plug-ins Work and Overview of Plug-in Structure sections in the introduction. Plugin method summary NPP_Destroy Deletes a specific instance of a plug-in. NPP_DestroyStream Tells the plug-in that a stream is about to be closed or destroyed. NP_GetEntryPoints Undocumented. NP_GetMIMEDescription Registers the mime types supported by the plug-in (Unix, Mac OS). NPP_GetValue Allows the browser to query the plug-in for information. NP_GetValue Allows the browser to query the plug-in for information. NPP_HandleEvent Delivers a platform-specific window event to the instance. NP_Initialize Provides global initialization for a plug-in. NPP_New Creates a new ...
Streams - Plugins
the buffer of data (delivered by the stream). The buffer allocated by the browser is deleted after returning from the function, so the plug-in must make a copy of the data it needs to keep. As an example, suppose that a plug-in (and the HTTP server) supports byte-range requests, and that the browser is in the process of pushing data to the plug-in. If the user now requests a specific page of the document, the plug-in calls NPN_RequestRead with a list of byte ranges. The open stream is converted from normal mode to seek mode in an effort to pass the plug-in data that was already on the way, rather than just discarding it. All NPP_Write calls for streaming data eventually stop, and NPP_Write calls will be completed only for data requested with NPN_RequestRead. The browser does not create a new str...
Gecko Plugin API Reference - Plugins
ass Structures NPAnyCallbackStruct NPByteRange NPEmbedPrint NPEvent NPFullPrint NPP NP_Port NPPrint NPPrintCallbackStruct NPRect NPRegion NPSavedData NPSetWindowCallbackStruct NPStream NPWindow Constants Error Codes Result Codes Plug-in Version Constants Version Feature Constants External resources External projects and articles for plugin creation Original document information Copyright Information: Netscape Communication ...
Plugins
ation about the developing for click-to-play, and plugin blocking. Flash Activation: Browser Comparison Each browser activates Flash slightly differently, which can be confusing for users and web authors. Plugin Blocking By Domain In order to improve security and performance for Firefox users, Firefox maintains a list of sites that are not able to use plugins. Archived Information Legacy documentation about developing NPAPI plugins. ...
Accessibility Inspector - Firefox Developer Tools
g the drop-down menu next to: Check for issues. The available menu items include: None -- Don't show the possible list of issues All Issues -- Check for all types of issues Contrast -- Check for issues with visual contrast Keyboard -- Check for issues with navigating via a keyboard Text Labels -- Check for issues with missing text labels When you one of the menu items, Firefox scans your document for the type of issues you selected. Depending on the size and complexity of your document, this may take a few seconds. When the scan is complete, the left side of the Accessibility Inspector panel displays only the items that have that type of issue. In the right side of the panel, the Checks subpanel lists the specific issue with the selected node. For each type of issue, there is a Learn more...
Browser Toolbox - Firefox Developer Tools
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 using the normal Debugger, just as if they were ordinary content pages. Targeting a document In the normal toolbox, there's a button in the toolbar enabling you to target specific iframes in the document. The same button appears in the browser toolbox where it lists all the top-level chrome and content windows as well as any iframes they contain. This enables you to inspect documents in individual chrome windows and popups, as well as in content tabs. For example, here's what the frame...
Access debugging in add-ons - Firefox Developer Tools
Don't write new add-ons that use these techniques. The following items are accessible in the context of chrome://browser/content/debugger.xul (or, in version 23 beta, chrome://browser/content/devtools/debugger.xul): window.addEventListener("Debugger:EditorLoaded") - called when the read-only script panel loaded. ...
Debug eval sources - Firefox Developer Tools
You can debug JavaScript code that is evaluated dynamically, either as a string passed to eval() or as a string passed to the Function constructor. 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. The debugger will also stop at debugger; statements in unnamed eval sourc...
Debugger.Memory - Firefox Developer Tools
O...
Debugger.Script - Firefox Developer Tools
as introduced into the system; the entire string is not a valid URL. For Function.prototype's script, this is null. If this Debugger.Script's source property is non-null, then this is equal to source.url. If the instance refers to WebAssembly code, throw a TypeError. startLine If the instance refers to a JSScript, the number of the line at which this script's code starts, within the file or document named by url. lineCount If the instance refers to a JSScript, the number of lines this script's code occupies, within the file or document named by url. source If the instance refers to a JSScript, the Debugger.Source instance representing the source code from which this script was produced. This is null if the source code was not retained. If the instance refers to WebAssembly code, the ...
Debugger - Firefox Developer Tools
ance is debugging. If the designated global is already a debuggee, this has no effect. Return this Debugger's Debugger.Object instance referring to the designated global. The valueglobal may be any of the following: A global object. An HTML5 WindowProxy object (an "outer window", in Firefox terminology), which is treated as if the Window object of the browsing context's active document (the "inner window") were passed. A cross-compartment wrapper of an object; we apply the prior rules to the wrapped object. A Debugger.Object instance belonging to this Debugger instance; we apply the prior rules to the referent. Any other sort of value is treated as a TypeError. (Note that each rule is only applied once in the process of resolving a givenglobal argumen...
Tutorial: Set a breakpoint - Firefox Developer Tools
rowser content toolbox's console. Then it evaluates the expression what in the given stack frame, and logs its result. The toolbox's console now looks like this: You can also click on the text that says "Or me!", to see report called from a different handler. If Debugger is unable to find the report function, or the console output does not appear, evaluate the expression tabs[0].content.document.location in the console to make sure that tabs[0] indeed refers to the HTML file you visited. If you have more than one tab visiting a file: URL, they all share a single content process, so you may need to use a different element of the array as the debuggee. Press "Run" in the Scratchpad again. Now, clicking on "Click me!" causes the breakpoint hit to be logged twice--one for each Debugger...
JSON viewer - Firefox Developer Tools
a JSON viewer. If you open a JSON file in the browser, or view a remote URL with the Content-Type set to application/json, it is parsed and given syntax highlighting. Arrays and objects are shown collapsed, and you can expand them using the "+" icons. The JSON viewer provides a search box that you can use to filter the JSON. You can also view the raw JSON and pretty-print it. Finally, if the document was the result of a network request, the viewer displays the request and response headers. ...
Dominators view - Firefox Developer Tools
nce to an Object, and so on. If you look in the Dominators Tree panel, you can trace the same path there. If either of these references were removed, the items below them could be garbage-collected. Each connection in the graph is labeled with the variable name for the referenced object. Sometimes there's more than one retaining path back from a node: Here there are three paths back from the DocumentPrototype node to a GC root. If one were removed, then the DocumentPrototype would still not be garbage-collected, because it's still retained by the other two path. Example Let's see how some simple code is reflected in the Dominators view. We'll use the monster allocation example, which creates three arrays, each containing 5000 monsters, each monster having a randomly-generated name. Taking...
Monster example - Firefox Developer Tools
Specifically: the code creates an object with three properties, each an array: one for fierce monsters one for friendly monsters one for monsters who haven't decided yet. for each array, the code cr...
Memory - Firefox Developer Tools
Monster example DOM allocation example ...
Migrating from Firebug - Firefox Developer Tools
mand Editor. The DevTools do not have a side panel like the Command Editor (which is requested in bug 1133849), but therefore has a separate tool called Scratchpad, which can be added as panel to the toolbox or opened in a separate window via Firefox menu > Developer > Scratchpad or Shift + F4. Also, the normal command line smartly enters a line break when it recognizes an unfinished command like document. and you hit Enter. You can also manually enter a line break by pressing Shift + Enter. Response preview There is a Preview tab when a network request logged to the console is expanded in Firebug. The Web Console displays a preview within the Response tab. It is currently missing the preview for HTML, XML and SVG, though, which is tracked in bug 1247392 and bug 1262796, but when you click on th...
Edit fonts - Firefox Developer Tools
Note: The updated Font tools as shown in this article are available in Firefox 63 onwards; if you are using an older version of Firefox the tools will not look or behave quite the same, but they will be similar (most notably the Font Editor will not be available). ...
Examine and edit CSS - Firefox Developer Tools
f the source file: right-click the link and select "Copy Location". The Inspector understands CSS source maps. That means that if you are using a CSS preprocessor that has support for source maps, and you've enabled source map support in the Style Editor settings, then the link will take you to the original source, not the generated CSS. Read more about CSS source map support in the Style Editor documentation. Overridden declarations If a CSS declaration is overridden by some other CSS rule with a greater weight, then the declaration is shown with a line through it. Overridden declarations have a funnel next to them. Click the funnel to filter the rule view to show only the rules applying to the current node that try to set the same property: that is, the complete cascade for the given propert...
Animation inspector example: CSS transitions - Firefox Developer Tools
lected+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) { selected.removeAttribute("id"); } } document.addEventListener("click", toggleSelection); ...
Call Tree - Firefox Developer Tools
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. You can find the specific profile we discuss here - just import it to the performance tool to follow along. There's a short page describing the structure of this program here. Note that we use the same 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 ...
Settings - Firefox Developer Tools
ng like this: Categories Default Firefox Developer Tools This group of checkboxes determines which tools are enabled in the toolbox. New tools are often included in Firefox but not enabled by default. Available Toolbox Buttons This group of checkboxes determines which tools get an icon in the Toolbox's toolbar. As of Firefox 62, if the option to "Select an iframe as the currently targeted document" is checked, the icon will appear in the toolbar while the Settings tab is displayed, even if the current page doesn't include any iframes. Note that in Firefox 52 we removed the checkbox to toggle the "Select element" button. The "Select element" button is now always shown. Themes This enables you to choose one of two themes. There's a light theme, which is the default: A dark...
Style Editor - Firefox Developer Tools
nu (which is a submenu in the "Tools" menu on the Mac). The Toolbox will appear at the bottom of the browser window, with the Style Editor activated: The Style Editor is divided into three main sections: the style sheet pane on the left the editor on the right the media sidebar. The style sheet pane The style sheet pane, on the left, lists all the style sheets being used by the current document. You can quickly toggle the use of a given sheet on and off by clicking the eyeball icon to the left of the sheet's name. You can save any changes you've made to the style sheet to your local computer by clicking the Save button in the bottom-right corner of each sheet's entry in the list. From Firefox 40 onwards, the style sheet pane also includes a context menu that lets you open the selected ...
Tips - Firefox Developer Tools
to an overridden property to find which other property overrides it. Right-click on a name, value, or rule to copy anything from the name, the value, the declaration or the whole rule to your clipboard. Web Console In all panels: Esc opens the 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 ava...
Toolbox - Firefox Developer Tools
le, 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 array of buttons that can be added or removed in the developer tool settings. By default this array includes: Toggle split console Responsive Design Mode Select a frame as the currently targeted document (this is only included by default from Firefox 41 onwards). The following tools are not included in the toolbar by default, but you can add them in the settings: Highlight painted area 3D view (note that this is not available in Firefox 40) Scratchpad Grab a color from the page Take a screenshot of the entire page: take a screenshot of the complete web page and saves it in your Downloads...
Web Console - Firefox Developer Tools
, 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 reference. Opening the Web Console You open the Web Console from a menu or with ...
Working with iframes - Firefox Developer Tools
You can point the developer tools at a specific iframe within a document. You'll see a button in the toolbar: Click it, and you'll see a popup listing all the iframes in the document, as well as the main document itself. If you select an entry in the list, all the tools in the toolbox - the Inspector, the Console, the Debugger and so on - will now target only that iframe, and will essentially behave as if the rest of the page does not exist. ...
AbortController.AbortController() - Web APIs
When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort(), as seen below in the second event listener. var controller = new AbortController(); var signal = controller.signal; var downloadBtn = document.querySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function() { controller.abort(); console.log('Download aborted'); }); function fetchVideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textContent = 'Download error: ' + ...
AbortController.abort() - Web APIs
When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort(), as seen below in the second event listener. var controller = new AbortController(); var signal = controller.signal; var downloadBtn = document.querySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function() { controller.abort(); console.log('Download aborted'); }); function fetchVideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textContent = 'Download error: ' + ...
AbortController.signal - Web APIs
When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort(), as seen below in the second event listener. var controller = new AbortController(); var signal = controller.signal; var downloadBtn = document.querySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function() { controller.abort(); console.log('Download aborted'); }); function fetchVideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textContent = 'Download error: ' + ...
AbortController - Web APIs
When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort(), as seen below in the second event listener. var controller = new AbortController(); var signal = controller.signal; var downloadBtn = document.querySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function() { controller.abort(); console.log('Download aborted'); }); function fetchVideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textContent = 'Download error: ' + ...
AbortSignal - Web APIs
When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort(), as seen below in the second event listener. var controller = new AbortController(); var signal = controller.signal; var downloadBtn = document.querySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function() { controller.abort(); console.log('Download aborted'); }); function fetchVideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textContent = 'Download error: ' + ...
AddressErrors - Web APIs
the Payment Request API know to present the specified error or errors but to allow the user to keep trying to edit the address. Setting up the Donate Now button This code creates a handler for the load event on the window which in turn adds the needed click event handler to the "Donate Now" button so that clicking it starts the payment process. window.addEventListener("load", function(ev) { document.getElementById("pay").addEventListener("click", process, false); }, false); See addEventListener() for information about event handlers and how they work. HTML Here's the simple HTML for this example. <p>Donate US $65 to our worthwhile cause and we will send you a totally not-useless gift as a token of our thanks!</p> <button id="pay">Donate Now</button> Result The final product is below.
Ambient Light Events - Web APIs
ct level by using the addEventListener method (using the devicelight event name) or by attaching an event handler to the window.ondevicelight property. Once captured, the event object gives access to the light intensity expressed in lux through the DeviceLightEvent.value property. ...
AnalyserNode.getFloatFrequencyData() - Web APIs
de = audioCtx.createMediaElementSource(audioEle); //Create analyser node const analyserNode = audioCtx.createAnalyser(); analyserNode.fftSize = 256; const bufferLength = analyserNode.frequencyBinCount; const dataArray = new Float32Array(bufferLength); //Set up audio node network audioSourceNode.connect(analyserNode); analyserNode.connect(audioCtx.destination); //Create 2D canvas const canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = 0; canvas.style.left = 0; canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); const canvasCtx = canvas.getContext('2d'); canvasCtx.clearRect(0, 0, canvas.width, canvas.height); function draw() { //Schedule next redraw requestAnimationFrame(draw); //Get spec...
AnalyserNode - Web APIs
ic demo (see app.js lines 128-205 for relevant code). var audioCtx = new(window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); // ... ...
Animation.commitStyles() - Web APIs
eb Animations API's Animation interface commits the end styling state of an animation to the element being animated, even after that animation has been removed. It will cause the end styling state to be written to the element being animated, in the form of properties inside a style attribute. Syntax animation.commitStyles(); Parameters None. Return value None. Examples const divElem = document.querySelector('div'); document.body.addEventListener('mousemove', evt => { let anim = divElem.animate( { transform: `translate(${ evt.clientX}px, ${evt.clientY}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitStyles(); }); Specifications Specification Status Comment Web AnimationsThe definition of 'commitStyles()' in that specification. Workin...
Animation.pause() - Web APIs
Web › API › Animation › pause
yet) and the end time of the animation is positive infinity. ...
Animation.play() - Web APIs
Web › API › Animation › play
e beginning. Syntax animation.play(); Parameters None. Return value undefined Example In the Growing/Shrinking Alice Game example, clicking or tapping the cake causes Alice's growing animation (aliceChange) to play forward, causing her to get bigger, as well as triggering the cake's animation. Two Animation.play()s, one EventListener: // The cake has its own animation: var nommingCake = document.getElementById('eat-me_sprite').animate( [ { transform: 'translateY(0)' }, { transform: 'translateY(-80%)' } ], { fill: 'forwards', easing: 'steps(4, end)', duration: aliceChange.effect.timing.duration / 2 }); // Pause the cake's animation so it doesn't play immediately. nommingCake.pause(); // This function will play when ever a user clicks or taps var growAlice = function() { ...
Animation.timeline - Web APIs
The Animation.timeline property of the Animation interface returns or sets the timeline associated with this animation. A timeline is a source of time values for synchronization purposes, and is an AnimationTimeline-based object. By default, the animation's timeline and the Document's timeline are the same. Syntax var animationsTimeline = Animation.timeline; Animation.timeline = newTimeline; Value A timeline object to use as the timing source for the animation, or null to use the default, which is the Document's timeline. Examples Here we set the animation's timeline to be the same as the document's timeline (this is the default timeline for all animations, by the way): animation.timeline = document.timeline; Specifications Specification Status Comment Web Ani...
AnimationEvent.initAnimationEvent() - Web APIs
AnimationEvent created this way are untrusted. Note: During the standardization process, this method was removed from the specification. It has been deprecated and is in the progress of being removed from most implementations. Do not use this method; instead, use the standard constructor, AnimationEvent(), to create a synthetic AnimationEvent. ...
AnimationEvent - Web APIs
* delay). AnimationEvent.pseudoElement Read only Is a DOMString, starting with '::', containing the name of the pseudo-element the animation runs on. If the animation doesn't run on a pseudo-element but on the element, an empty string: ''. Methods Also inherits methods from its parent Event. AnimationEvent.initAnimationEvent() Initializes a AnimationEvent created using the deprecated Document.createEvent("AnimationEvent") method. Specifications Specification Status Comment CSS AnimationsThe definition of 'AnimationEvent' in that specification. Working Draft Initial definition. ...
Attr.localName - Web APIs
Web › API › Attr › localName
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 documents. Note: In Gecko 1.9.2 and ea...
Attr.namespaceURI - Web APIs
Web › API › Attr › namespaceURI
espaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { // this is a XUL value } Notes This is not a computed value that is the result of a namespace lookup based on an examination of the namespace declarations in scope. The namespace URI of an attribute is frozen at the attribute creation time. In Firefox 3.5 and earlier, the namespace URI for HTML attributes in HTML documents is null. In later versions, in compliance with HTML5, it is https://www.w3.org/1999/xhtml as in XHTML. You can create an attribute with the specified namespaceURI using the DOM Level 2 method Element.setAttributeNS. Per the Namespaces in XML specification, an attribute does not inherit its namespace from the element it is attached to. If an attribute is not explicitly given a namespace, it ha...
Attr.prefix - Web APIs
Web › API › Attr › prefix
operty returns the namespace prefix of the specified attribute, or null if no prefix is specified. Before DOM4 this API was defined within the Node interface. Syntax string = attribute.prefix Examples The following logs "x" to the console. <div x:id="example" onclick="console.log(this.attributes[0].prefix)"/> Notes This will only work when a namespace-aware parser is used, i.e. when a document is served with an XML MIME type. This will not work for HTML documents. Specifications Specification Status Comment DOMThe definition of 'Attr: prefix' in that specification. Living Standard DOM4The definition of 'Attr.prefix' in that specification. Obsolete ...
AudioListener.dopplerFactor - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioListener.forwardX - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioListener.forwardY - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioListener.forwardZ - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioListener.positionX - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioListener.positionY - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioListener.positionZ - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioListener.setOrientation() - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioListener.setPosition() - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioListener.speedOfSound - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioListener.upX - Web APIs
Web › API › AudioListener › upX
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioListener.upY - Web APIs
Web › API › AudioListener › upY
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioListener.upZ - Web APIs
Web › API › AudioListener › upZ
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioListener - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
AudioParam.setValueCurveAtTime() - Web APIs
ton (see the webaudio-examples repo for the source code, or view the example live.) When this button is pressed, setValueCurveAtTime() is used to change the gain value between the values contained in the waveArray array: // create audio context var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext(); // set basic variables for example var myAudio = document.querySelector('audio'); var pre = document.querySelector('pre'); var myScript = document.querySelector('script'); pre.innerHTML = myScript.innerHTML; var valueCurve = document.querySelector('.value-curve'); // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var source = audioCtx.createMediaElementSource(myAudio); // Create a gain node and set it's gain value to 0.5 v...
AudioScheduledSourceNode: ended event - Web APIs
udioScheduledSourceNode has stopped playing, either because it's reached a predetermined stop time, the full duration of the audio has been performed, or because the entire buffer has been played. Examples In this simple example, an event listener for the ended event is set up to enable a "Start" button in the user interface when the node stops playing: node.addEventListener('ended', () => { document.getElementById("startButton").disabled = false; }) You can also set up the event handler using the AudioScheduledSourceNode.onended property: node.onended = function() { document.getElementById("startButton").disabled = false; } For an example of the ended event in use, see our audio-buffer example on GitHub. Specifications Specification Status Comment Web Audio...
AudioScheduledSourceNode.onended - Web APIs
called by the browser when the ended event occurs on the AudioScheduledSourceNode. The function receives as input a single parameter, which is an object of type Event describing the event that occurred. Examples In this simple example, an event listener for the ended event is set up to enable a "Start" button in the user interface when the node stops playing. node.onended = function(event) { document.getElementById("startButton").disabled = false; } Specifications Specification Status Comment Web Audio APIThe definition of 'onended' in that specification. Working Draft Initial specification. ...
AudioTrack.enabled - Web APIs
d property is a Boolean whose value is true if the track is enabled; enabled tracks produce audio while the media is playing. Setting enabled to false effectively mutes the audio track, preventing it from contributing to the media's audio performance. Example This example switches between the main and commentary audio tracks of a media element. ...
AudioTrack - Web APIs
e track. Returns null if the track was not created by a SourceBuffer or the SourceBuffer has been removed from the MediaSource.sourceBuffers attribute of its parent media source. Usage notes To get an AudioTrack for a given media element, use the element's audioTracks property, which returns an AudioTrackList object from which you can get the individual tracks contained in the media: var el = document.querySelector("video"); var tracks = el.audioTracks; You can then access the media's individual tracks using either array syntax or functions such as forEach(). This first example gets the first audio track on the media: var firstTrack = tracks[0]; The next example scans through all of the media's audio tracks, enabling any that are in the user's preferred language (taken from a variable use...
AudioTrackList: addtrack event - Web APIs
The addtrack event is fired when a track is added to an AudioTrackList. Bubbles No Cancelable No Interface TrackEvent Event handler property onaddtrack Examples Using addEventListener(): const videoElement = document.querySelector('video'); videoElement.audioTracks.addEventListener('addtrack', (event) => { console.log(`Audio track: ${event.track.label} added`); }); Using the onaddtrack event handler property: const videoElement = document.querySelector('video'); videoElement.audioTracks.onaddtrack = (event) => { console.log(`Audio track: ${event.track.label} added`); }; Specifications Specification Status HTML Living StandardThe definition of 'addtrack' in that specification. Living Standard ...
AudioTrackList.length - Web APIs
udio tracks in the media. Syntax var trackCount = AudioTrackList.length; Value A number indicating how many audio tracks are included in the AudioTrackList. Each track can be accessed by treating the AudioTrackList as an array of objects of type AudioTrack. Example This snippet gets the number of audio tracks in the first <video> element found in the DOM by querySelector(). var videoElem = document.querySelector("video"); var numAudioTracks = 0; if (videoElem.audioTracks) { numAudioTracks = videoElem.audioTracks.length; } Note that this sample checks to be sure HTMLMediaElement.audioTracks is defined, to avoid failing on browsers without support for AudioTrack. Specifications Specification Status Comment HTML Living StandardThe definition of 'AudioTrackLis...
AudioTrackList.onaddtrack - Web APIs
first attached to the element; one addtrack event will occur for each audio track in the media resource. Example This snippet establishes a handler for the addtrack event that calls a function, addToTrackList(), passing in the AudioTrack object representing the newly-added track. In this scenario, that function's role is to add the new track to a list of audio tracks available to choose from. document.querySelector("video").audioTracks.onaddtrack = function(event) { addToTrackList(event.track); }; Specifications Specification Status Comment HTML Living StandardThe definition of 'AudioTrackList.onaddtrack' in that specification. Living Standard HTML5The definition of 'AudioTrackList.onaddtrack' in that specification. Recommendation ...
AudioTrackList.onchange - Web APIs
dioTrackList.onchange = eventHandler; Value Set onchange to a function that should be called whenever tracks are enabled or disabled on the media element. Example This snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track. ...
AudioTrackList.onremovetrack - Web APIs
ntListener(). Syntax AudioTrackList.onremovetrack = eventHandler; Value Set onremovetrack to a function that accepts as input a TrackEvent object which indicates in its track property which audio track has been removed from the media element. Example This simple example just fetches the current number of audio tracks in the media element whenever a track is removed from the media element. document.querySelector("my-video").audioTracks.onremovetrack = function(event) { myTrackCount = document.querySelector("my-video").audioTracks.length; }; The current number of audio tracks remaining in the media element is obtained from AudioTrackList property length. Specifications Specification Status Comment HTML Living StandardThe definition of 'AudioTrackList.onremov...
AudioTrackList: removetrack event - Web APIs
The removetrack event is fired when a track is removed from an AudioTrackList. Bubbles No Cancelable No Interface TrackEvent Event handler property onremovetrack Examples Using addEventListener(): const videoElement = document.querySelector('video'); videoElement.audioTracks.addEventListener('removetrack', (event) => { console.log(`Audio track: ${event.track.label} removed`); }); Using the onremovetrack event handler property: const videoElement = document.querySelector('video'); videoElement.audioTracks.onremovetrack = (event) => { console.log(`Audio track: ${event.track.label} removed`); }; Specifications Specification Status HTML Living StandardThe definition of 'removetrack' in that specification. Livi...
AudioTrackList - Web APIs
on a media element, AudioTrackList lets you set event handlers on the addtrack and removetrack events, so that you can detect when tracks are added to or removed from the media element's stream. See onaddtrack and onremovetrack for details and examples. Examples Getting a media element's audio track list To get a media element's AudioTrackList, use its audioTracks property. var audioTracks = document.querySelector("video").audioTracks; Monitoring track count changes In this example, we have an app that displays information about the number of channels available. To keep it up to date, handlers for the addtrack and removetrack events are set up. audioTracks.onaddtrack = updateTrackCount; audioTracks.onremovetrack = updateTrackCount; function updateTrackCount(event) { trackCount = audioTr...
BaseAudioContext.createGain() - Web APIs
e and unmute the audio when a Mute button is clicked by changing the gain property value. ...
BaseAudioContext.createPanner() - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
BaseAudioContext.decodeAudioData() - Web APIs
n and sets it to loop. The buttons in the example simply run getData() to load the track and start it playing, and stop it playing, respectively. When the stop() method is called on the source, the source is cleared out. Note: You can run the example live (or view the source.) // define variables var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var source; var pre = document.querySelector('pre'); var myScript = document.querySelector('script'); var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); // use XHR to load an audio track, and // decodeAudioData to decode it and stick it in a buffer. // Then we put the buffer into the source function getData() { source = audioCtx.createBufferSource(); var request = new XMLHttpRequest()...
BasicCardRequest.supportedNetworks - Web APIs
The supportedNetworks property of the BasicCardRequest dictionary contains an array of DOMStrings representing the card networks that the retailer supports (e.g. amex, mastercard). Syntax supportedNetworks : [value [, ... value]] Value An array containing one or more DOMStrings, which describe the card networks the retailer supports. Legal values are defined in the W3C's document Card Network Identifiers Approved for use with Payment Request API, and are currently: amex cartebancaire diners discover jcb mastercard mir unionpay visa Example The following example shows a sample definition of the first parameter of the PaymentRequest() constructor, the data property of which contains supportedNetworks and supportedTypes properties. var supportedInstruments = [{ supportedMetho...
BatteryManager.charging - Web APIs
tery.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
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. ...
BatteryManager.dischargingTime - Web APIs
fully discharged and the system will suspend. This value is Infinity if the battery is currently charging rather than discharging, or if the system is unable to report the remaining discharging time. ...
BatteryManager.level - Web APIs
the system is about to be suspended. A value of 1.0 means the battery is full. ...
Using the Beacon API - Web APIs
See Beacon API for an overview. Navigator.sendBeacon() The Beacon API's Navigator.sendBeacon() method sends a beacon request to the server in the global browsing context. The method takes two arguments: the URL and the data to send. ...
BeforeUnloadEvent - Web APIs
When a non-empty string is assigned to the returnValue Event property, a dialog box appears, asking the users for confirmation to leave the page (see example below). When no value is provided, the event is processed silently. Some implementations only show the dialog box if the frame or any embedded frame receives a user gesture or user interaction. See Browser compatibility for more information. ...
Blob.size - Web APIs
Web › API › Blob › size
sizeInBytes = blob.size Value The number of bytes of data contained within the Blob (or Blob-based object, such as a File). Example This example uses an <input> element of type file to ask the user for a group of files, then iterates over those files outputting their names and lengths in bytes. // fileInput is a HTMLInputElement: <input type="file" multiple id="myfileinput"> var fileInput = document.getElementById("myfileinput"); // files is a FileList object (simliar to NodeList) var files = fileInput.files; for (var i = 0; i < files.length; i++) { console.log(files[i].name + " has a size of " + files[i].size + " Bytes"); } Specifications Specification Status Comment File APIThe definition of 'Blob.size' in that specification. Working Draft Initial defini...
Blob.type - Web APIs
Web › API › Blob › type
.type Value A DOMString containing the file's MIME type, or an empty string if the type could not be determined. Example This example asks the user to select a number of files, then checks each file to make sure it's one of a given set of image file types. var i, fileInput, files, allowedFileTypes; // fileInput is a HTMLInputElement: <input type="file" multiple id="myfileinput"> fileInput = document.getElementById("myfileinput"); // files is a FileList object (simliar to NodeList) files = fileInput.files; // our application only allows GIF, PNG, and JPEG images allowedFileTypes = ["image/png", "image/jpeg", "image/gif"]; for (i = 0; i < files.length; i++) { // Test if file.type is an allowed file type. if (allowedFileTypes.indexOf(files[i].type) > -1) { // file type matched is one...
Bluetooth.referringDevice - Web APIs
The Bluetooth.referringDevice attribute of the Bluetooth interface returns a BluetoothDevice if the current document was opened in response to an instruction sent by this device and null otherwise. Syntax Bluetooth.referringDevice Value A BluetoothDevice, if the document was opened in response to an instruction sent by this device and null otherwise. Specifications Specification Status Comment Web BluetoothThe definition of 'referringDevice' in that specification. Draft Initial definition. ...
Body.blob() - Web APIs
Web › API › Body › blob
at resolves with a Blob. Example In our fetch request example (run fetch request live), we create a new request using the Request() constructor, then use it to fetch a JPG. When the fetch is successful, we read a Blob out of the response using blob(), put it into an object URL using URL.createObjectURL, and then set that URL as the source of an <img> element to display the image. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest) .then(response => response.blob()) .then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); Specifications Specification Status Comment FetchThe definition of 'blob()' in that specification. Living Standard ...
Body.body - Web APIs
Web › API › Body › body
leStream of the body contents. Syntax var stream = response.body; Value A ReadableStream. Example In our simple stream pump example we fetch an image, expose the response's stream using response.body, create a reader using ReadableStream.getReader(), then enqueue that stream's chunks into a second, custom readable stream -- effectively creating an identical copy of the image. ...
Body.bodyUsed - Web APIs
Web › API › Body › bodyUsed
and then set that URL as the source of an <img> element to display the image. Notice that we log response.bodyUsed to the console once before the response.blob() call and once after. This returns false before and true afterwards, as at that point the body has been read. ...
Body - Web APIs
Web › API › Body
d using UTF-8. Examples The example below uses a simple fetch call to grab an image and display it in an <img> tag. You'll notice that since we are requesting an image, we need to run Body.blob() (Response implements body) to give the response its correct MIME type. HTML Content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> JS Content const myImage = document.querySelector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg') .then(res => res.blob()) .then(res => { const objectURL = URL.createObjectURL(res); myImage.src = objectURL; }); Specifications Specification Status Comment FetchThe definition of 'Body' in that specification. Living Standard ...
BroadcastChannel: message event - Web APIs
border: 1px solid black; padding: .5rem; height: 150px; font-family: "Fira Sans", sans-serif; } h1 { font: 1.6em "Fira Sans", sans-serif; margin-bottom: 1rem; } textarea { padding: .2rem; } label, br { margin: .5rem 0; } button { vertical-align: top; height: 1.5rem; } const channel = new BroadcastChannel('example-channel'); const messageControl = document.querySelector('#message'); const broadcastMessageButton = document.querySelector('#broadcast-message'); broadcastMessageButton.addEventListener('click', () => { channel.postMessage(messageControl.value); }) Receiver 1 <h1>Receiver 1</h1> <div id="received"></div> body { border: 1px solid black; padding: .5rem; height: 100px; font-family: "Fira Sans", sans-serif; } h1 { ...
BroadcastChannel - Web APIs
Messages are broadcasted via a message event fired at all BroadcastChannel objects listening to the channel. Note: This feature is available in Web Workers. ...
BudgetService - Web APIs
Properties None. Methods BudgetService.getCost() Returns a Promise that resolves to a double, indicating the worst-case background operation cost of the provided background operation. BudgetService.getBudget() Returns a Promise that resolves to an array of BudgetState objects, indicating the expected state of the budget at times in the future. ...
CDATASection - Web APIs
ecific methods and implements those of its parent Text. Specifications Specification Status Comment DOMThe definition of 'CDATASection' in that specification. Living Standard Re-added in issue #295 due to web breakage DOM4The definition of 'CDATASection' in that specification. Obsolete Removed in favour of the more generic Text interface Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'CDATASection' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'CDATASection' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Docu...
CSS.escape() - Web APIs
Web › API › CSS › escape
.escape(".foo#bar") // "\.foo\#bar" CSS.escape("()[]{}") // "\(\)\[\]\{\}" CSS.escape('--a') // "--a" CSS.escape(0) // "\30 ", the Unicode code point of '0' is 30 CSS.escape('\0') // "\ufffd", the Unicode REPLACEMENT CHARACTER In context uses To escape a string for use as part of a selector, the escape() method can be used: var element = document.querySelector('#' + CSS.escape(id) + ' > img'); The escape() method can also be used for escaping strings, although it escapes characters that don't strictly need to be escaped: var element = document.querySelector('a[href="#' + CSS.escape(fragment) + '"]'); Specification Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSS.escape()' in that spec...
CSSGroupingRule - Web APIs
CSSPageRule Syntax The syntax is described using the WebIDL format. ...
CSSImageValue - Web APIs
nd</button> We add some CSS, including a background image requesting a binary file: button { display: inline-block; min-height: 100px; min-width: 100px; background: no-repeat 5% center url(https://mdn.mozillademos.org/files/16793/magicwand.png) aqua; } We get the element's style map. ...
CSSKeywordValue.CSSKeywordValue() - Web APIs
ollowing example resets the CSS display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector. #myElement { display: flex; } <div id="myElement">Check the developer tools to see the log in the console and to inspect the style attribute on this div.</div> let keyword = new CSSKeywordValue('initial'); let myElement = document.getElementById('myElement').attributeStyleMap; myElement.set('display', keyword); console.log( myElement.get('display').value); // 'initial' console.dir( keyword ); Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'CSSKeywordValue' in that specification. Working Draft Initial definition. ...
CSSKeywordValue.value - Web APIs
The value property of the CSSKeywordValue interface returns or sets the value of the CSSKeywordValue. Syntax var val = cssKeywordValue.value cssKeywordValue.value = val Value A USVString. Examples The following example resets the CSS display property to its defaults. let indicator = Document.getElementById('indicator'); indicator.attributeStyleMap.set('display', new CSSKeywordValue('initial')); indicator.attributeStyleMap.get('display').value // 'initial' Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'undefined' in that specification. Working Draft Initial definition. ...
CSSKeywordValue - Web APIs
s methods from CSSStyleValue. Examples The following example resets the CSS display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector. #myElement { display: flex; } <div id="myElement">Check the developer tools to see the log in the console and to inspect the style attribute on this div.</div> let myElement = document.getElementById('myElement').attributeStyleMap; myElement.set('display', new CSSKeywordValue('initial')); console.log( myElement.get('display').value); // 'initial' Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'CSSKeywordValue' in that specification. Working Draft Initial definition. ...
CSSMathSum - Web APIs
s Returns a CSSNumericArray object which contains one or more CSSNumericValue objects. Event handlers No Methods None. Examples We create an element with a width determined using a calc() function, then console.log() the operator and values, and dig into the values a bit. ...
CSSMathValue.operator - Web APIs
ax" CSSMathClamp "clamp" CSSMathNegate "negate" CSSMathInvert "invert" Examples We create an element with a width determined using a calc() function, then console.log() the operator. ...
CSSMathValue - Web APIs
CSSMathSum Properties CSSMathValue.operator Indicates the operator that the current subtype represents. Event handlers No Methods None. Examples We create an element with a width determined using a calc() function, then console.log() the operator. ...
CSSMediaRule - Web APIs
rface. It has no specific methods. Specifications Specification Status Comment CSS Conditional Rules Module Level 3The definition of 'CSSMediaRule' in that specification. Candidate Recommendation Make it derived from the CSSConditionRule. CSS Object Model (CSSOM)The definition of 'CSSMediaRule' in that specification. Working Draft No changes from Document Object Model (DOM) Level 2 Style Specification Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSMediaRule' in that specification. Obsolete ...
CSSPageRule - Web APIs
at-rule. CSSPageRule.style Read only Returns the declaration block associated with the at-rule. Methods As a CSSRule, CSSPageRule also implements the methods of that interface. It has no specific methods. Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSPageRule' in that specification. Working Draft No changes from Document Object Model (DOM) Level 2 Style Specification Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSPageRule' in that specification. Obsolete Initial definition ...
CSSPositionValue.CSSPositionValue() - Web APIs
resents values for properties that take a position, for example object-position. Syntax cvar cssPositionValue = new CSSPositionValue(x, y) Parameters x A position along the web page's horizontal axis. ...
CSSPositionValue.x - Web APIs
The x property of the CSSPositionValue interface returns returns the item's position along the web page's horizontal axis. Syntax var x = CSSPositionValue.x Value A CSSNumericValue. ...
CSSPositionValue.y - Web APIs
The y property of the CSSPositionValue interface returns the item's position along the vertical axis. Syntax var y = CSSPositionValue.y Value A CSSNumericValue. ...
CSSPositionValue - Web APIs
alue.CSSPositionValue() Creates a new CSSPositionValue object. Properties CSSPositionValue.x Returns the item's position along the web page's horizontal axis. CSSPositionValue.y Returns the item's position along the vertical axis. Methods None. Examples The following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page. let replacedEl = document.getElementById( 'image' ); let position = new CSSPositionValue( CSS.px(35), CSS.px(40) ); replacedEl.attributeStyleMap.set( 'object-position', position ); console.log( position.x.value, position.y.value ); console.log( replacedEl.computedStyleMap().get('object-position') ); We set the object-position property, then check the values returned. #image { width: 300px; height: 300px; border: ...
CSSPrimitiveValue.getCounterValue() - Web APIs
interface. Syntax var counterValue = cssPrimitiveValue.getCounterValue(); Return value A Counter object representing the counter value. Exceptions Type Description DOMException An INVALID_ACCESS_ERR is raised if the CSS value doesn't contain a Counter value (e.g. this is not CSS_COUNTER). Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSPrimitiveValue.getCounterValue' in that specification. Obsolete Initial definition ...
CSSPrimitiveValue.getFloatValue() - Web APIs
e> in radians. CSS_S The value is a <time> in seconds. Return value A float value in the specified unit. Exceptions Type Description DOMException An INVALID_ACCESS_ERR is raised if the CSS value doesn't contain a float value or if the float value can't be converted into the specified unit. Example var cs = window.getComputedStyle(document.body); var cssValue = cs.getPropertyCSSValue("margin-top"); console.log(cssValue.getFloatValue(CSSPrimitiveValue.CSS_CM)); Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSPrimitiveValue.getFloatValue' in that specification. Obsolete Initial definition ...
CSSPrimitiveValue.getRGBColorValue() - Web APIs
ng the RGBColor interface. Syntax var rgbColorValue = cssPrimitiveValue.getRGBColorValue(); Return value An RGBColor object representing the color value. Exceptions Type Description DOMException An INVALID_ACCESS_ERR is raised if the attached property can't return an RGB color value (i.e. this is not CSS_RGBCOLOR). Example var cs = window.getComputedStyle(document.body); var cssValue = cs.getPropertyCSSValue("color"); console.log(cssValue.getRGBColorValue()); Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSPrimitiveValue.getRGBColorValue' in that specification. Obsolete Initial definition ...
CSSPrimitiveValue.getRectValue() - Web APIs
yle property can be achieved using the Rect interface. Syntax var rectValue = cssPrimitiveValue.getRectValue(); Return value A Rect object representing the rect value. Exceptions Type Description DOMException An INVALID_ACCESS_ERR is raised if the CSS value doesn't contain a Rect value. (i.e. this is not CSS_RECT). Example var cs = window.getComputedStyle(document.getElementById("clippedDiv")); var cssValue = cs.getPropertyCSSValue("clip"); console.log(cssValue.getRectValue()); Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSPrimitiveValue.getRectValue' in that specification. Obsolete Initial definition ...
CSSPrimitiveValue.getStringValue() - Web APIs
used to get a string value. If this CSS value doesn't contain a string value, a DOMException is raised. Syntax var stringValue = cssPrimitiveValue.getStringValue(); Return value A string value. Exceptions Type Description DOMException An INVALID_ACCESS_ERR is raised if the CSS value doesn't contain a string value. Example var cs = window.getComputedStyle(document.body); var cssValue = cs.getPropertyCSSValue("display"); console.log(cssValue.getStringValue()); Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSPrimitiveValue.getStringValue' in that specification. Obsolete Initial definition ...
CSSPrimitiveValue.primitiveType - Web APIs
od. CSS_STRING The value is a <string>. The value can be obtained by using the getStringValue() method. CSS_UNKNOWN The value is not a recognized CSS2 value. The value can only be obtained by using the cssText attribute. CSS_URI The value is a <uri>. The value can be obtained by using the getStringValue() method. Example var cs = window.getComputedStyle(document.body); var cssValue = cs.getPropertyCSSValue("color"); console.log(cssValue.primitiveType); Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSPrimitiveValue.primitiveType' in that specification. Obsolete Initial definition ...
CSSPrimitiveValue.setFloatValue() - Web APIs
t value. Return value Void. Exceptions Type Description DOMException An INVALID_ACCESS_ERR is raised if the CSS value doesn't contain a float value or if the string value can't be converted into the specified unit. An NO_MODIFICATION_ALLOWED_ERR is raised if this property is read-only. Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSPrimitiveValue.setFloatValue' in that specification. Obsolete Initial definition ...
CSSPrimitiveValue.setStringValue() - Web APIs
value. Return value Void. Exceptions Type Description DOMException An INVALID_ACCESS_ERR is raised if the CSS value doesn't contain a string value or if the string value can't be converted into the specified unit. An NO_MODIFICATION_ALLOWED_ERR is raised if this property is read-only. Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSPrimitiveValue.setStringValue' in that specification. Obsolete Initial definition ...
CSSPrimitiveValue - Web APIs
he float value, the value will be unchanged and a DOMException will be raised. CSSPrimitiveValue.setStringValue() A method to set the string value with the specified unit. If the property attached to this value can't accept the specified unit or the string value, the value will be unchanged and a DOMException will be raised. Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSPrimitiveValue' in that specification. Obsolete Initial definition ...
CSSPseudoElement.element - Web APIs
CSSPseudoElement interface returns a reference to the originating element of the pseudo-element, in other words its parent element. Syntax var originatingElement = cssPseudoElement.element; Value An Element representing the pseudo-element's originating element. ...
CSSPseudoElement.type - Web APIs
ement interface returns the type of the pseudo-element as a string, represented in the form of a CSS selector. Syntax var typeOfPseudoElement = cssPseudoElement.type; Value A CSSOMString containing one of the following values: "::before" "::after" "::marker" Examples The example below demonstrates the relationship between CSSPseudoElement.type and Element.pseudo(): const myElement = document.querySelector('q'); const mySelector = '::after'; const cssPseudoElement = myElement.pseudo(mySelector); const typeOfPseudoElement = cssPseudoElement.type; console.log(mySelector === typeOfPseudoElement); // Outputs true Specifications Specification Status Comment CSS Pseudo-Elements Level 4The definition of 'type' in that specification. Working Draft Initial def...
CSSPseudoElement - Web APIs
om the pseudo-element. Examples Basic example using Element.pseudo Using pseudo-elements, most modern browsers will automatically add quotation marks around text inside a <q> element. (A style rule may be needed to add quotation marks in older browsers.) The example below demonstrates the basic properties of the CSSPseudoElement object representing the opening quotation mark. const element = document.querySelector('q'); const cssPseudoElement = element.pseudo('::before'); console.log(cssPseudoElement.element); // Outputs [object HTMLQuoteElement] console.log(cssPseudoElement.type); // Outputs '::before' Specifications Specification Status Comment CSS Pseudo-Elements Level 4The definition of 'CSSPseudoElement' in that specification. Working Draft Initial defini...
CSSRule.cssText - Web APIs
Web › API › CSSRule › cssText
and doesn't even omit a warning or error. Furthermore, it has no settable sub-properties. Therefore, to modify it, use the stylesheet's cssRules[index] properties .selectorText and .style (or its sub-properties). See Using dynamic styling information for details. Syntax string = cssRule.cssText Example <style> body { background-color: darkblue; } </style> <script> var stylesheet = document.styleSheets[0]; alert(stylesheet.cssRules[0].cssText); // body { background-color: darkblue; } </script> Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSRule: cssText' in that specification. Working Draft ...
CSSRuleList - Web APIs
rhaps being a livecopy of a list that does), it cannot just be assigned one (as it has no such property), and neither can it be assigned to one (as stylesheet.cssRules is read-only), but it must unfortunately be inserted into one, rule by rule, and unless combining lists, after any existing list therein is deleted, rule by rule. Example // get the first style sheet's first rule var first_rule = document.styleSheets[0].cssRules[0]; See also CSSRule CSSRuleList implementations There are multiple properties in the CSSOM that will return a CSSRuleList. They are: CSSStyleSheet property cssRules CSSMediaRule property cssRules CSSKeyframesRule property cssRules CSSMozDocumentRule property cssRules Specifications Specification Status Comment CSS Object Model...
CSSStyleDeclaration.cssText - Web APIs
The cssText property of the CSSStyleDeclaration interface returns or sets the text of the element's inline style declaration only. To be able to set a stylesheet rule dynamically, see Using dynamic styling information. Not to be confused with stylesheet style-rule CSSRule.cssText. Example <span id="s1" style="color: red;"> Some text </span> <script> var elem = document.getElementById("s1"); alert(elem.style.cssText); // "color: red;" </script> Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleDeclaration: cssText' in that specification. Working Draft ...
CSSStyleDeclaration.getPropertyCSSValue() - Web APIs
lue is a CSSValue containing the CSS value for a property. If none exists, returns null. Example The following JavaScript code gets an object containing the computed RGB values of the color CSS property: var style = window.getComputedStyle(elem, null); var rgbObj = style.getPropertyCSSValue('color').getRGBColorValue(); Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSStyleDeclaration' in that specification. Obsolete Declared as obsolete in July 2003. ...
CSSStyleDeclaration.getPropertyPriority() - Web APIs
= style.getPropertyPriority(property); Parameters property is a DOMString representing the property name to be checked. Return value priority is a DOMString that represents the priority (e.g. "important") if one exists. If none exists, returns the empty string. Example The following JavaScript code checks whether margin is marked as important in a CSS selector rule: var declaration = document.styleSheets[0].cssRules[0].style; var isImportant = declaration.getPropertyPriority('margin') === 'important'; Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleDeclaration.getPropertyPriority()' in that specification. Working Draft Document Object Model (DOM) Level 2 Style SpecificationThe definition of ...
CSSStyleDeclaration.getPropertyValue() - Web APIs
ified CSS property. Syntax var value = style.getPropertyValue(property); Parameters property is a DOMString representing the property name to be checked. Return value value is a DOMString containing the value of the property. If not set, returns the empty string. Example The following JavaScript code queries the value of the margin property in a CSS selector rule: var declaration = document.styleSheets[0].cssRules[0].style; var value = declaration.getPropertyValue('margin'); // "1px 2px" Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleDeclaration.getPropertyValue()' in that specification. Working Draft Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSStyleDeclar...
CSSStyleDeclaration.item() - Web APIs
s provided. Syntax var propertyName = style.item(index); Parameters index is the index of the node to be fetched. The index is zero-based. Return value propertyName is a DOMString that is the name of the CSS property at the specified index. JavaScript has a special simpler syntax for obtaining an item from a NodeList by index: var propertyName = style[index]; Example var style = document.getElementById('div1').style; var propertyName = style.item(1); // or simply style[1] - returns the second style listed Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleDeclaration.item()' in that specification. Working Draft Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSSty...
CSSStyleDeclaration.length - Web APIs
e declarations in this CSS declaration block. Syntax var num = styles.length; Value An integer that provides the number of styles explictly set on the parent of the instance. Example The following gets the number of explicitly set styles on the following HTML element: <div id="div1" style="margin: 0 10px; background-color: #CA1; font-family: monospace"></div> JavaScript code: var myDiv = document.getElementById('div1'); var divStyle = myDiv.style; var len = divStyle.length; // 6 Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleDeclaration.length' in that specification. Working Draft Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSStyleDeclaration' in that specification.
CSSStyleDeclaration.parentRule - Web APIs
turns a CSSRule that is the parent of this style block, e.g. a CSSStyleRule representing the style for a CSS selector. Syntax var rule = styles.parentRule; Value The CSS rule that contains this declaration block or null if this CSSStyleDeclaration is not attached to a CSSRule. Example The following JavaScript code gets the parent CSS style rule from a CSSStyleDeclaration: var declaration = document.styleSheets[0].rules[0].style; var rule = declaration.parentRule; Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleDeclaration.parentRule' in that specification. Working Draft Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSStyleDeclaration' in that specification. Obsolete...
CSSStyleDeclaration.removeProperty() - Web APIs
multi-word property names are hyphenated and not camel-cased. Return value oldValue is a DOMString equal to the value of the CSS property before it was removed. Exceptions DOMException NO_MODIFICATION_ALLOWED_ERR: if the property or declaration block is read only. Example The following JavaScript code removes the background-color CSS property from a selector rule: var declaration = document.styleSheets[0].rules[0].style; var oldValue = declaration.removeProperty('background-color'); Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleDeclaration.removeProperty()' in that specification. Working Draft Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSStyleDeclaration' ...
CSSStyleRule.selectorText - Web APIs
The CSSRule.selectorText property gets the textual representation of the selector for the rule set. This is readonly in some browsers; to set stylesheet rules dynamically cross-browser, see Using dynamic styling information. Syntax string = cssRule.selectorText Example // for cssrule: body { background-color: darkblue; } var stylesheet = document.styleSheets[0]; alert(stylesheet.cssRules[0].selectorText); // body Notes The implementation may have stripped out insignificant whitespace while parsing the selector. If set to a selector string which cannot be parsed, a SyntaxError is thrown. Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleRule.selectorText' in that specification. Working Draft Browser ...
CSSStyleRule.style - Web APIs
The CSSRule.style property is the CSSStyleDeclaration interface for the declaration block of the CSSRule. Syntax styleObj = cssRule.style Example function stilo() { alert(document.styleSheets[0].cssRules[0].style.cssText); } // displays "background-color: gray;" Notes The declaration block is that part of the style rule that appears within the braces and that actually provides the style definitions (for the selector, the part that comes before the braces). ...
CSSStyleRule - Web APIs
leRule.style Read only Returns the CSSStyleDeclaration object for the rule. CSSStyleRule.styleMap Read only Returns a StylePropertyMap object which provides access to the rule's property-value pairs. Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleRule' in that specification. Working Draft No changes Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSRule' in that specification. Obsolete ...
CSSStyleSheet.cssRules - Web APIs
ylesheet. Each item in the list is a CSSRule defining a single rule. Syntax var rules = cssStyleSheet.cssRules; Value A live-updating CSSRuleList containing each of the CSS rules making up the stylesheet. Each entry in the rule list is a CSSRule object describing one rule making up the stylesheet. Examples Individual rules within the stylesheet can then be accessed by index: let ruleList = document.styleSheets[0].cssRules; for (let i=0; i < ruleList.length; i++) { processRule(ruleList[i]); } Rules can also be accessed using for...of: let ruleList = document.styleSheets[0].cssRules; for (let rule of ruleList) { processRule(rule); } However, because CSSRule is not a proper array, you can't use forEach(). Specifications Specification Status Comment CSS Obje...
CSSValue.cssText - Web APIs
Web › API › CSSValue › cssText
The cssText property of the CSSValue interface represents the current computed CSS property value. Syntax cssText = cssValue.cssText; Value A DOMString representing the current CSS property value. Example var styleDeclaration = document.styleSheets[0].cssRules[0].style; var cssValue = styleDeclaration.getPropertyCSSValue("color"); console.log(cssValue.cssText); Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSValue.cssText' in that specification. Obsolete Initial definition ...
CSSValue.cssValueType - Web APIs
lue and an instance of the CSSPrimitiveValue interface can be obtained by using binding-specific casting methods on this instance of the CSSValue interface. CSS_VALUE_LIST The value is a CSSValue list and an instance of the CSSValueList interface can be obtained by using binding-specific casting methods on this instance of the CSSValue interface. Example var styleDeclaration = document.styleSheets[0].cssRules[0].style; var cssValue = styleDeclaration.getPropertyCSSValue("color"); console.log(cssValue.cssValueType); Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSValue.cssValueType' in that specification. Obsolete Initial definition ...
CSSValue - Web APIs
Web › API › CSSValue
terface can be obtained by using binding-specific casting methods on this instance of the CSSValue interface. CSS_VALUE_LIST The value is a CSSValue list and an instance of the CSSValueList interface can be obtained by using binding-specific casting methods on this instance of the CSSValue interface. Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSValue' in that specification. Obsolete Initial definition ...
CSSValueList.item() - Web APIs
Web › API › CSSValueList › item
to the number of values in the list, this method returns null. Syntax var cssValue = cssValueList.item(index); Parameters index An unsigned long representing the index of the CSS value within the collection. Return value A CSSValue object at the index position in the CSSValueList, or null if that is not a valid index. Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSValueList.item' in that specification. Obsolete Initial definition ...
CSSValueList.length - Web APIs
The length read-only property of the CSSValueList interface represents the number of CSSValues in the list. The range of valid values of the indices is 0 to length-1 inclusive. Syntax var length = cssValueList.length; Value An unsigned long representing the number of CSSValues. Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSValueList.length' in that specification. Obsolete Initial definition ...
CSSValueList - Web APIs
ng representing the number of CSSValues in the list. Methods CSSValueList.item() This method is used to retrieve a CSSValue by ordinal index. The order in this collection represents the order of the values in the CSS style property. If index is greater than or equal to the number of values in the list, this returns null. Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSValuesList' in that specification. Obsolete Initial definition ...
CSS Font Loading API - Web APIs
Loading API provides events and interfaces for dynamically loading font resources. Interfaces FontFace Represents a single usable font face. FontFaceSet An interface loading font faces and checking their download statuses. FontFaceSource A mixin providing all of the fonts used in font-related operations, unless defined otherwise. It defines the FontFaceSources.fonts property available to Document and WorkerGlobalScope. FontFaceSetLoadEvent Fired whenever a FontFaceSet loads. Specifications Specification Status Comment CSS Font Loading Module Level 3 Working Draft Initial definition. ...
CSS Painting API - Web APIs
ze 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 ['--boxColor']; } static get inputArguments() { return ['*','<length>']; } static get ...
CanvasCaptureMediaStreamTrack.canvas - Web APIs
The CanvasCaptureMediaStreamTrack canvas read-only property returns the HTMLCanvasElement from which frames are being captured. Syntax var elt = stream.canvas; Value An HTMLCanvasElement indicating the canvas which is the source of the frames being captured. Example // Find the canvas element to capture var canvasElt = document.getElementsByTagName("canvas")[0]; // Get the stream var stream = canvasElt.captureStream(25); // 25 FPS // Do things to the stream ... // Obtain the canvas associated with the stream var canvas = stream.canvas; Specifications Specification Status Comment Media Capture from DOM ElementsThe definition of 'CanvasCaptureMediaStreamTrack.canvas' in that specification. Working Draft Initial definition ...
CanvasCaptureMediaStreamTrack.requestFrame() - Web APIs
the specification pointing out that at this time, no exceptions are being thrown if the canvas isn't origin-clean. This may change in the future, so it would be wise to plan ahead and watch for exceptions such as SecurityError (although the specific error that might be thrown is not mentioned in the spec, this is a likely candidate). ...
CanvasGradient.addColorStop() - Web APIs
ide that range. color A CSS <color> value representing the color of the stop. A SYNTAX_ERR is raised if the value cannot be parsed as a CSS <color> value. Examples Adding stops to a gradient This example uses the addColorStop method to add stops to a linear CanvasGradient object. The gradient is then used to fill a rectangle. ...
CanvasRenderingContext2D.beginPath() - Web APIs
e matching the current canvas state, you can use CanvasRenderingContext2D.moveTo(). Syntax void ctx.beginPath(); Examples Creating distinct paths This example creates two paths, each of which contains a single line. HTML <canvas id="canvas"></canvas> JavaScript The beginPath() method is called before beginning each line, so that they may be drawn with different colors. ...
CanvasRenderingContext2D.canvas - Web APIs
the Canvas API, is a read-only reference to the HTMLCanvasElement object that is associated with a given context. It might be null if there is no associated <canvas> element. Syntax ctx.canvas; Examples Given this <canvas> element: <canvas id="canvas"></canvas> ... you can get a reference to the canvas element within the CanvasRenderingContext2D by using the canvas property: var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.canvas // HTMLCanvasElement Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.canvas' in that specification. Living Standard ...
CanvasRenderingContext2D.clearHitRegions() - Web APIs
The CanvasRenderingContext2D method clearHitRegions() removes all hit regions from the canvas. Syntax void ctx.clearHitRegions(); Examples Using the clearHitRegions method This example demonstrates the clearHitRegions() method. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Set some hit regions ctx.addHitRegion({id: 'eyes'}); ctx.addHitRegion({id: 'nose'}); ctx.addHitRegion({id: 'mouth'}); // Remove them altogether from the canvas ctx.clearHitRegions(); 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.createLinearGradient() - Web APIs
the specified line. Examples Filling a rectangle with a linear gradient This example initializes a linear gradient using the createLinearGradient() method. Three color stops between the gradient's start and end points are then created. Finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle. ...
CanvasRenderingContext2D.createRadialGradient() - Web APIs
es. 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.currentTransform - Web APIs
rent transformation matrix. Syntax ctx.currentTransform [= value]; value A DOMMatrix or SVGMatrix object to use as the current transformation matrix. ...
CanvasRenderingContext2D.direction - Web APIs
The CanvasRenderingContext2D.direction property of the Canvas 2D API specifies the current text direction used to draw text. Syntax ctx.direction = "ltr" || "rtl" || "inherit"; Options Possible values: "ltr" The text direction is left-to-right. "rtl" The text direction 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'; ct...
CanvasRenderingContext2D.drawWindow() - Web APIs
The height of the window. bgColor A DOMString that specifies the color the canvas is filled with before the window is rendered into it. This color may be transparent/translucent. It is given as a CSS color string (for example, rgb() or rgba()). Notes: If "rgba(0,0,0,0)" is used for the background color, the drawing will be transparent wherever the window is transparent. Top-level browsed documents are usually not transparent because the user's background-color preference is applied, but iframes are transparent if the page doesn't set a background. If an opaque color is used for the background color, rendering will be faster because we won't have to compute the window's transparency. flags Optional Used to better control the drawWindow call. Flags can be ORed together. ...
CanvasRenderingContext2D.font - Web APIs
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 the font in a canvas cont...
CanvasRenderingContext2D.getLineDash() - Web APIs
tenated. 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. ...
CanvasRenderingContext2D.getTransform() - Web APIs
t2D.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.globalCompositeOperation - Web APIs
he 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
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 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.lineWidth - Web APIs
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 Comment HTML Livi...
CanvasRenderingContext2D.measureText() - Web APIs
ureText() method returns a TextMetrics object that contains information about the measured text (such as its width, for example). Syntax ctx.measureText(text); Parameters text The text String to measure. Return value A TextMetrics object. Example Given this <canvas> element: <canvas id="canvas"></canvas> ... you can get a TextMetrics object using the following code: const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let text = ctx.measureText('Hello world'); console.log(text.width); // 56; Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.measureText' in that specification. Living Standard ...
CanvasRenderingContext2D.moveTo() - Web APIs
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). ...
CanvasRenderingContext2D.rect() - Web APIs
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. Living Standard ...
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
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
r, 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.shadowBlur - Web APIs
pond 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. Living Standard ...
CanvasRenderingContext2D.shadowOffsetX - Web APIs
ative 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. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Shadow ctx.shadowColor = 'red'; ctx.shadowOffsetX = 25; ctx.shadowBlur = 10; // Rectangle ctx.fillStyle = 'blue'; ctx.fillRect(20, 20, 150, 100); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.shadowOffsetX' in that specification. ...
CanvasRenderingContext2D.shadowOffsetY - Web APIs
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. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Shadow ctx.shadowColor = 'red'; ctx.shadowOffsetY = 25; ctx.shadowBlur = 10; // Rectangle ctx.fillStyle = 'blue'; ctx.fillRect(20, 20, 150, 80); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.shadowOffsetY' in that specification. ...
CanvasRenderingContext2D.textBaseline - Web APIs
m" 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
al 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
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 matrix ctx.setTransform(1, 0, 0, 1, 0, 0); // Unmoved square ctx.fillStyle = 'gray'; ctx.fillRect(0, 0, 80, 80); Result The moved square is red, and the unmoved square is gray. Spec...
CanvasRenderingContext2D - Web APIs
ar and below. The Canvas tutorial has more explanation, examples, and resources, as well. Basic example To get a CanvasRenderingContext2D instance, you must first have an HTML <canvas> element to work with: <canvas id="my-house" width="300" height="300"></canvas> To get the canvas' 2D rendering context, call getContext() on the <canvas> element, supplying '2d' as the argument: const canvas = document.getElementById('my-house'); const ctx = canvas.getContext('2d'); With the context in hand, you can draw anything you like. This code draws a house: // Set line width ctx.lineWidth = 10; // Wall ctx.strokeRect(75, 140, 150, 110); // Door ctx.fillRect(130, 190, 40, 60); // Roof ctx.beginPath(); ctx.moveTo(50, 140); ctx.lineTo(150, 60); ctx.lineTo(250, 140); ctx.closePath(); ctx.stroke(); Th...
Compositing and clipping - Web APIs
o close a path and turn it into a clipping path instead of stroking or filling the path. By default the <canvas> element has a clipping path that's the exact same size as the canvas itself. In other words, no clipping occurs. A clip example In this example, we'll use a circular clipping path to restrict the drawing of a set of random stars to a particular region. ...
Finale - Web APIs
Web › API › Canvas API › Tutorial › Finale
ess of the size at which they're drawn. ...
Hit regions and accessibility - Web APIs
nvas. CanvasRenderingContext2D.removeHitRegion() Removes the hit region with the specified id from the canvas. CanvasRenderingContext2D.clearHitRegions() Removes all hit regions from the canvas. You can add a hit region to your path and check for the MouseEvent.region property to test if your mouse is hitting your region, for example. ...
Optimizing canvas - Web APIs
similar primitives or repeating objects on an offscreen canvas If you find yourself repeating some of the same drawing operations on each animation frame, consider offloading them to an offscreen canvas. You can then render the offscreen image to your primary canvas as often as needed, without unnecessarily repeating the steps needed to generate it in the first place. myCanvas.offscreenCanvas = document.createElement('canvas'); myCanvas.offscreenCanvas.width = myCanvas.width; myCanvas.offscreenCanvas.height = myCanvas.height; myCanvas.getContext('2d').drawImage(myCanvas.offScreenCanvas, 0, 0); Avoid floating-point coordinates and use integers instead Sub-pixel rendering occurs when you render objects on a canvas without whole values. ctx.drawImage(myImage, 0.3, 0.5); This forces the brows...
CaretPosition - Web APIs
Properties This interface doesn't inherit any properties. CaretPosition.offsetNode Read only Returns a Node containing the found node at the caret's position. CaretPosition.offset Read only Returns a long representing the character offset in the caret position node. ...
Client.type - Web APIs
Web › API › Client › type
The type read-only property of the Client interface indicates the type of client the service worker is controlling. Syntax var myClientType = client.type; Value A string, representing the client type. The value can be one of "window" "worker" "sharedworker" Example // service worker client (e.g. ...
Clipboard.readText() - Web APIs
representation among the DataTransfer objects representing the clipboard's contents. To read non-text contents from the clipboard, use the read() method instead. You can write text to the clipboard using writeText(). Example This example retrieves the textual contents of the clipboard and inserts the returned text into an element's contents. navigator.clipboard.readText().then( clipText => document.getElementById("outbox").innerText = clipText); Specifications Specification Status Comment Clipboard API and eventsThe definition of 'readText()' in that specification. Working Draft Initial definition. ...
Clipboard - Web APIs
Web › API › Clipboard
rd vary significantly. Please see the section Clipboard availability for details. All of the Clipboard API methods operate asynchronously; they return a Promise which is resolved once the clipboard access has been completed. The promise is rejected if clipboard access is denied. The clipboard is a data buffer that is used for short-term, data storage and/or data transfers, this can be between documents or applications It is usually implemented as an anonymous, temporary data buffer, sometimes called the paste buffer, that can be accessed from most or all programs within the environment via defined programming interfaces. A typical application accesses clipboard functionality by mapping user input such as keybindings, menu selections, etc. to these interfaces. Methods Clipboard is based o...
ClipboardEvent.clipboardData - Web APIs
Syntax data = ClipboardEvent.clipboardData Specifications Specification Status Comment Clipboard API and eventsThe definition of 'ClipboardEvent.clipboardData' in that specification. Working Draft Initial definition. ...
CloseEvent.initCloseEvent() - Web APIs
This method must be called to set the event before it is dispatched, using EventTarget.dispatchEvent(). Once dispatched, it doesn't do anything anymore. Do not use this method anymore as it is deprecated. Instead use specific event constructors, like CloseEvent(). The page on Creating and triggering events gives more information about the way to use these. ...
CompositionEvent.CompositionEvent() - Web APIs
Obsolete Initial definition. ...
CompositionEvent.data - Web APIs
ing composed. This value doesn't change even if content changes the selection range; rather, it indicates the string that was selected when composition started. For compositionupdate, this is the string as it stands currently as editing is ongoing. For compositionend events, this is the string as committed to the editor. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'data' in that specification. Obsolete Initial definition. ...
CompositionEvent.initCompositionEvent() - Web APIs
er or not the event can bubble. cancelableArg A Boolean shether or not the event can be canceled. viewArg The Window object from which the event was generated. dataArg A DOMString representing the value of the data attribute. localeArg A DOMString representing the value of the locale attribute. Return value Void. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'initCompositionEvent()' in that specification. Obsolete Initial definition. ...
CompositionEvent.locale - Web APIs
...
CompositionEvent - Web APIs
on is associated with IME). Methods This interface also inherits methods of its parent, UIEvent, and its ancestor -- Event. CompositionEvent.initCompositionEvent() Initializes the attributes of a CompositionEvent object. Specifications Specification Status Comment UI EventsThe definition of 'CompositionEvent' in that specification. Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'CompositionEvent' in that specification. Obsolete ...
console.assert() - Web APIs
Web › API › Console › assert
currently work as intended as a parameter for console.assert in all browsers: console.assert(false, 'the word is %s', 'foo'); // correct output in Node.js and some browsers // (e.g. Firefox v60.0.2): // Assertion failed: the word is foo // incorrect output in some browsers // (e.g. Chrome v67.0.3396.87): // Assertion failed: the word is %s foo See Outputting text to the console in the documentation of console for further details. Specifications Specification Status Comment Console APIThe definition of 'console.assert()' in that specification. Living Standard Initial definition ...
console.debug() - Web APIs
Web › API › Console › debug
aining 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 the output. See Using string substitutions in console for a description of how substitutions work. See Outputting text to the console in the documentation of the console object for details. Specifications Specification Status Comment Console APIThe definition of 'console.debug()' in that specification. Living Standard Initial definition ...
Console.error() - Web APIs
Web › API › Console › error
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 Specification Status Comment Console APIThe definition of 'console.error()' in that specification. Living Standard Initial definition ...
Console.group() - Web APIs
Web › API › Console › group
oup, call console.groupEnd(). For example, given this code: console.log("This is the outer level"); console.group(); console.log("Level 2"); console.group(); console.log("Level 3"); console.warn("More of level 3"); console.groupEnd(); console.log("Back to level 2"); console.groupEnd(); console.log("Back to the outer level"); The output looks like this: See Using groups in the console in the documentation of console for more details. Specifications Specification Status Comment Console APIThe definition of 'console.group()' in that specification. Living Standard Initial definition ...
Console.groupCollapsed() - Web APIs
Creates a new inline group in the Web Console. Unlike console.group(), however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. Call console.groupEnd() to back out to the parent group. See Using groups in the console in the console documentation for details and examples. Note: This feature is available in Web Workers. Syntax console.groupCollapsed([label]); Parameters label Label for the group. Optional. Specifications Specification Status Comment Console APIThe definition of 'console.groupCollapsed()' in that specification. Living Standard Initial definition ...
Console.groupEnd() - Web APIs
Web › API › Console › groupEnd
Note: This feature is available in Web Workers. Syntax console.groupEnd(); Parameters None. ...
Console.info() - Web APIs
Web › API › Console › info
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 Specification Status Comment Console APIThe definition of 'console.info()' in that specification. Living Standard Initial definition ...
console.log() - Web APIs
Web › API › Console › log
e 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() and console.log(). Another useful difference in Chrome exists when sending DOM elements to the console. Notice: console.log prints the element in an HTML-like tree console.dir prints the element in a JSON-like tree Specifically, console.log gives special t...
Console.time() - Web APIs
Web › API › Console › time
Note: This feature is available in Web Workers. ...
Console.timeEnd() - Web APIs
Web › API › Console › timeEnd
Note: This feature is available in Web Workers. Syntax console.timeEnd(label); Parameters label The name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the Web Console along with an indicator that the time has ended. ...
Console.timeLog() - Web APIs
Web › API › Console › timeLog
Note: This feature is available in Web Workers. Syntax console.timeLog(label); Parameters label The name of the timer to log to the console. Return If no label parameter included: default: 1042ms If an existing label is included: timer name: 1242ms Exceptions If there is no running timer, timeLog() returns the warning: Timer "default" doesn't exist. If a label parameter is included, but there is no corresponding timer: Timer "timer name" doesn't exist. ...
console.trace() - Web APIs
Web › API › Console › trace
Syntax console.trace( [...any, ...data ]); Parameters ...any, ...data Optional Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the console.log() method. ...
Console.warn() - Web APIs
Web › API › Console › warn
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 Specification Status Comment Console APIThe definition of 'console.warn()' in that specification. Living Standard Initial definition ...
console - Web APIs
Web › API › Console
owser to browser, but there is a de facto set of features that are typically provided. The console object can be accessed from any global object. Window on browsing scopes and WorkerGlobalScope as specific variants in workers via the property console. It's exposed as Window.console, and can be referenced as simply console. For example: console.log("Failed to open the specified link") This page documents the Methods available on the console object and gives a few Usage examples. Note: This feature is available in Web Workers. Note: The actual console interface is defined as all lower case (i.e. not Console), for historical reasons. Methods console.assert() Log a message and stack trace to console if the first argument is false. console.clear() Clear the console. console.count() Log ...
ConstrainBoolean - Web APIs
...
ConstrainDOMString - Web APIs
. Specifications Specification Status Comment Media Capture and StreamsThe definition of 'ConstrainDOMString' in that specification. Candidate Recommendation Initial definition Technically, ConstrainDOMString is actually based on an intermediary dictionary named ConstrainDOMStringParameters, which adds exact and ideal to DOMString. However, for the sake of documentation clarity, the intermediate type (present only because of quirks in WebIDL syntax) is ignored here. ...
ConstrainDouble - Web APIs
edia Capture and StreamsThe definition of 'ConstrainDouble' in that specification. Candidate Recommendation Initial definition Technically, ConstrainDouble is actually based on an intermediary dictionary named ConstrainDoubleRange, which adds exact and ideal to DoubleRange, with ConstrainDouble being a type that can be either a long integer or a DoubleRange. However, for the sake of documentation clarity, the intermediate type (present only because of quirks in WebIDL syntax) is ignored here. ...
ConstrainULong - Web APIs
Media Capture and StreamsThe definition of 'ConstrainULong' in that specification. Candidate Recommendation Initial definition Technically, ConstrainULong is actually based on an intermediary dictionary named ConstrainULongRange, which adds exact and ideal to ULongRange, with ConstrainULong being a type that can be either a long integer or a ULongRange. However, for the sake of documentation clarity, the intermediate type (present only because of quirks in WebIDL syntax) is ignored here. ...
ContentIndex.add() - Web APIs
Web › API › ContentIndex › add
e item registered is an Object containing the following data: id: A unique String identifier. title: A String title for the item. Used in user-visible lists of content. title: A String title of the item. Used in user-visible lists of content. description: A String description of the item. Used in user-visible lists of content. url: A String containing the url of the corresponding HTML document. Needs to be under the scope of the current service worker. category: Optional A String defining the category of content. Can be: '' An empty String, this is the default. homepage article video audio icons: Optional An Array of image resources, defined as an Object with the following data: src: A url String of the source image. sizes: Optional A Stri...
CrashReportBody - Web APIs
For security reasons, no details of the crash are communicated in the body except for a general crash reason. Properties reason A string representing the reason for the crash. Current possible reasons are: oom: The browser ran out of memory. unresponsive: The page was killed due to being unresponsive. ...
CustomElementRegistry.get() - Web APIs
customElements.get(name); Parameters name The name of the custom element whose constructor you want to return a reference to. Return value The constructor for the named custom element, or undefined if there is no custom element definition with that name. ...
CustomElementRegistry.whenDefined() - Web APIs
) to detect when the custom elements that make up a menu are defined. The menu displays placeholder content until the actual menu content is ready to display. <nav id="menu-container"> <div class="menu-placeholder">Loading...</div> <nav-menu> <menu-item>Item 1</menu-item> <menu-item>Item 2</menu-item> ... <menu-item>Item N</menu-item> </nav-menu> </nav> const container = document.getElementById('menu-container'); const placeholder = container.querySelector('.menu-placeholder'); // Fetch all the children of menu that are not yet defined. const undefinedElements = container.querySelectorAll(':not(:defined)'); const promises = [...undefinedElements].map( button => customElements.whenDefined(button.localName) ); // Wait for all the children to be upgraded, // then remove ...
CustomElementRegistry - Web APIs
nt words in element's parent element var wcParent = this.parentNode; function countWords(node){ var text = node.innerText || node.textContent return text.split(/\s+/g).length; } var count = 'Words: ' + countWords(wcParent); // Create a shadow root var shadow = this.attachShadow({mode: 'open'}); // Create text node and add word count to it var text = document.createElement('span'); text.textContent = count; // Append it to the shadow root shadow.appendChild(text); // Update count when element content changes setInterval(function() { var count = 'Words: ' + countWords(wcParent); text.textContent = count; }, 200) } } // Define the new element customElements.define('word-count', WordCount, { extends: 'p' }); N...
CustomEvent.initCustomEvent() - Web APIs
This method must be called to set the event before it is dispatched, using EventTarget.dispatchEvent(). Once dispatched, it doesn't do anything anymore. Do not use this method anymore, as it is deprecated. Note: Rather than using the feature, instead use specific event constructors, like CustomEvent(). ...
DOMError - Web APIs
Web › API › DOMError
the error type names (see below). DOMError.message Read only Returns a DOMString representing a message or description associated with the given error type name. Error types Type Description IndexSizeError The index is not in the allowed range (e.g. thrown in a range object). HierarchyRequestError The node tree hierarchy is not correct. WrongDocumentError The object is in the wrong document. InvalidCharacterError The string contains invalid characters. NoModificationAllowedError The object can not be modified. NotFoundError The object can not be found here. NotSupportedError The operation is not supported InvalidStateError The object is in an invalid state. SyntaxError ...
DOMException - Web APIs
below indicate the legacy code value and constant name that were used in the past. IndexSizeError The index is not in the allowed range. For example, this can be thrown by the Range object. (Legacy code value: 1 and legacy constant name: INDEX_SIZE_ERR) HierarchyRequestError The node tree hierarchy is not correct. (Legacy code value: 3 and legacy constant name: HIERARCHY_REQUEST_ERR) WrongDocumentError The object is in the wrong Document. (Legacy code value: 4 and legacy constant name: WRONG_DOCUMENT_ERR) InvalidCharacterError The string contains invalid characters. (Legacy code value: 5 and legacy constant name: INVALID_CHARACTER_ERR) NoModificationAllowedError The object cannot be modified. (Legacy code value: 7 and legacy constant name: NO_MODIFICATION_ALLOWED_ERR) NotFoundError ...
DOMImplementationList - Web APIs
Returned by DOMImplementationSource.getDOMImplementationList() and DOMImplementationRegistry.getDOMImplementationList() . Can be iterated with 0-based index. Properties DOMImplementationList.length Read only Returns an integer. Methods DOMImplementationList.item() Returns the pos item. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'DOMImplementationList' in that specification. Obsolete Initial definition. ...
DOMLocator - Web APIs
yteOffset Read only Returns a positive integer or -1. DOMLocator.utf16Offset Read only Returns a positive integer or -1. DOMLocator.relatedNode Read only Returns a positive integer or -1. DOMLocator.uri Read only Returns a positive integer or -1. Methods This interface neither implements, nor inherits, any method. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'DOMLocator' in that specification. Obsolete Initial definition ...
DOMMatrixReadOnly.flipX() - Web APIs
00" 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()); ScreenshotLive sample Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMMatrixReadOnly.flipX()' in that specification. Candidate Recommendation Initia...
DOMObject - Web APIs
Web › API › DOMObject
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 ...
DOMParser() - Web APIs
The DOMParser() constructor creates a new DOMParser object. Syntax var parser = new DOMParser(); Parameters None. Return Value A new DOMParser object. This object can be used to parse the text of a document using the parseFromString() method. ...
DOMTokenList.add() - Web APIs
Web › API › DOMTokenList › add
String 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
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. First, the HTML: <span class="a b c"></span> Now the JavaScript: let span = document.querySelector("span"); let classes = span.classList; let result = classes.contains("c"); if (result) { span.textContent = "The classList contains 'c'"; } else { span.textContent = "The classList does not contain 'c'"; } The output looks like this: Specifications Specification Status Comment DOMThe definition of 'contains()' in that specification. Living St...
DOMTokenList.entries() - Web APIs
erator. 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 definition. ...
DOMTokenList.forEach() - Web APIs
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
Web › API › DOMTokenList › item
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
Web › API › DOMTokenList › keys
n 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
s 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.replace() - Web APIs
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 work with IE10-11. To ...
DOMTokenList.supports() - Web APIs
The supports() method of the DOMTokenList interface returns true if a given token is in the associated attribute's supported tokens. This method is intended to support feature detection. Syntax let trueOrFalse = element.supports(token) Parameters token A DOMString containing the token to query for. Returns A Boolean indicating whether the token was found. ...
DOMTokenList.toggle() - Web APIs
urn 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
he 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
erator. 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
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. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'DOMUserData' in that specification. Obsolete Initial specification ...
DataTransfer.dropEffect - Web APIs
er.setData("text", ev.target.id); ev.dataTransfer.effectAllowed = "move"; } function drop_handler(ev) { console.log("drop: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed); ev.preventDefault(); // Get the id of the target and add the moved element to the target's DOM var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragover_handler(ev) { console.log("dragOver: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed); ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move" } Specifications Specification Status Comment HTML Living StandardThe definition of 'dropEff...
DataTransfer.effectAllowed - Web APIs
aTransfer.setData("text", ev.target.id); ev.dataTransfer.effectAllowed = "move"; } function drop_handler(ev) { console.log("drop: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed); ev.preventDefault(); // Get the id of the target and add the moved element to the target's DOM var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragover_handler(ev) { console.log("dragOver: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed); ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move" } </script> <body> <h1>Examples <code>DataTransfer</code>.{<code>dropEffect</code>, <code>effectAllowed</code>} properties</h...
DataTransfer.items - Web APIs
types[" + i + "] = " + ev.dataTransfer.types[i]); } } // Print each item's "kind" and "type" if (ev.dataTransfer.items != null) { for (var i=0; i < ev.dataTransfer.items.length; i++) { console.log("... items[" + i + "...
DataTransfer.setData() - Web APIs
the drag's format and data. ...
DataTransfer.setDragImage() - Web APIs
t drag image will be used. ...
DataTransfer.types - Web APIs
types[" + i + "] = " + ev.dataTransfer.types[i]); } } // Print each item's "kind" and "type" if (ev.dataTransfer.items != null) { for (var i=0; i < ev.dataTransfer.items.length; i++) { console.log("... items[" + i + "...
DataTransfer - Web APIs
e a new item is added, and the mozItemCount is incremented by one. Removed in Firefox 71. DataTransfer.mozTypesAt() Holds a list of the format types of the data that is stored for an item at the specified index. If the index is not in the range from 0 to the number of items minus one, an empty string list is returned. Removed in Firefox 71. Examples Every method and property listed in this document has its own reference page and each reference page either directly includes an example of the interface or has a link to an example. Specifications Specification Status Comment HTML Living StandardThe definition of 'DataTransfer' in that specification. Living Standard mozCursor, mozItemCount, mozSourceNode, mozUserCancelled, addElement(), mozClearDataAt(), mozGetDa...
DataTransferItemList.DataTransferItem() - Web APIs
Drop: HTML = " + s); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI data[i].getAsString(function (s){ ...
DataTransferItemList.add() - Web APIs
Drop: HTML = " + s); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI data[i].getAsString(function (s){ ...
DataTransferItemList.clear() - Web APIs
Drop: HTML = " + s); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI data[i].getAsString(function (s){ ...
DataTransferItemList.length - Web APIs
Drop: HTML = " + s); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI data[i].getAsString(function (s){ ...
DataTransferItemList.remove() - Web APIs
Drop: HTML = " + s); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI data[i].getAsString(function (s){ ...
Detecting device orientation - Web APIs
ixel wide (Yes, it's a tiny one), and the ball is in the center: .garden { position: relative; width : 200px; height: 200px; border: 5px solid #CCC; border-radius: 10px; } .ball { position: absolute; top : 90px; left : 90px; width : 20px; height: 20px; background: green; border-radius: 100%; } Now, if we move our device, the ball will move accordingly: var ball = document.querySelector('.ball'); var garden = document.querySelector('.garden'); var output = document.querySelector('.output'); var maxX = garden.clientWidth - ball.clientWidth; var maxY = garden.clientHeight - ball.clientHeight; function handleOrientation(event) { var x = event.beta; // In degree in the range [-180,180] var y = event.gamma; // In degree in the range [-90,90] output.innerHTML ...
Using light sensors - Web APIs
is generally treated as shown below. 10 ~ 50 lux : Dim Environment 100 ~ 1000 lux : Normal > 10000 lux : Bright It uses the addEventListener method of the window object. window.addEventListener("devicelight", function (event) { // Read out the lux value var luminosity = event.value; alert(luminosity); }); Example: window.addEventListener('devicelight', function(event) { var bodyBg= document.body.style; //event.value is the lux value returned by the sensor on the device if (event.value < 100) { alert('Hey, you! You are working in a dark environment'); bodyBg.backgroundColor="lightgrey"; } else { bodyBg.backgroundColor="#fff"; } }); This example shows how the API can actually be used in the wild. If your app contains a lot of white in the UI, it is usually beneficial to the us...
DirectoryEntrySync - Web APIs
The DirectoryEntrySync interface of the File System API represents a directory in a file system. It includes methods for creating, reading, looking up, and recursively removing files in a directory. This interface has been abandonned: it was on a standard track and it proves not a good idea. Do not use it anymore. About this document This document was last updated on March 2, 2012 and follows the W3C Specifications (Working Draft) drafted on April 19, 2011. This specification is pretty much abandoned, having failed to reach any substantial traction. Basic concepts If you want to create subdirectories, you have to create each child directory in sequence. If you try to create a directory using a full path that includes parent directories that do not exist yet, you get an error. So create ...
DisplayMediaStreamConstraints.video - Web APIs
or sharing. logicalSurface A ConstrainBoolean value which may contain a single Boolean value or a set of them, indicating whether or not to allow the user to choose source surfaces which do not directly correspond to display areas. These may include backing buffers for windows to allow capture of window contents that are hidden by other windows in front of them, or buffers containing larger documents that need to be scrolled through to see the entire contents in their windows. Example Specifications Specification Status Comment UnknownThe definition of 'DisplayMediaStreamConstraints.video' in that specification. Unknown Initial definition ...
Events and the DOM - Web APIs
ment myButton.onclick = function(event){alert('Hello world')} The function can be defined to take an event parameter. The return value is treated in a special way, described in the HTML specification. The problem with this method is that only one handler can be set per element and per event. Accessing Event interfaces Event handlers may be attached to various objects (including DOM elements, document, the window object, etc.). When an event occurs, an event object is created and passed sequentially to the event listeners. The Event interface is accessible from within the handler function, via the event object passed as the first argument. The following simple example shows how an event object is passed to the event handler function, and can be used from within one such function. function pr...
EffectTiming.direction - Web APIs
ernate-reverse" Similar to "alternate", except the animation playback starts by going from the end of the animation sequence toward the beginning the first iteration, then goes forward during the second, and so forth. Examples In the Forgotten Key example, Alice waves her arm up and down by passing her an alternate value for her direction property: // Get Alice's arm, and wave it up and down document.getElementById("alice_arm").animate([ { transform: 'rotate(10deg)' }, { transform: 'rotate(-40deg)' } ], { easing: 'steps(2, end)', iterations: Infinity, direction: 'alternate', duration: 600 }); Specifications Specification Status Comment Web AnimationsThe definition of 'direction' in that specification. Working Draft Editor's draft. ...
EffectTiming.easing - Web APIs
steps(1, start) step-end Equivalent to steps(1, end). ...
EffectTiming.iterations - Web APIs
rough once then stops automatically. Exceptions TypeError An attempt was made to set the value of this property to a negative number or NaN. The property's value is left unchanged. Examples In the Forgotten Key example, Alice waves her arm up and down the entire time the page is open by passing Infinity as the value for her iterations property: // Get Alice's arm, and wave it up and down document.getElementById("alice_arm").animate([ { transform: 'rotate(10deg)' }, { transform: 'rotate(-40deg)' } ], { easing: 'steps(2, end)', iterations: Infinity, direction: 'alternate', duration: 600 }); Specifications Specification Status Comment Web AnimationsThe definition of 'iterations' in that specification. Working Draft Editor's draft. ...
Element.animate() - Web APIs
Web › API › Element › animate
t to accumulate or replace (see above). Defaults to replace. Return value Returns an Animation. Examples In the demo Down the Rabbit Hole (with the Web Animation API), we use the convenient animate() method to immediately create and play an animation on the #tunnel element to make it flow upwards, infinitely. Notice the array of objects passed as keyframes and also the timing options block. document.getElementById("tunnel").animate([ // keyframes { transform: 'translateY(0px)' }, { transform: 'translateY(-300px)' } ], { // timing options duration: 1000, iterations: Infinity }); Implicit to/from keyframes In newer browser versions, you are able to set a beginning or end state for an animation only (i.e. a single keyframe), and the browser will infer the other end of the animat...
Element.attachShadow() - Web APIs
s in element's parent element var wcParent = this.parentNode; function countWords(node){ var text = node.innerText || node.textContent return text.trim().split(/\s+/g).length; } var count = 'Words: ' + countWords(wcParent); // Create a shadow root var shadow = this.attachShadow({mode: 'open'}); // Create text node and add word count to it var text = document.createElement('span'); text.textContent = count; // Append it to the shadow root shadow.appendChild(text); // Update count when element content changes setInterval(function() { var count = 'Words: ' + countWords(wcParent); text.textContent = count; }, 200) } } // Define the new element customElements.define('word-count', WordCount, { extends: 'p' }); Spec...
Element.clientHeight - Web APIs
ero for elements with no CSS or inline layout boxes; otherwise, it's the inner height of an element in pixels. It includes padding but excludes borders, margins, and horizontal scrollbars (if present). clientHeight can be calculated as: CSS height + CSS padding - height of horizontal scrollbar (if present). When clientHeight is used on the root element (the <html> element), (or on <body> if the document is in quirks mode), the viewport's height (excluding any scrollbar) is returned. This is a special case of clientHeight. Note: This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect(). Syntax var intElemClientHeight = element.clientHeight; intElemClientHeight is an integer corresponding to the clientHeight of element in pixels. T...
Element.clientWidth - Web APIs
This is a special case of clientWidth. ...
Element: contextmenu event - Web APIs
sing 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: error event - Web APIs
tarea> </div> CSS body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } button { height: 2rem; margin: .5rem; } img { width: 0; height: 0; } JS const log = document.querySelector('.event-log-contents'); const badImg = document.querySelector('.bad-img'); badImg.addEventListener('error', (event) => { log.textContent = log.textContent + `${event.type}: Loading image\n`; console.log(event) }); const imgError = document.querySelector('#img-error'); imgError.addEventListener('click', () => { badImg.setAttribute('src', 'i-dont-exist'); }); Result ...
Element: focusin event - Web APIs
pposite 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. Document Object Model (DOM) L...
Element: focusout event - Web APIs
posite 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. Document Object Model (DOM) L...
Element: fullscreenerror event - Web APIs
The fullscreenerror event is fired when the browser cannot switch to full-screen mode. Bubbles Yes Cancelable No Interface Event Event handler property onfullscreenerror As with the fullscreenchange event, two fullscreenerror events are fired; the first is sent to the Element which failed to change modes, and the second is sent to the Document which contains that element. For some reasons that switching into full-screen mode might fail, see the guide to the Fullscreen API. Examples const requestor = document.querySelector('div'); requestor.addEventListener('fullscreenerror', (event) => { console.error('an error occurred changing into fullscreen'); console.log(event); }); requestor.requestFullscreen(); Specifications Speci...
Element.getAnimations() - Web APIs
ne of its descendents. Defaults to false. Return value An Array of Animation objects, each representing an animation currently targetting the Element on which this method is called, or one of its descendant elements if { subtree: true } is specified. Examples The following code snippet will wait for all animations on elem and its descendants to finish before removing the element from the document. Promise.all( elem.getAnimations({ subtree: true }) .map(animation => animation.finished) ).then(() => elem.remove()); Specifications Specification Status Comment Web AnimationsThe definition of 'Animatable.getAnimations()' in that specification. Working Draft Editor's draft. ...
Element.getAttribute() - Web APIs
ribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string); see Non-existing attributes for details. Syntax let attribute = element.getAttribute(attributeName); where attribute is a string containing the value of attributeName. attributeName is the name of the attribute whose value you want to get. Examples const div1 = document.getElementById('div1'); const align = div1.getAttribute('align'); alert(align); // Shows the value of align for the element with id="div1" Description Lower casing When called on an HTML element in a DOM flagged as an HTML document, getAttribute() lower-cases its argument before proceeding. Non-existing attributes Essentially all web browsers (Firefox, Internet Explorer, recent versions of ...
Element.getAttributeNode() - Web APIs
Returns the specified attribute of the specified element, as an Attr node. Syntax var attrNode = element.getAttributeNode(attrName); attrNode is an Attr node for the attribute. attrName is a string containing the name of the attribute. Example // html: <div id="top" /> let t = document.getElementById("top"); let idAttr = t.getAttributeNode("id"); alert(idAttr.value == "top") Notes When called on an HTML element in a DOM flagged as an HTML document, getAttributeNode lower-cases its argument before proceeding. The Attr node inherits from Node, but is not considered a part of the document tree. Common Node attributes like parentNode, previousSibling, and nextSibling are null for an Attr node. You can, however, get the element to which the attribute belongs with the ownerElement propert...
Element.getAttributeNodeNS() - Web APIs
tr node for the attribute with the given namespace and name. Syntax attributeNode = element.getAttributeNodeNS(namespace, nodeName) attributeNode is the node for specified attribute. namespace is a string specifying the namespace of the attribute. nodeName is a string specifying the name of the attribute. == Example == TBD The example needs to be fixed pre> // html: <div id="top" /> t = document.getElementById("top"); specialNode = t.getAttributeNodeNS( "http://www.mozilla.org/ns/specialspace", "id"); // iNode.value = "full-top" </pre Notes getAttributeNodeNS is more specific than getAttributeNode in that it allows you to specify attributes that are part of a particular namespace. The corresponding setter method is setAttributeNodeNS. DOM methods dealing with element's attributes: ...
Element.insertAdjacentHTML() - Web APIs
d': After the element itself. text The string to be parsed as HTML or XML and inserted into the tree. Visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> Note: The beforebegin and afterend positions work only if the node is in the DOM tree and has a parent element. Example // <div id="one">one</div> var d1 = document.getElementById('one'); d1.insertAdjacentHTML('afterend', '<div id="two">two</div>'); // At this point, the new structure is: // <div id="one">one</div><div id="two">two</div> Notes Security considerations When inserting HTML into a page by using insertAdjacentHTML(), be careful not to use user input that hasn't been escaped. It is not recommended you use insertAdjacentHTML() when inserting p...
Element.msZoomTo() - Web APIs
Web › API › Element › msZoomTo
al zoom occurs).This argument is ignored if the element is not zoomable. animate[in]: The type of animation to use. default: Uses the default animation. none: No animation is used. This method has no scrolling effect on non-scrollable elements and no zooming effect on non-zoomable elements (e.g., elements with "-ms-content-zooming: none"). This method has no effect if called from a parent document to scroll or zoom content hosted in an iframe. Return value This method does not return a value. Example /* Zooming in on an element while still keeping it centered in the viewport */ var args = { contentX: target.offsetLeft + target.offsetWidth/2; contentY: target.offsetTop + target.offsetHeight/2; scaleFactor: 2.0; } zoomer.msZoomTo(args); See also Microsoft API extensions ...
Element.namespaceURI - Web APIs
element.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { // this is a XUL browser } Notes This is not a computed value that is the result of a namespace lookup based on an examination of the namespace declarations in scope. The namespace URI of a node is frozen at the node creation time. In Firefox 3.5 and earlier, the namespace URI for HTML elements in HTML documents is null. In later versions, in compliance with HTML5, it is http://www.w3.org/1999/xhtml as in XHTML. You can create an element with the specified namespaceURI using the DOM Level 2 method document.createElementNS. The DOM does not handle or enforce namespace validation per se. It is up to the DOM application to do any validation necessary. Also note that the namespace prefix, once it is asso...
Element.onfullscreenerror - Web APIs
An error handler for the fullscreenerror event. Example This example attempts to switch into full-screen mode from outside a handler for a user-initiated event (such as a click or keypress event). Since full-screen mode changes are only permitted in response to a user input, this causes an error to occur, which triggers the delivery of the fullscreenerror event to the error handler, let elem = document.querySelector("video")}} elem.onfullscreenerror = function ( event ) { displayWarning("Unable to switch into full-screen mode."); }; //.... elem.requestFullscreen(); Specifications Specification Status Comment Fullscreen APIThe definition of 'onfullscreenerror' in that specification. Living Standard Initial definition. ...
Element: overflow event - Web APIs
Examples <div id="wrapper"> <div id="child"></div> </div> <br/> <label><input type="checkbox" id="toggle" checked/> Overflow</label> <style> #wrapper { width: 20px; height: 20px; background: #000; padding: 5px; overflow: hidden; } #child { width: 40px; height: 40px; border: 2px solid grey; background: #ccc; } </style> <script> var wrapper = document.getElementById("wrapper"), child = document.getElementById("child"), toggle = document.getElementById("toggle"); wrapper.addEventListener("overflow", function( event ) { console.log( event ); }, false); wrapper.addEventListener("underflow", function( event ) { console.log( event ); }, false); toggle.addEventListener("change", function( event ) { if ( eve...
Element.prefix - Web APIs
Web › API › Element › prefix
The Element.prefix read-only property returns the namespace prefix of the specified element, or null if no prefix is specified. Before DOM4 this API was defined within the Node interface. Syntax string = element.prefix Examples The following logs "x" to the console. <x:div onclick="console.log(this.prefix)"/> Notes This will only work when a namespace-aware parser is used, i.e. when a document is served with an XML MIME type. This will not work for HTML documents. Specifications Specification Status Comment DOMThe definition of 'Element: prefix' in that specification. Living Standard ...
Element.releasePointerCapture() - Web APIs
Recommendation Non-stable version. Pointer EventsThe definition of 'releasePointerCapture' in that specification. ...
Element.removeAttribute() - Web APIs
Living Standard ...
Element.removeAttributeNS() - Web APIs
from an element. Syntax element.removeAttributeNS(namespace, attrName); Parameters namespace is a string that contains the namespace of the attribute. attrName is a string that names the attribute to be removed from the current node. ...
Element.removeAttributeNode() - Web APIs
The removeAttributeNode() method of the Element object removes the specified attribute from the current element. Syntax removedAttr = element.removeAttributeNode(attributeNode) attributeNode is the Attr node that needs to be removed. removedAttr is the removed Attr node. Example // Given: <div id="top" align="center" /> var d = document.getElementById("top"); var d_align = d.getAttributeNode("align"); d.removeAttributeNode(d_align); // align is now removed: <div id="top" /> Notes If the removed attribute has a default value, it is immediately replaced. The replacing attribute has the same namespace URI and local name, as well as the original prefix, when applicable. There is no removeAttributeNodeNS method; the removeAttributeNode method can remove both namespaced attributes and non...
Element.requestPointerLock() - Web APIs
The Element.requestPointerLock() method lets you asynchronously ask for the pointer to be locked on the given element. To track the success or failure of the request, it is necessary to listen for the pointerlockchange and pointerlockerror events at the Document level. Syntax instanceOfElement.requestPointerLock(); Specifications Specification Status Comment Pointer LockThe definition of 'requestPointerLock()' in that specification. Candidate Recommendation ...
Element.scrollIntoView() - Web APIs
l Is an Object with the following properties: behavior Optional Defines the transition animation. One of auto or smooth. Defaults to auto. block Optional Defines vertical alignment. One of start, center, end, or nearest. Defaults to start. inline Optional Defines horizontal alignment. One of start, center, end, or nearest. Defaults to nearest. Example var element = document.getElementById("box"); element.scrollIntoView(); element.scrollIntoView(false); element.scrollIntoView({block: "end"}); element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"}); Notes The element may not be scrolled completely to the top or bottom depending on the layout of other elements. Specifications Specification Status Comment CSS Objec...
Element.scrollIntoViewIfNeeded() - Web APIs
rollable ancestor. If false, the element will be aligned to the nearest edge of the visible area of the scrollable ancestor. Depending on which edge of the visible area is closest to the element, either the top of the element will be aligned to the top edge of the visible area, or the bottom edge of the element will be aligned to the bottom edge of the visible area. Example var element = document.getElementById("my-el"); element.scrollIntoViewIfNeeded(); element.scrollIntoViewIfNeeded(true); // Centers the element in the visible area Specifications Not part of any specification. This is a proprietary, WebKit-specific method. ...
Element.scrollLeft - Web APIs
ent 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.scrollWidth - Web APIs
tton { margin-bottom: 2em; } </style> </head> <body> <div id="aDiv"> FooBar-FooBar-FooBar-FooBar </div> <button id="aButton"> Check for overflow </button> <div id="anotherDiv"> FooBar-FooBar-FooBar-FooBar </div> <button id="anotherButton"> Check for overflow </button> </body> <script> var buttonOne = document.getElementById('aButton'), buttonTwo = document.getElementById('anotherButton'), divOne = document.getElementById('aDiv'), divTwo = document.getElementById('anotherDiv'); //check to determine if an overflow is happening function isOverflowing(element) { return (element.scrollWidth > element.offsetWidth); } function alertOverflow(element) { if (isOverf...
Element.setAttributeNode() - Web APIs
ode 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.setAttribute() usually...
Element.setPointerCapture() - Web APIs
Recommendation Non-stable version. Pointer EventsThe definition of 'setPointerCapture' in that specification. Obs...
Element: show event - Web APIs
ired when a contextmenu event was fired on/bubbled to an element that has a contextmenu attribute. Bubbles No Cancelable No Interface Event Event handler property onshow Examples <div contextmenu="test"></div> <menu type="context" id="test"> <menuitem label="alert" onclick="alert('the alert label has been clicked')" /> </menu> <script> document.getElementById("test").addEventListener("show", function(e){ alert("the context menu will be displayed"); }, false); </script> Specifications Specification Status HTML5The definition of 'show event' in that specification. Recommendation ...
Element: underflow event - Web APIs
Examples <div id="wrapper"> <div id="child"></div> </div> <br/> <label><input type="checkbox" id="toggle" checked/> Overflow</label> <style> #wrapper { width: 20px; height: 20px; background: #000; padding: 5px; overflow: hidden; } #child { width: 40px; height: 40px; border: 2px solid grey; background: #ccc; } </style> <script> var wrapper = document.getElementById("wrapper"), child = document.getElementById("child"), toggle = document.getElementById("toggle"); wrapper.addEventListener("overflow", function( event ) { console.log( event ); }, false); wrapper.addEventListener("underflow", function( event ) { console.log( event ); }, false); toggle.addEventListener("change", function( event ) { if ( eve...
Element: wheel event - Web APIs
Working Draft ...
ElementCSSInlineStyle.style - Web APIs
l CSS properties for an element you should use Window.getComputedStyle() instead. The following code snippet demonstrates the difference between the values obtained using the element's style property and that obtained using the getComputedStyle() method: <!DOCTYPE HTML> <html> <body style="font-weight:bold;"> <div style="color:red" id="myElement">..</div> </body> </html> var element = document.getElementById("myElement"); var out = ""; var elementStyle = element.style; var computedStyle = window.getComputedStyle(element, null); for (prop in elementStyle) { if (elementStyle.hasOwnProperty(prop)) { out += " " + prop + " = '" + elementStyle[prop] + "' > '" + computedStyle[prop] + "'\n"; } } console.log(out) The output would be something like: ... fontWeight = '' > 'bold' colo...
ElementTraversal - Web APIs
It proved useless, as very few types of Node were able to implement all its methods and properties. It has been split into two interfaces, containing the useful methods and properties for each kind of nodes: ChildNode ParentNode As it was a pure interface, with no object of this type, this change has no effect on the Web. Specifications Specification Status Comment DOMThe definition of 'ChildNode' in that specification. ...
Event() - Web APIs
Web › API › Event › Event
l A Boolean indicating whether the event can be cancelled. The default is false. composed Optional A Boolean indicating whether the event will trigger listeners outside of a shadow root (see Event.composed for more details). The default is false. Example // create a look event that bubbles up and cannot be canceled const evt = new Event("look", {"bubbles":true, "cancelable":false}); document.dispatchEvent(evt); // event can be dispatched from any element, not only the document myDiv.dispatchEvent(evt); Specifications Specification Status Comment DOMThe definition of 'Event()' in that specification. Living Standard Initial definition ...
Event.bubbles - Web APIs
Web › API › Event › bubbles
passItOn(e); } // Already bubbling doOutput(e); } Note: Only certain events can bubble. Events that do bubble have this property set to true. You can use this property to check if an event is allowed to bubble or not. Specifications Specification Status Comment DOMThe definition of 'Event.bubbles' in that specification. Living Standard Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'Event.bubbles' in that specification. Obsolete Initial definition. ...
Event.isTrusted - Web APIs
Web › API › Event › isTrusted
modified by a script or dispatched via EventTarget.dispatchEvent(). Syntax var eventIsTrusted = event.isTrusted; Value Boolean Example if (e.isTrusted) { /* The event is trusted */ } else { /* The event is not trusted */ } Specification Specification Status Comment DOMThe definition of 'Event.isTrusted' in that specification. Living Standard Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'Trusted events' in that specification. Obsolete Adds requirements regarding trusted and untrusted events, though it does not itself define the isTrusted property. ...
Event.msConvertURL() - Web APIs
nt.msConvertURL(file, targetType, targetURL); Parameters file [in] Type: File The file object to be converted. targetType [in] Type: DOMString One of the following values indicating the desired conversion type: "specified", "base64", or "unchanged". targetURL [in, optional] Type: URL The target URL. Return value This method does not return a value. Example var blobList = []; document.getElementById("pasteZone").addEventListener('paste', handlePaste, false); function handlePaste(evt) { var fileList = window.clipboardData.files; // Note that window.DataTransfer.files is not applicable. if (!fileList) { console.log("fileList is null."); return; } for (var i = 0; i < fileList.length; i++) { var file = fileList[i]; var...
Event.stopPropagation() - Web APIs
e Example 5: Event Propagation in the Examples chapter for a more detailed example of this method and event propagation in the DOM. Specifications Specification Status Comment DOMThe definition of 'Event.stopPropagation()' in that specification. Living Standard DOM4The definition of 'Event.stopPropagation()' in that specification. Obsolete Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'Event.stopPropagation()' in that specification. Obsolete Initial definition ...
Event - Web APIs
Web › API › Event
where a parent element receives the very same event as its child elements because "spatially" they overlap so the event technically occurs in both, and the processing order of such events depends on the Event bubbling and capture settings of each handler triggered. Interfaces based on Event Below is a list of interfaces which are based on the main Event interface, with links to their respective documentation in the MDN API reference. Note that all event interfaces have names which end in "Event". AnimationEvent AudioProcessingEvent BeforeInputEvent BeforeUnloadEvent BlobEvent ClipboardEvent CloseEvent CompositionEvent CSSFontFaceLoadEvent CustomEvent DeviceLightEvent DeviceMotionEvent DeviceOrientationEvent DeviceProximityEvent DOMTransactionEvent DragEvent EditingBeforeInpu...
EventListener.handleEvent() - Web APIs
ener.handleEvent(event); Parameters event An Event object describing the event that has been fired and needs to be processed. Return value undefined. If you return a value, the browser will ignore it. Specifications Specification Status Comment DOMThe definition of 'EventListener.handleEvent()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'EventListener.handleEvent()' in that specification. Obsolete Initial definition. ...
EventSource() - Web APIs
guration); Parameters url A USVString that represents the location of the remote resource serving the events/messages. configuration Optional Provides options to configure the new connection. The possible entries are: withCredentials, defaulting to false, indicating if CORS should be set to include credentials. Examples var evtSource = new EventSource('sse.php'); var eventList = document.querySelector('ul'); evtSource.onmessage = function(e) { var newElement = document.createElement("li"); newElement.textContent = "message: " + e.data; eventList.appendChild(newElement); } Note: You can find a full example on GitHub -- see Simple SSE demo using PHP. Specifications Specification Status Comment HTML Living StandardThe definition of 'EventSource()...
EventSource.close() - Web APIs
Web › API › EventSource › close
The close() method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed). Note: If the connection is already closed, the method does nothing. Syntax eventSource.close(); Parameters None. Return value Void. Examples var button = document.querySelector('button'); var evtSource = new EventSource('sse.php'); button.onclick = function() { console.log('Connection closed'); evtSource.close(); } Note: You can find a full example on GitHub -- see Simple SSE demo using PHP. Specifications Specification Status Comment HTML Living StandardThe definition of 'close()' in that specification. Living Standard Initial definition ...
EventSource.onmessage - Web APIs
The onmessage property of the EventSource interface is an EventHandler called when a message event is received, that is when a message is coming from the source. Event objects of onmessage event handers are of type MessageEvent. Syntax eventSource.onmessage = function Examples evtSource.onmessage = function(e) { var newElement = document.createElement("li"); newElement.textContent = "message: " + e.data; eventList.appendChild(newElement); } Note: You can find a full example on GitHub -- see Simple SSE demo using PHP. Specifications Specification Status Comment HTML Living StandardThe definition of 'onmessage' in that specification. Living Standard Initial definition ...
FeaturePolicy.features() - Web APIs
text and/or might not be accessible because of user's permissions. Syntax const supportedFeatures = FeaturePolicy.features() Parameters None. Return value A list of strings that represent names of all Feature Policy directives supported by the User Agent. Example The followin example logs all the supported directives in the console. // Get the Feature Policy object const featurePolicy = document.featurePolicy // Retreive the list of all supported Feature Policy directives const supportedDirectives = featurePolicy.features() // Print out each directive into the console for (const directive of supportedDirectives){ console.log(directive) } Specification Specification Status Comment Feature PolicyThe definition of 'features' in that specification. Editor's ...
FeaturePolicy.getAllowlistForFeature() - Web APIs
er, it will also return empty array, inditating that no origin is allowed to use the feature. Example The followin example prints all the origins that are allowed to use Camera API by the Feature Policy. Please note that Camera API might be restricted by the Permissions API, if the user did not grant the corrsponding permission yet. // First, get the Feature Policy object const featurePolicy = document.featurePolicy // Then query feature for specific const allowlist = featurePolicy.getAllowlistForFeature("camera") for (const origin of allowlist){ console.log(origin) } Specification Specification Status Comment Feature PolicyThe definition of 'getAllowlistForFeature' in that specification. Editor's Draft Initial definition. ...
File.getAsBinary() - Web APIs
Web › API › File › getAsBinary
ng it. Summary The getAsBinary method allows to access the file's data in raw binary format. Note: This method is obsolete; you should use the FileReader method readAsBinaryString() or readAsArrayBuffer() instead. Syntax var binary = instanceOfFile.getAsBinary(); Returns A string. ...
File.getAsText() - Web APIs
Web › API › File › getAsText
) instead. Syntax var str = instanceOfFile.getAsText(encoding); Parameters encoding A string indicating the encoding to use for the returned data. If this string is empty, UTF-8 is assumed. Returns A string containing the file's data interpreted as text in the specified encoding. ...
File.lastModified - Web APIs
Web › API › File › lastModified
d date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. Syntax const time = instanceOfFile.lastModified; Value A number that represents the number of milliseconds since the Unix epoch. ...
File.lastModifiedDate - Web APIs
ile.lastModifiedDate read-only property returns the last modified date of the file. Files without a known last modified date returns the current date . Syntax var time = instanceOfFile.lastModifiedDate Value A Date object indicating the date and time at which the file was last modified. ...
File.type - Web APIs
Web › API › File › type
type; alert("Filename: " + name + " , Type: " + type); } } Note: Based on the current implementation, browsers won't actually read the bytestream of a file to determine its media type. It is assumed based on the file extension; a PNG image file renamed to .txt would give "text/plain" and not "image/png". Moreover, file.type is generally reliable only for common file types like images, HTML documents, audio and video. Uncommon file extensions would return an empty string. Client configuration (for instance, the Windows Registry) may result in unexpected values even for common types. Developers are advised not to rely on this property as a sole validation scheme. Specifications Specification Status Comment File APIThe definition of 'type' in that specification. ...
FileEntrySync - Web APIs
This specification is more or less abandoned as it didn't get significant traction among browser makers. Basic concepts To write content to file, create a FileWriter object by calling createWriter(). ...
FileReader: abort event - Web APIs
ght: 5rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } JS const fileInput = document.querySelector('input[type="file"]'); const preview = document.querySelector('img.preview'); const eventLog = document.querySelector('.event-log-contents'); const reader = new FileReader(); function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; ...
FileReader: error event - Web APIs
The error event is fired when the read failed due to an error (for example, because the file was not found or not readable). ...
FileReader: load event - Web APIs
ght: 5rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } JS const fileInput = document.querySelector('input[type="file"]'); const preview = document.querySelector('img.preview'); const eventLog = document.querySelector('.event-log-contents'); const reader = new FileReader(); function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; ...
FileReader: loadend event - Web APIs
ght: 5rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } JS const fileInput = document.querySelector('input[type="file"]'); const preview = document.querySelector('img.preview'); const eventLog = document.querySelector('.event-log-contents'); const reader = new FileReader(); function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; ...
FileReader: loadstart event - Web APIs
ght: 5rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } JS const fileInput = document.querySelector('input[type="file"]'); const preview = document.querySelector('img.preview'); const eventLog = document.querySelector('.event-log-contents'); const reader = new FileReader(); function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; ...
FileReader: progress event - Web APIs
ght: 5rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } JS const fileInput = document.querySelector('input[type="file"]'); const preview = document.querySelector('img.preview'); const eventLog = document.querySelector('.event-log-contents'); const reader = new FileReader(); function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; ...
FileReader.readAsBinaryString() - Web APIs
riggered. At that time, the result attribute contains the raw binary data from the file. Note that this method was once removed from the File API specification, but re-introduced for backward compatibility. Using FileReader.readAsArrayBuffer() is recommended. Syntax instanceOfFileReader.readAsBinaryString(blob); Parameters blob The Blob or File from which to read. ...
FileReader.result - Web APIs
Web › API › FileReader › result
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 creating a FileReader object and creating a listener for load events such that when then file is read, the result is obtained and passed to the callback function provided to read(). The content is handled as raw text data. var fileInput = document.querySelector('input[type="file"]'); function read(callback) { var file = fileInput.files.item(0); var reader = new FileReader(); reader.onload = function() { callback(reader.result); } reader.readAsText(file); } Specifications Specification Status Comment File APIThe definition of 'result' in that specification. Working Draft Initial definiti...
FileRequest.onprogress - Web APIs
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 request.onprogress = function (status) { var progress = document.querySelector('progress'); progress.value = status.loaded; progress.max = status.total; } Specification Not part of any current specification. ...
FileSystemFileEntry.file() - Web APIs
on which is called when the File has been created successfully; the File is passed into the callback as the only parameter. errorCallback Optional If provided, this must be a method which is called when an error occurs while trying to create the File. This callback receives as input a FileError object describing the error. Editor's note: We need to find out what kinds of errors can occur and document them. Return value undefined. Example This example establishes a method, readFile(), reads a text file and calls a specified callback function with the received text (in a String object) once the read is completed. If an error occurs, a specified (optional) error callback is called. function readFile(entry, successCallback, errorCallback) { entry.file(function(file) { let reader = new...
FileSystemSync - Web APIs
The specification is abandonned for the moment, failing to get significant traction. Basic concepts The FileSystemSync object is your gateway to the entire API and you will use it a lot. So once you have a reference, cache the object in a global variable or class property. Attributes Attribute Type Description name readonly DOMString Name of the file system. ...
FileHandle API - Web APIs
LockedFile interface return a FileRequest object. Such an object is basically a DOMRequest with an extra power: it allows to monitor the progress of an operation. Sometimes writing and reading operations can be very long, therefore it is a good idea to monitor the operation to provide feedback to the user. Such monitoring can be done using the FileRequest.onprogress event handler. ...
FocusEvent() - Web APIs
he event. focusEventInit Optional Is a FocusEventInit dictionary, having the following fields: "relatedTarget", optional and defaulting to null, is an EventTarget representing the secondary target of a FocusEvent. The FocusEventInit dictionary also accepts fields from the UIEventInit and EventInit dictionaries. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'FocusEvent()' in that specification. Obsolete Initial definition ...
FocusEvent.relatedTarget - Web APIs
be null. relatedTarget may also be set to null for security reasons, like when tabbing in or out of a page. MouseEvent.relatedTarget is a similar property for mouse events. Syntax secondTarget = focusEvent.relatedTarget Specifications Specification Status Comment UI EventsThe definition of 'FocusEvent.relatedTarget' in that specification. Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'FocusEvent.relatedTarget' in that specification. Obsolete Initial definition. ...
FocusEvent - Web APIs
In some cases (such as when tabbing in or out a page), this property may be set to null for security reasons. Methods This interface has no specific methods. It inherits methods from its parent UIEvent, and indirectly from Event. Specifications Specification Status Comment UI EventsThe definition of 'FocusEvent' in that specification. Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'FocusEvent' in that specification. Obsolete Initial definition. ...
FontFace.FontFace() - Web APIs
Web › API › FontFace › FontFace
escriptors passed as an object. It can have the following keys: family: Family style: Style weight: Weight stretch: Stretch unicodeRange: Unicode range variant: variant featureSettings: Feature settings Example async function loadFonts() { const font = new FontFace('myfont', 'url(myfont.woff)'); // wait for font to be loaded await font.load(); // add font to document document.fonts.add(font); // enable font with CSS class document.body.classList.add('fonts-loaded'); } Specifications Specification Status Comment CSS Font Loading Module Level 3The definition of 'FontFace Constructor' in that specification. Working Draft Initial definition ...
FontFaceSet.check() - Web APIs
Web › API › FontFaceSet › check
aFontFaceSet.check(font); bool = aFontFaceSet.check(font, text); Returns A Boolean that is true if the font list is available Parameters font: a font specification using the CSS value syntax, e.g. "italic bold 16px Roboto" text: limit the font faces to those whose Unicode range contains at least one of the characters in text. This does not check for individual glyph coverage. Examples document.fonts.check("12px courier"); // returns true if the font courier is available at 12px document.fonts.check("12px MyFont", "ss"); // returns true if the font 'MyFont' has a ss character. Specifications Specification Status Comment CSS Font Loading Module Level 3The definition of 'check' in that specification. Working Draft Initial definition ...
FontFaceSet.load() - Web APIs
Web › API › FontFaceSet › load
specification using the CSS value syntax, e.g. "italic bold 16px Roboto" text: limit the font faces to those whose Unicode range contains at least one of the characters in text. This does not check for individual glyph coverage. Examples // returns a promise that will be fulfilled or rejected according the success to load MyFont // The code in 'then' can assume the availability of that font. document.fonts.load("12px MyFont", "ss").then(...); Specifications Specification Status Comment CSS Font Loading Module Level 3The definition of 'load' in that specification. Working Draft Initial definition ...
FormData() - Web APIs
Web › API › FormData › FormData
cc"> </div> <div> <label for="userfile">Upload file:</label> <input type="file" id="userfile" name="userfile"> </div> <input type="submit" value="Submit!"> </form> Note: Only successful form controls are included in a FormData object, i.e. those with a name, not disabled and checked (radio buttons and checkboxes) or selected (one or more options within a select). let myForm = document.getElementById('myForm'); let formData = new FormData(myForm); Specifications Specification Status Comment XMLHttpRequestThe definition of 'FormData()' in that specification. Living Standard Initial definition ...
FormDataEvent.formData - Web APIs
The formData read only property of the FormDataEvent interface contains the FormData object representing the data contained in the form when the event was fired. Syntax formData = formDataEvent.formData Returns A FormData object. ...
FormDataEvent - Web APIs
objects). Constructor FormDataEvent() Creates a new FormDataEvent object instance. Properties Inherits properties from its parent interface, Event. FormDataEvent.formData Contains the FormData object representing the data contained in the form when the event was fired. Methods Inherits methods from its parent interface, Event. ...
Using the Frame Timing API - Web APIs
z refresh rate is a common target for a good responsive user experience. This means the browser should process a frame in about 16.7ms. An application can register a PerformanceObserver for "frame" performance entry types and the observer will have data about the duration of each frame event. This data can be used to help identify areas that take too long to provide a good user experience. This document describes how to use the PerformanceFrameTiming interfaces including example code. For an overview of these interfaces see Frame Timing API. Frame observers The performance observer interfaces allow an application to register an observer for specific performance event types. When one of those event types is added to the browser's performance timeline, the application is notified of the event v...
Frame Timing API - Web APIs
tion can register a PerformanceObserver for "frame" performance entry types. The observer (callback) will be notified when new "frame" events are added to the browser's performance timeline and the frame's duration (length of time) will be available. This data can be used to help identify areas that take too long to provide a good user experience. Example code of the interfaces described in this document is included in Using the Frame Timing API. Performance frames The PerformanceFrameTiming interface extends the following PerformanceEntry properties (for "frame" performance entry types) by qualifying and constrainting the properties as follows: PerformanceEntry.entryType Set to "frame". PerformanceEntry.name Set to the document's address. PerformanceEntry.startTime Set to the DOMHighRe...
GainNode.gain - Web APIs
Web › API › GainNode › gain
e and unmute the audio when a Mute button is clicked by changing the gain property value. ...
GainNode - Web APIs
Web › API › GainNode
e and unmute the audio when a Mute button is clicked by changing the gain property value. ...
GeometryUtils - Web APIs
Properties This interface does not implement any properties. Methods GeometryUtils.getBoxQuads() Returns a list of DOMQuad objects representing the CSS fragments of the node. ...
GlobalEventHandlers.onloadstart - Web APIs
vent handler for the loadstart event. Syntax element.onloadstart = handlerFunction; var handlerFunction = element.onloadstart; handlerFunction should be either null or a JavaScript function specifying the handler for the event. Notes See the DOM event handlers page for information on working with on... handlers. The loadstart event is fired when progress has begun. See the loadstart event documentation for more information about the event. Specification Specification Status Comment HTML Living StandardThe definition of 'loadstart' in that specification. Living Standard ...
GlobalEventHandlers.onabort - Web APIs
TODO: define what "abort" is. Closing the window via window manager? Stopping the load of the page? By which means and reasons (user, network/server)? At which stages would it fire / be caught? For IE, onabort is only available with <img> tags. ...
GlobalEventHandlers.onchange - Web APIs
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. Living Standard ...
GlobalEventHandlers.ondblclick - Web APIs
thin 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.ondrag - Web APIs
solid black; } </style> </head> <script> function drag_handler(ev) { console.log("Drag"); } function dragstart_handler(ev) { console.log("dragStart"); ev.dataTransfer.setData("text", ev.target.id); } function drop_handler(ev) { console.log("Drop"); ev.currentTarget.style.background = "lightyellow"; ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragover_handler(ev) { console.log("dragOver"); ev.preventDefault(); } </script> <body> <h1>Examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <!-- <div class="source"> --> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> Select this e...
GlobalEventHandlers.ondragover - Web APIs
solid black; } </style> </head> <script> function drag_handler(ev) { console.log("Drag"); } function dragstart_handler(ev) { console.log("dragStart"); ev.dataTransfer.setData("text", ev.target.id); } function drop_handler(ev) { console.log("Drop"); ev.currentTarget.style.background = "lightyellow"; ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragover_handler(ev) { console.log("dragOver"); ev.preventDefault(); } </script> <body> <h1>Examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zo...
GlobalEventHandlers.ondragstart - Web APIs
solid black; } </style> </head> <script> function drag_handler(ev) { console.log("Drag"); } function dragstart_handler(ev) { console.log("dragStart"); ev.dataTransfer.setData("text", ev.target.id); } function drop_handler(ev) { console.log("Drop"); ev.currentTarget.style.background = "lightyellow"; ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragover_handler(ev) { console.log("dragOver"); ev.preventDefault(); } </script> <body> <h1>Examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zo...
GlobalEventHandlers.ondrop - Web APIs
solid black; } </style> </head> <script> function drag_handler(ev) { console.log("Drag"); } function dragstart_handler(ev) { console.log("dragStart"); ev.dataTransfer.setData("text", ev.target.id); } function drop_handler(ev) { console.log("Drop"); ev.currentTarget.style.background = "lightyellow"; ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragover_handler(ev) { console.log("dragOver"); ev.preventDefault(); } </script> <body> <h1>Examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div class="source"> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it...
GlobalEventHandlers.onemptied - Web APIs
ion should be either null or a JavaScript function specifying the handler for the event. 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. See the emptied event documentation for more information about the event. Specification Specification Status Comment HTML Living StandardThe definition of 'onemptied' in that specification. Living Standard ...
GlobalEventHandlers.onfocus - Web APIs
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 Living StandardThe defi...
GlobalEventHandlers.onformdata - Web APIs
onstructed. This happens when the form is submitted, but can also be triggered by the invocation of a FormData() constructor. onformdata is available on HTMLFormElement. Syntax target.onformdata = functionRef; Value functionRef is a function name or a function expression. The function receives a FormDataEvent object as its sole argument. ...
GlobalEventHandlers.ongotpointercapture - Web APIs
gotpointercapture events. Syntax target.ongotpointercapture = functionRef; Value functionRef is a function name or a function expression. The function receives a PointerEvent object as its sole argument. Example function overHandler(event) { // Determine the target event's gotpointercapture handler let gotCaptureHandler = event.target.ongotpointercapture; } function init() { let el = document.getElementById('target'); el.ongotpointercapture = overHandler; } Specifications Specification Status Comment Pointer Events - Level 2The definition of 'ongotpointercapture' in that specification. Recommendation ...
GlobalEventHandlers.oninput - Web APIs
et.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. Living Standard Ini...
GlobalEventHandlers.onkeydown - Web APIs
wn 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 ...
GlobalEventHandlers.onkeyup - Web APIs
when the user releases a key that was previously pressed. Syntax target.onkeyup = 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 release a key inside the <input> element. HTML <input> <p id="log"></p> JavaScript const input = document.querySelector('input'); const log = document.getElementById('log'); input.onkeyup = logKey; function logKey(e) { log.textContent += ` ${e.code}`; } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'onkeyup' in that specification. Living Standard ...
GlobalEventHandlers.onlostpointercapture - Web APIs
ointercapture events. Syntax target.onlostpointercapture = functionRef; Value functionRef is a function name or a function expression. The function receives a PointerEvent object as its sole argument. Example function overHandler(event) { // Determine the target event's lostpointercapture handler let lostCaptureHandler = event.target.onlostpointercapture; } function init() { let el = document.getElementById('target'); el.onlostpointercapture = overHandler; } Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onlostpointercapture' in that specification. Recommendation ...
GlobalEventHandlers.onmouseout - Web APIs
vent fires when the mouse leaves an element. For example, when the mouse moves off of an image in the web page, the mouseout event is raised for that image element. Syntax element.onmouseout = function; Example This example adds an onmouseout and an onmouseover event to a paragraph. Try moving your mouse over and out of the element. HTML <p>Test your mouse on me!</p> JavaScript const p = document.querySelector('p'); p.onmouseover = logMouseOver; p.onmouseout = logMouseOut; function logMouseOver() { p.innerHTML = 'MOUSE OVER detected'; } function logMouseOut() { p.innerHTML = 'MOUSE OUT detected'; } Result Specification Specification Status Comment HTML Living StandardThe definition of 'onmouseout' in that specification. Living Standard ...
GlobalEventHandlers.onmouseover - Web APIs
e GlobalEventHandlers mixin is an EventHandler that processes mouseover events. The mouseover event fires when the user moves the mouse over a particular element. Syntax element.onmouseover = function; Example This example adds an onmouseover and an onmouseout event to a paragraph. Try moving your mouse over and out of the element. HTML <p>Test your mouse on me!</p> JavaScript const p = document.querySelector('p'); p.onmouseover = logMouseOver; p.onmouseout = logMouseOut; function logMouseOver() { p.innerHTML = 'MOUSE OVER detected'; } function logMouseOut() { p.innerHTML = 'MOUSE OUT detected'; } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'onmouseover' in that specification. Living Standard ...
GlobalEventHandlers.onmousewheel - Web APIs
...
GlobalEventHandlers.onpointercancel - Web APIs
tElement.onpointercancel = cancelHandler; var cancelHandler = targetElement.onpointercancel; Value cancelHandler The pointercancel event handler for element targetElement. Example This example shows two ways to use onpointercancel to handle an element's pointercancel events. <html> <script> function cancelHandler(ev) { // Process the pointercancel event } function init() { var el = document.getElementById('target1'); el.onpointercancel = cancelHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointercancel="cancelHandler(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onpointercancel' in that specification. ...
GlobalEventHandlers.onpointerenter - Web APIs
targetElement.onpointerenter = enterHandler; var enterHandler = targetElement.onpointerenter; Value enterHandler The pointerenter event handler for element targetElement. Example This example shows two ways to use onpointerenter to set an element's pointerenter event handler. <html> <script> function enterHandler(ev) { // Process the pointerenter event } function init() { let el = document.getElementById('target1'); el.onpointerenter = enterHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointerenter="enterHandler(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onpointerenter' in that specification. Reco...
GlobalEventHandlers.onpointerleave - Web APIs
eave = leaveHandler; var leaveHandler = EventTarget.onpointerleave; Value leaveHandler The EventListener which will be invoked to handle pointerleave events sent to the target. Example This example shows two ways to use onpointerleave to set an element's pointerleave event handler. <html> <script> function leaveHandler(ev) { // Process the pointerleave event } function init() { var el=document.getElementById("target1"); el.onpointerleave = leaveHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointerleave="leaveHandler(event)"> Touch me ... </div> </body> </html> See Using Pointer Events for additional details. Specifications Specification Status Comment Pointer Events - Level 2The definition of 'on...
GlobalEventHandlers.onpointermove - Web APIs
ts. Syntax targetElement.onpointermove = moveHandler; var moveHandler = targetElement.onpointermove; Value moveHandler The pointermove event handler for element targetElement. Example This example shows two ways to use onpointermove to set an element's pointermove event handler. <html> <script> function moveHandler(ev) { // Process the pointermove event } function init() { let el=document.getElementById('target1'); el.onpointermove = moveHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointermove="moveHandler(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onpointermove' in that specification. Recommend...
GlobalEventHandlers.onpointerout - Web APIs
erout events. Syntax targetElement.onpointerout = outHandler; var outHandler = targetElement.onpointerout; Value outHandler The pointerout event handler for element targetElement. Example This example shows two ways to use onpointerout to set an element's pointerout event handler. <html> <script> function outHandler(ev) { // Process the pointerout event } function init() { let el=document.getElementById('target1'); el.onpointerout = outHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointerout="outHandler(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onpointerout' in that specification. Recommendation...
GlobalEventHandlers.onpointerover - Web APIs
. Syntax targetElement.onpointerover = overHandler; var overHandler = targetElement.onpointerover; Value overHandler The pointerover event handler for element targetElement. Example This example shows two ways to use onpointerover to set an element's pointerover event handler. <html> <script> function overHandler(ev) { // Process the pointerover event } function init() { let el = document.getElementById('target1'); el.onpointerover = overHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointerover="overHandler(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onpointerover' in that specification. Recommend...
GlobalEventHandlers.onpointerup - Web APIs
ses pointerup events. Syntax targetElement.onpointerup = upHandler; var upHandler = targetElement.onpointerup; Value upHandler The pointerup event handler for element targetElement. Example This example shows two ways to use onpointerup to set an element's pointerup event handler. <html> <script> function upHandler(ev) { // Process the pointerup event } function init() { let el = document.getElementById('target1'); el.onpointerup = upHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointerup="upHandler(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onpointerup' in that specification. Recommendation N...
GlobalEventHandlers.onreset - Web APIs
es an Event object as its sole argument. Example This example logs the current Event.timeStamp whenever you reset the form. 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.onreset = logReset; Result Specification Specification Status Comment HTML Living StandardThe definition of 'onreset' in that specification. Living Standard ...
GlobalEventHandlers.onresize - Web APIs
n resized. Syntax window.onresize = functionRef; Value functionRef is a function name or a function expression. The function receives a FocusEvent object as its sole argument. Examples Window size logger <p>Resize the browser window to fire the <code>resize</code> event.</p> <p>Window height: <span id="height"></span></p> <p>Window width: <span id="width"></span></p> const heightOutput = document.querySelector('#height'); const widthOutput = document.querySelector('#width'); function resize() { heightOutput.textContent = window.innerHeight; widthOutput.textContent = window.innerWidth; } window.onresize = resize; Specification Specification Status Comment HTML Living StandardThe definition of 'onresize' in that specification. Living Standard ...
GlobalEventHandlers.onselectionchange - Web APIs
nselectionchange property of the GlobalEventHandlers mixin is an EventHandler that processes selectionchange events. The selectionchange event fires when the text selected on a webpage changes. Syntax object.onselectionchange = functionRef; Value functionRef is a function name or a function expression. The function receives a FocusEvent object as its sole argument. Example let selection; document.onselectionchange = function() { console.log('New selection made'); selection = document.getSelection(); }; For a full example, see our Key quote generator demo. Specifications Specification Status Comment Selection APIThe definition of 'GlobalEventHandlers.onselectionchange' in that specification. Working Draft Initial definition. ...
GlobalEventHandlers.onselectstart - Web APIs
The onselectstart property of the GlobalEventHandlers mixin is an EventHandler that processes selectstart events. The selectstart event fires when the user starts to make a new text selection on a webpage. Syntax object.onselectstart = functionRef; Value functionRef is a function name or a function expression. The function receives a FocusEvent object as its sole argument. Example document.onselectstart = function() { console.log('Selection started!'); }; For a full example, see our Key quote generator demo. Specifications Specification Status Comment Selection APIThe definition of 'GlobalEventHandlers.onselectstart' in that specification. Working Draft Initial definition. ...
GlobalEventHandlers.ontouchcancel - Web APIs
dation. This attribute is not widely implemented. Syntax var cancelHandler = someElement.ontouchcancel; Return value cancelHandler The touchcancel event handler for element someElement. Example This example shows two ways to use ontouchcancel to set an element's touchcancel event handler. <html> <script> function cancelTouch(ev) { // Process the event } function init() { let el = document.getElementById('target1'); el.ontouchcancel = cancelTouch; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" ontouchcancel="cancelTouch(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. ...
GlobalEventHandlers.ontouchend - Web APIs
uch Events Recommendation. This attribute is not widely implemented. Syntax var endHandler = targetElement.ontouchend; Return value endHandler The touchend event handler for element targetElement. Example This example shows two ways to use ontouchend to set an element's touchend event handler. <html> <script> function endTouch(ev) { // Process the event } function init() { var el=document.getElementById("target1"); el.ontouchend = endTouch; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" ontouchend="endTouch(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. ...
GlobalEventHandlers.ontouchmove - Web APIs
Recommendation. This attribute is not widely implemented. Syntax var moveHandler = someElement.ontouchmove; Return value moveHandler The touchmove event handler for element someElement. Example This example shows two ways to use ontouchmove to set an element's touchmove event handler. <html> <head> <script> function moveTouch(ev) { // Process the event } function init() { var el=document.getElementById("target1"); el.ontouchmove = moveTouch; } </script> </head> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" ontouchmove="moveTouch(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. ...
GlobalEventHandlers.ontouchstart - Web APIs
ecommendation. This attribute is not widely implemented. Syntax var startHandler = someElement.ontouchstart; Return value startHandler The touchstart event handler for element someElement. Example This example shows two ways to use ontouchstart to set an element's touchstart event handler. <html> <script> function startTouch(ev) { // Process the event } function init() { let el = document.getElementById('target1'); el.ontouchstart = startTouch; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" ontouchstart="startTouch(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. ...
HTMLAnchorElement.referrerPolicy - Web APIs
eader will not be sent. "origin" meaning that the referrer will be the origin of the page, that is roughly the scheme, the host and the port. "unsafe-url" meaning that the referrer will include the origin and the path (but not the fragment, password, or username). This case is unsafe as it can leak path information that has been concealed to third-party by using TLS. Examples var elt = document.createElement("a"); var linkText = document.createTextNode("My link"); elt.appendChild(linkText); elt.href = "https://developer.mozilla.org/"; elt.referrerPolicy = "no-referrer"; var div = document.getElementById("divAround"); div.appendChild(elt); // When clicked, the link will not send a referrer header. Specifications Specification Status Comment Referrer Policy...
HTMLAreaElement.referrerPolicy - Web APIs
cheme, the host and the port. "unsafe-url" meaning that the referrer will include the origin and the path (but not the fragment, password, or username). This case is unsafe as it can leak path information that has been concealed to third-party by using TLS. Examples <img usemap="#mapAround" width="100" height="100" src="/img/logo@2x.png" /> <map id="myMap" name="mapAround" />> var elt = document.createElement("area"); elt.href = "/img2.png"; elt.shape = "rect"; elt.referrerPolicy = "no-referrer"; elt.coords = "0,0,100,100"; var map = document.getElementById("myMap"); map.appendChild(elt); // When clicked, the area's link will not send a referrer header. Specifications Specification Status Comment Referrer PolicyThe definition of 'referrerpolicy attribute' ...
HTMLAreaElement.rel - Web APIs
The HTMLAreaElement.rel property reflects the rel attribute. It is a DOMString containing a space-separated list of link types indicating the relationship between the resource represented by the <area> element and the current document. Syntax var relstr = areaElt.rel; areaElt.rel = relstr; Example var areas = document.getElementsByTagName("area"); var length = areas.length; for (var i = 0; i < length; i++) { alert("Rel: " + areas[i].rel); } Specifications Specification Status Comment HTML Living StandardThe definition of 'rel' in that specification. Living Standard Initial definition ...
HTMLBRElement - Web APIs
around floating objects. ...
HTMLButtonElement.labels - Web APIs
d with the <button> element. Syntax var labelElements = button.labels; Return value A NodeList containing the <label> elements associated with the <button> element. Example HTML <label id="label1" for="test">Label 1</label> <button id="test">Button</button> <label id="label2" for="test">Label 2</label> JavaScript window.addEventListener("DOMContentLoaded", function() { const button = document.getElementById("test"); for(var i = 0; i < button.labels.length; i++) { console.log(button.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Living Standard Initial definition ...
HTMLCanvasElement.captureStream() - Web APIs
ges; if set to 0, frames will not be captured automatically; instead, they will only be captured when the returned track's requestFrame() method is called. Return value A reference to a MediaStream object, which has a single CanvasCaptureMediaStreamTrack in it. Exceptions NotSupportedError The value of frameRate is negative. Example // Find the canvas element to capture var canvasElt = document.querySelector('canvas'); // Get the stream var stream = canvasElt.captureStream(25); // 25 FPS // Do things to the stream // E.g. Send it to another computer using an RTCPeerConnection // pc is an RTCPeerConnection created elsewhere pc.addStream(stream); Specifications Specification Status Comment Media Capture from DOM ElementsThe definition of 'HTMLCanvasEl...
HTMLCanvasElement.getContext() - Web APIs
deringContext for "webgl" and "experimental-webgl", WebGL2RenderingContext for "webgl2" or ImageBitmapRenderingContext for "bitmaprenderer". If the contextType doesn't match a possible drawing context, null is returned. Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> You can get a 2d context of the canvas with the following code: var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); console.log(ctx); // CanvasRenderingContext2D { ... } Now you have the 2D rendering context for a canvas and you can draw within it. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLCanvasElement.getContext' in that specification. Living Standard No change since the...
HTMLCanvasElement.height - Web APIs
ue, like a negative, the default value of 150 is used. This is one of the two properties, the other being HTMLCanvasElement.width, that controls the size of the canvas. Syntax var pxl = canvas.height; canvas.height = pxl; Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> You can get the height of the canvas with the following code: var canvas = document.getElementById('canvas'); console.log(canvas.height); // 300 Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLCanvasElement.height' in that specification. Living Standard No change since the latest snapshot, HTML5 HTML 5.1The definition of 'HTMLCanvasElement.height' in that specification. Recommendation ...
HTMLCanvasElement.mozFetchAsStream() - Web APIs
tStreamCallback. type Optional A DOMString indicating the image format. The default type is image/png. Return value None. Examples Save to disk with mozFetchAsStream (Chrome context only) This technique also converts it to ico, however it will not work in Windows XP as WinXP cannot convert from PNG to ICO. It saves to the desktop it uses FileUtils.jsm. ...
HTMLCanvasElement.mozOpaque - Web APIs
. Syntax var opaque = canvas.mozOpaque; canvas.mozOpaque = true; Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300" moz-opaque></canvas> You can get or set the mozOpaque property. For example, you could conditionally set it to true if mimeType == 'image/jpeg', or similar, to gain performance in your application when translucency is not needed. var canvas = document.getElementById('canvas'); console.log(canvas.mozOpaque); // true // deactivate it canvas.mozOpaque = false; Specifications Not part of any standard. ...
HTMLCanvasElement.transferControlToOffscreen() - Web APIs
The HTMLCanvasElement.transferControlToOffscreen() method transfers control to an OffscreenCanvas object, either on the main thread or on a worker. Syntax OffscreenCanvas HTMLCanvasElement.transferControlToOffscreen() Return value An OffscreenCanvas object. Examples var htmlCanvas = document.createElement('canvas'); var offscreen = htmlCanvas.transferControlToOffscreen(); var gl = offscreen.getContext('webgl'); // ... some drawing using the gl context ... // Push frames back to the original HTMLCanvasElement gl.commit(); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLCanvasElement.transferControlToOffscreen()' in that specification. Living Standard ...
HTMLCanvasElement: webglcontextcreationerror event - Web APIs
WebGL API is fired if the user agent is unable to create a WebGLRenderingContext context. This event has a WebGLContextEvent.statusMessage property, which can contain a platform dependent string with more information about the failure. ...
HTMLCanvasElement: webglcontextlost event - Web APIs
of the WebGL API is fired if the user agent detects that the drawing buffer associated with a WebGLRenderingContext object has been lost. Bubbles Yes Cancelable Yes Interface WebGLContextEvent Event handler property none Example With the help of the WEBGL_lose_context extension, you can simulate the webglcontextlost event: const canvas = document.getElementById('canvas'); const gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', (event) => { console.log(event); }); gl.getExtension('WEBGL_lose_context').loseContext(); // "webglcontextlost" event is logged. Specifications Specification Status Comment WebGL 1.0The definition of 'webglcontextlost' in that specification. Recommendation...
HTMLCanvasElement: webglcontextrestored event - Web APIs
ed before the context was lost are no longer valid. You need to reinitialize the state of your WebGL application and recreate resources. Bubbles Yes Cancelable Yes Interface WebGLContextEvent Event handler property none Example With the help of the WEBGL_lose_context extension, you can simulate the webglcontextrestored event: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getExtension('WEBGL_lose_context').restoreContext(); // "webglcontextrestored" event is logged. Specifications Specification Status Comment WebGL 1.0The definition of 'webglcontextrestored' in that specification. ...
HTMLCanvasElement.width - Web APIs
alue, like a negative, the default value of 300 is used. This is one of the two properties, the other being HTMLCanvasElement.height, that controls the size of the canvas. Syntax var pxl = canvas.width; canvas.width = pxl; Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> You can get the width of the canvas with the following code: var canvas = document.getElementById('canvas'); console.log(canvas.width); // 300 Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLCanvasElement.width' in that specification. Living Standard No change since the latest snapshot, HTML5 HTML 5.1The definition of 'HTMLCanvasElement.width' in that specification. Recommendation ...
HTMLDListElement - Web APIs
etween list items should be reduced. Methods No specific methods; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLDListElement' in that specification. Living Standard HTML5The definition of 'HTMLDListElement' in that specification. Recommendation No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLDListElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLDListElement' in that specification. Obsolete Initial definit...
HTMLDetailsElement: toggle event - Web APIs
s> <details id="ch3"> <summary>Chapter III</summary> Boethius falls back upon his present sense of misery. Philosophy reminds him of the brilliancy of his former fortunes. </details> </section> CSS body { display: flex; flex-direction: row-reverse; } #log { flex-shrink: 0; padding-left: 3em; } #summaries { flex-grow: 1; } JavaScript function logItem(e) { const item = document.querySelector(`[data-id=${e.target.id}]`); item.toggleAttribute('hidden'); } const chapters = document.querySelectorAll('details'); chapters.forEach((chapter) => { chapter.addEventListener('toggle', logItem); }); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'toggle event' in that specification. Living Standard ...
HTMLDialogElement.close() - Web APIs
<option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function() { var updateButton = document.getElementById('updateDetails'); var cancelButton = document.getElementById('cancel'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if(dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } } // Update button opens a mo...
HTMLDialogElement.open - Web APIs
<option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function() { var updateButton = document.getElementById('updateDetails'); var cancelButton = document.getElementById('cancel'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if(dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } } // Update button opens a mo...
HTMLDialogElement.returnValue - Web APIs
<option>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select> </label></p> <menu> <button>Cancel</button> <button>Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function() { var updateButton = document.getElementById('updateDetails'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if (dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } } function handleUserInput(returnValue) { if (returnValue === 'Cancel' || return...
HTMLDialogElement.show() - Web APIs
<option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function() { var updateButton = document.getElementById('updateDetails'); var cancelButton = document.getElementById('cancel'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if(dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } } // Update button opens a mo...
HTMLDialogElement.showModal() - Web APIs
<option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function() { var updateButton = document.getElementById('updateDetails'); var cancelButton = document.getElementById('cancel'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if(dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } } // Update button opens a mo...
HTMLDialogElement - Web APIs
<option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function() { var updateButton = document.getElementById('updateDetails'); var cancelButton = document.getElementById('cancel'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if(dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } } // Update button opens a mo...
HTMLDivElement - Web APIs
"left", "right", "justify", and "center". Methods No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLDivElement' in that specification. Living Standard HTML5The definition of 'HTMLDivElement' in that specification. Recommendation No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLDivElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLDivElement' in that specification. Obsolete Initial definition.
accessKeyLabel - Web APIs
The HTMLElement.accessKeyLabel read-only property returns a String that represents the element's assigned access key (if any); otherwise it returns an empty string. Syntax label = element.accessKeyLabel Example JavaScript var node = document.getElementById('btn1'); if (node.accessKeyLabel) { node.title += ' [' + node.accessKeyLabel + ']'; } else { node.title += ' [' + node.accessKey + ']'; } node.onclick = function () { var p = document.createElement('p'); p.textContent = 'Clicked!'; node.parentNode.appendChild(p); }; HTML <button accesskey="h" title="Caption" id="btn1">Hover me</button> Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLElement.accessKeyLabel' in that specification. Living Standar...
HTMLElement: beforeinput event - Web APIs
Event handler property None Sync / Async Sync Composed Yes Default Action Update the DOM element Examples This example logs current value of the element immediately before replacing that value with the new one applied to the <input> element. HTML <input placeholder="Enter some text" name="name"/> <p id="values"></p> JavaScript const input = document.querySelector('input'); const log = document.getElementById('values'); input.addEventListener('beforeinput', updateValue); function updateValue(e) { log.textContent = e.target.value; } Result Specifications Specification Status UI EventsThe definition of 'beforeinput event' in that specification. Working Draft ...
HTMLElement.contextMenu - Web APIs
The HTMLElement.contextMenu property refers to the context menu assigned to an element using the contextmenu attribute. ...
HTMLElement.hidden - Web APIs
nts 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 for the two ...
HTMLElement: input event - Web APIs
value of the element changes. This is unlike the change event, which only fires when the value is committed, such as by pressing the enter key, selecting a value from a list of options, and the like. Examples This example logs the value whenever you change the value of the <input> element. HTML <input placeholder="Enter some text" name="name"/> <p id="values"></p> JavaScript const input = document.querySelector('input'); const log = document.getElementById('values'); input.addEventListener('input', updateValue); function updateValue(e) { log.textContent = e.target.value; } Result Specifications Specification Status HTML Living StandardThe definition of 'input event' in that specification. Living Standard Document Object Model (DOM) Level 3 Even...
HTMLElement.isContentEditable - Web APIs
property returns a Boolean that is true if the contents of the element are editable; otherwise it returns false. Syntax editable = element.isContentEditable Example HTML <p id="myText1">Uneditable Paragraph</p> <p id="myText2" contentEditable="true">Editable Paragraph</p> <p id="infoText1">Can edit the first paragraph? </p> <p id="infoText2">Can edit the second paragraph? </p> JavaScript document.getElementById('infoText1').innerHTML += document.getElementById('myText1').isContentEditable; document.getElementById('infoText2').innerHTML += document.getElementById('myText2').isContentEditable; Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLElement.contenteditable' in that specification. Living Standard No ...
HTMLElement.offsetHeight - Web APIs
The HTMLElement.offsetHeight read-only property returns the height of an element, including vertical padding and borders, as an integer. Typically, offsetHeight is a measurement in pixels of the element's CSS height, including any borders, padding, and horizontal scrollbars (if rendered). It does not include the height of pseudo-elements such as ::before or ::after. For the document body object, the measurement includes total linear content height instead of the element's CSS height. Floated elements extending below other linear content are ignored. If the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned. This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientR...
HTMLElement.offsetTop - Web APIs
The HTMLElement.offsetTop read-only property returns the distance of the current element relative to the top of the offsetParent node. Syntax topPos = element.offsetTop; Parameters topPos is the number of pixels from the top of the closest relatively positioned parent element. Example var d = document.getElementById("div1"); var topPos = d.offsetTop; if (topPos > 10) { // object is offset more // than 10 pixels from its parent } Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'offsetTop' in that specification. Working Draft 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 http...
HTMLFontElement.color - Web APIs
...
HTMLFontElement.size - Web APIs
...
HTMLFontElement - Web APIs
The HTML Font Element <font> defines the font size, font face and color of text. Properties Inherits properties from its parent, HTMLElement. HTMLFontElement.color Is a DOMString that reflects the color HTML attribute, containing either a named color or a color specified in the hexadecimal #RRGGBB format. HTMLFontElement.face Is a DOMString that reflects the face HTML attribute, containing a comma-separated list of one or more font names. HTMLFontElement.size Is a DOMString that reflects the size HTML attribute, containing either a font size number ranging from 1 to 7 or a relative size to the size attribute of the <basefont> element, for example -2 or +1. ...
HTMLFormControlsCollection.namedItem() - Web APIs
lection["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. Recommendation In this snapshot of HTML Living Standard, the HTMLFormControlsCollec...
HTMLFormElement.acceptCharset - Web APIs
The HTMLFormElement.acceptCharset property represents a list of the supported character encodings for the given <form> element. This list can be comma-separated or space-separated. Syntax var string = form.acceptCharset; form.acceptCharset = string; Example inputs = document.forms['myform'].acceptCharset; Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement: acceptCharset' in that specification. Living Standard ...
HTMLFormElement: formdata event - Web APIs
he 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. ...
HTMLFormElement.length - Web APIs
a> No other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms. Syntax numControls = form.length; Value numControls is the number of form controls within the <form>. This is the same as the number of the elements in the HTMLFormControlsCollection returned by the elements property. Example if (document.getElementById('form1').length > 1) { // more than one form control here } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement: length' in that specification. Living Standard ...
HTMLFormElement.method - Web APIs
The HTMLFormElement.method property represents the HTTP method used to submit the <form>. Unless explicitly specified, the default method is 'get'. Syntax var string = form.method; form.method = string; Example document.forms['myform'].method = 'post'; const formElement = document.createElement("form"); // Create a form document.body.appendChild(formElement); console.log(formElement.method); // 'get' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement: method' in that specification. Living Standard ...
HTMLFormElement.name - Web APIs
current <form> element as a string. If your <form> element contains an element named name then that element overrides the form.name property, so that you can't access it. Internet Explorer (IE) does not allow the name attribute of an element created using createElement() to be set or modified using the name property. Syntax var string = form.name; form.name = string; Example var form1name = document.getElementById('form1').name; if (form1name != document.form.form1) { // Browser doesn't support this form of reference } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement: name' in that specification. Living Standard ...
HTMLFormElement.reportValidity() - Web APIs
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user. Syntax HTMLFormElement.reportValidity() Return value Boolean Example document.forms['myform'].addEventListener('submit', function() { document.forms['myform'].reportValidity(); }, false); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement.reportValidity()' in that specification. Living Standard HTML 5.1The definition of 'HTMLFormElement.reportValidity()' in that specification. Recommendation Initial definition ...
HTMLFormElement.requestSubmit() - Web APIs
by attempting to send the request using requestSubmit() if it's available. If a submit button with the ID main-submit is found, that's used to submit the form. Otherwise, the form is submitted with no submitter parameter, so it's submitted directly by the form itself. If, on the other hand, requestSubmit() isn't available, this code falls back to calling the form's submit() method. let myForm = document.querySelector("form"); let submitButton = myForm.querySelector("#main-submit"); if (myForm.requestSubmit) { if (submitButton) { myForm.requestSubmit(submitButton); } else { myForm.requestSubmit(); } } else { myForm.submit(); } Specifications Specification Status Comment HTML Living StandardThe definition of 'requestSubmit()' in that specification. ...
HTMLFormElement.reset() - Web APIs
The HTMLFormElement.reset() method restores a form element's default values. This method does the same thing as clicking the form's reset button. If a form control (such as a reset button) has a name or id of reset it will mask the form's reset method. It does not reset other attributes in the input, such as disabled. Syntax HTMLFormElement.reset() Example document.getElementById('myform').reset(); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement: reset' in that specification. Living Standard ...
HTMLFormElement: reset event - Web APIs
ple 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 No change HTML 5.2The definition of 'reset' in that specification. Recommendation No change ...
HTMLFormElement.submit() - Web APIs
mit <button> and does not have these differences. If a form control (such as a submit button) has a name or id of submit, this method will mask the form's submit method. <input> with attribute type="submit" will not be submitted with the form when using HTMLFormElement.submit(), but it would be submitted when you do it with original HTML form submit. Syntax HTMLFormElement.submit() Example document.forms["myform"].submit(); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement: submit' in that specification. Living Standard ...
HTMLFormElement: submit event - Web APIs
ent.timeStamp whenever that occurs, then prevents the default action of submitting the form. HTML <form id="form"> <label>Test field: <input type="text"></label> <br><br> <button type="submit">Submit form</button> </form> <p id="log"></p> JavaScript function logSubmit(event) { log.textContent = `Form Submitted! Time stamp: ${event.timeStamp}`; event.preventDefault(); } const form = document.getElementById('form'); const log = document.getElementById('log'); form.addEventListener('submit', logSubmit); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'submit' in that specification. Working Draft No change HTML 5.2The definition of 'submit' in that specification. Recommendation No change ...
HTMLFormElement.target - Web APIs
The target property of the HTMLFormElement interface represents the target of the form's action (i.e., the frame in which to render its output). Syntax string = HTMLFormElement.target HTMLFormElement.target = string Example myForm.target = document.frames[1].name; Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement: target' in that specification. Living Standard ...
HTMLFrameSetElement - Web APIs
andardThe definition of 'HTMLFrameSetElement' in that specification. Living Standard From the HTML5 snapshot, the WindowEventHandlers interface now have a onlanguagechange property. HTML5The definition of 'HTMLFrameSetElement' in that specification. Recommendation Snapshot of a previous HTML Living Standard Frames are now obsolete. Implements WindowEventHandlers. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLBodyElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLBodyElement' in that specification. Obsolete Initial definition. ...
HTMLHRElement - Web APIs
Comment HTML Living StandardThe definition of 'HTMLHRElement' in that specification. Living Standard The color property has been added, as an obsolete property, to increase compatibility with the existing web. HTML5The definition of 'HTMLHRElement' in that specification. Recommendation Following properties are now obsolete: align, noshade, size, and width. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLHRElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLHRElement' in that specification. Obsolete Initial definition. ...
HTMLHeadingElement - Web APIs
er". Methods No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHeadingElement' in that specification. Living Standard HTML5The definition of 'HTMLHeadingElement' in that specification. Recommendation The align property is now obsolete. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLHeadingElement' in that specification. Obsolete No change Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLHeadingElement' in that specification. Obsolete Initial definition ...
HTMLHtmlElement.version - Web APIs
This property has been declared as deprecated by the W3C technical recommendation for HTML 4.01 in favor of use of the DTD for obtaining version information for a document. Returns version information about the document type definition (DTD) of a document. While this property is recognized by Mozilla, the return value for this property is always an empty string. ...
HTMLHyperlinkElementUtils.hash - Web APIs
ash property returns a USVString containing a '#' followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string, "". Syntax string = object.hash; object.hash = string; Examples <a id="myAnchor" href="/docs/HTMLHyperlinkElementUtils.href#Examples">Examples</a> <script> var anchor = document.getElementById("myAnchor"); console.log(anchor.hash); // Returns '#Examples' </script> Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.hash' in that specification. Living Standard Initial definition ...
HTMLHyperlinkElementUtils.host - Web APIs
The HTMLHyperlinkElementUtils.host property is a USVString containing the host, that is the hostname, and then, if the port of the URL is nonempty, a ':', and the port of the URL. ...
HTMLHyperlinkElementUtils.hostname - Web APIs
The HTMLHyperlinkElementUtils.hostname property is a USVString containing the domain of the URL. Syntax string = object.hostname; object.hostname = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org/docs/HTMLHyperlinkElementUtils.hostname"> element be in the document var anchor = document.getElementById("myAnchor"); var result = anchor.hostname; // Returns:'developer.mozilla.org' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.hostname' in that specification. Living Standard Initial definition. ...
HTMLHyperlinkElementUtils.href - Web APIs
The HTMLHyperlinkElementUtils.href property is a stringifier that returns a USVString containing the whole URL, and allows the href to be updated. Syntax string = object.href; object.href = string; Examples // Lets imagine an <a id="myAnchor" href="https://developer.mozilla.org/HTMLHyperlinkElementUtils/href"> element is in the document var anchor = document.getElementById("myAnchor"); var result = anchor.href; // Returns: 'https://developer.mozilla.org/HTMLHyperlinkElementUtils/href' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.href' in that specification. Living Standard Initial definition. ...
HTMLHyperlinkElementUtils.password - Web APIs
HTMLHyperlinkElementUtils.password property is a USVString containing the password specified before the domain name. If it is set without first setting the username property, it silently fails. Syntax string = object.password; object.password = string; Examples // Let's <a id="myAnchor" href="https://anonymous:flabada@developer.mozilla.org/docs/HTMLHyperlinkElementUtils.username"> be in the document var anchor = document.getElementByID("myAnchor"); var result = anchor.password; // Returns:'flabada' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.password' in that specification. Living Standard Initial definition. ...
HTMLHyperlinkElementUtils.pathname - Web APIs
The HTMLHyperlinkElementUtils.pathname property is a USVString containing an initial '/' followed by the path of the URL (or the empty string if there is no path). Syntax string = object.pathname; object.pathname = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org/docs/HTMLHyperlinkElementUtils.pathname"> element be in the document var anchor = document.getElementById("myAnchor"); var result = anchor.pathname; // Returns:'/docs/HTMLHyperlinkElementUtils.pathname' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.pathname' in that specification. Living Standard Initial definition. ...
HTMLHyperlinkElementUtils.port - Web APIs
The HTMLHyperlinkElementUtils.port property is a USVString containing the port number of the URL. If the URL does not contain an explicit port number, it will be set to ''. Syntax string = object.port; object.port = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org:443/docs/HTMLHyperlinkElementUtils.port"> element be in the document var anchor = document.getElementByID("myAnchor"); var result = anchor.port; // Returns:'443' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.port' in that specification. Living Standard Initial definition. ...
HTMLHyperlinkElementUtils.protocol - Web APIs
The HTMLHyperlinkElementUtils.protocol property is a USVString representing the protocol scheme of the URL, including the final ':'. Syntax string = object.protocol; object.protocol = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org/HTMLHyperlinkElementUtils.protocol"> element be in the document var anchor = document.getElementById("myAnchor"); var result = anchor.protocol; // Returns:'https:' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.protocol' in that specification. Living Standard Initial definition. ...
HTMLHyperlinkElementUtils.search - Web APIs
, that is USVString containing a '?' followed by the parameters of the URL. Modern browsers provide URLSearchParams and URL.searchParams to make it easy to parse out the parameters from the querystring. Syntax string = object.search; object.search = string; Examples // Let an <a id="myAnchor" href="https://developer.mozilla.org/docs/HTMLHyperlinkElementUtils.search?q=123"> element be in the document var anchor = document.getElementById("myAnchor"); var queryString = anchor.search; // Returns:'?q=123' // Further parsing: let params = new URLSearchParams(queryString); let q = parseInt(params.get("q")); // is the number 123 Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.search' in that specification. Li...
HTMLHyperlinkElementUtils.username - Web APIs
The HTMLHyperlinkElementUtils.username property is a USVString containing the username specified before the domain name. Syntax string = object.username; object.username = string; Examples // Let's <a id="myAnchor" href="https://anonymous:flabada@developer.mozilla.org/docs/HTMLHyperlinkElementUtils.username"> be in the document var anchor = document.getElementByID("myAnchor"); var result = anchor.username; // Returns:'anonymous' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.username' in that specification. Living Standard Initial definition. ...
HTMLIFrameElement.contentWindow - Web APIs
The contentWindow property returns the Window object of an HTMLIFrameElement. You can use this Window object to access the iframe's document and its internal DOM. This attribute is read-only, but its properties can be manipulated like the global Window object. Example of contentWindow var x = document.getElementsByTagName("iframe")[0].contentWindow; //x = window.frames[0]; x.document.getElementsByTagName("body")[0].style.backgroundColor = "blue"; // this would turn the 1st iframe in document blue. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLIFrameElement: contentWindow' in that specification. Living Standard ...
HTMLIFrameElement.csp - Web APIs
Syntax var csp = HTMLIFrameElement.csp HTMLIFrameElement.csp = csp Value A content security policy. Specifications Specification Status Comment Content Security Policy: Embedded EnforcementThe definition of 'csp' in that specification. Working Draft Initial definition. 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. ...
HTMLIFrameElement.src - Web APIs
The HTMLIFrameElement.src property reflects the HTML referrerpolicy attribute of the <iframe> element defining which referrer is sent when fetching the resource. Syntax refStr = iframeElt.src; iframeElt.src= refStr; Example var iframe = document.createElement("iframe"); iframe.src = "/"; var body = document.getElementsByTagName("body")[0]; body.appendChild(iframe); // Fetch the image using the complete URL as the referrer Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLIFrameElement: src' in that specification. Living Standard 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-c...
srcdoc - Web APIs
The srcdoc property of the HTMLIFrameElement specifies the content of the page. Examples var iframe = document.createElement("iframe"); iframe.srcdoc = `<!DOCTYPE html><p>Hello World!</p>`; document.body.appendChild(iframe); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLIFrameElement: srcdoc' in that specification. Living Standard ...
HTMLImageElement.complete - Web APIs
ally this command wouldn't even be executed if the image hasn't fully loaded, for improved reliability you want to check to ensure this is the case. So the fixRedEyeCommand() function, which is called by the button that triggers red-eye removal, checks the value of the lightbox image's complete property before attempting to do its work. This is demonstrated in the code below. ...
HTMLImageElement.decode() - Web APIs
e. Examples The following example shows how to use the decode() method to control when an image is appended to the DOM. Without a Promise-returning method, you would add the image to the DOM in a load event handler, such as by using the img.onload event handler, and by handling the error in the error event's handler. const img = new Image(); img.src = 'nebula.jpg'; img.decode() .then(() => { document.body.appendChild(img); }) .catch((encodingError) => { // Do something with the error. }) Specifications Specification Status Comment HTML Living StandardThe definition of 'decode()' in that specification. Living Standard Initial definition. ...
HTMLImageElement.height - Web APIs
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 This example may be easier to try out in its own window. Specifications Specification Status Comment HTML Living Stand...
HTMLImageElement.referrerPolicy - Web APIs
f the page, that is roughly the scheme, the host and the port. "unsafe-url" meaning that the referrer will include the origin and the path (but not the fragment, password, or username). This case is unsafe as it can leak path information that has been concealed to third-party by using TLS. Examples var img = new Image(); img.src = 'img/logo.png'; img.referrerPolicy = 'origin'; var div = document.getElementById('divAround'); div.appendChild(img); // Fetch the image using the origin as the referrer Specifications Specification Status Comment Referrer PolicyThe definition of 'referrerPolicy attribute' in that specification. Candidate Recommendation Added the referrerPolicy property. Browser compatibility The compatibility table on this page is ge...
HTMLImageElement.width - Web APIs
ng" 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", updateWidth); window.addEventListener("resize", updateWidth); Result This example may be easier to try out in its own window. Specifications Specification Status Comment HTML Living StandardT...
HTMLInputElement: invalid event - Web APIs
ll 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.1The definition of 'Invali...
HTMLInputElement.labels - Web APIs
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 No change HTML5The definition of 'labels' in that specification. ...
HTMLInputElement.multiple - Web APIs
The HTMLInputElement.multiple property indicates if an input can have more than one value. Firefox currently only supports multiple for <input type="file">. ...
HTMLInputElement: search event - Web APIs
t elapses since the most recent keystroke (with new keystrokes resetting the timeout so the firing of the event is debounced). Current UA implementations of <input type="search"> have an additional control to clear the field. Using this control also fires the search event. In that case the value of the <input> element will be the empty string. Examples // addEventListener version const input = document.querySelector('input[type="search"]'); input.addEventListener('search', () => { console.log("The term searched for was " + input.value); }) // onsearch version const input = document.querySelector('input[type="search"]'); input.onsearch = () => { console.log("The term searched for was " + input.value); }) Specifications This event is not part of any specification. ...
HTMLInputElement.select() - Web APIs
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 onClick="this.select();" value...
HTMLInputElement.setRangeText() - Web APIs
eserve 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 'HTMLInputElement.setSelectionRange()' in that specif...
HTMLInputElement.setSelectionRange() - Web APIs
" "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.setSelectionRange()' in that specification. Rec...
HTMLInputElement.webkitEntries - Web APIs
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 File and Dir...
HTMLIsIndexElement - Web APIs
rm. HTMLIsIndexElement.prompt Is a DOMString representing a text to be prompted for the field. Methods No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML5The definition of 'HTMLIsIndexElement' in that specification. Recommendation Removed. <isindex> must now implement HTMLUnknownElement. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLIsIndexElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLIsIndexElement' in that specification. Obsolete Initial definition. ...
HTMLLIElement - Web APIs
Methods No specific method; inherits properties from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLLIElement' in that specification. Living Standard HTML5The definition of 'HTMLLIElement' in that specification. Recommendation The following property is now obsolete: type. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLLIElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLLIElement' in that specification. Obsolete Initial definition. ...
HTMLLabelElement - Web APIs
t, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLLabelElement' in that specification. Living Standard HTML5The definition of 'HTMLLabelElement' in that specification. Recommendation The property accessKey is now defined on HTMLElement. The following property has been added: control. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLLabelElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLLabelElement' in that specification. Obsolete Initial definition. ...
HTMLLegendElement - Web APIs
andardThe definition of 'HTMLLegendElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLLegendElement' in that specification. Recommendation HTML5The definition of 'HTMLLegendElement' in that specification. Recommendation The property accessKey is now defined on HTMLElement. The following property is now obsolete: align. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLLegendElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLLegendElement' in that specification. Obsolete Initial definition. ...
HTMLLinkElement.referrerPolicy - Web APIs
The HTMLLinkElement.referrerPolicy property reflect the HTML referrerpolicy attribute of the <link> element defining which referrer is sent when fetching the resource. See the HTTP Referrer-Policy header for details. Syntax DOMString HTMLLinkElement.referrerPolicy Example var links = document.getElementsByTagName("link"); links[0].referrerPolicy; // "no-referrer" Specifications Specification Status Comment Referrer PolicyThe definition of 'referrerPolicy attribute' in that specification. Candidate Recommendation ...
HTMLMapElement - Web APIs
iated to this <map>. Methods No specific method; inherits methods from its parent, HTMLElement . Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMapElement' in that specification. Living Standard HTML5The definition of 'HTMLMapElement' in that specification. Recommendation Adds the images property. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLAreaElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLAreaElement' in that specification. Obsolete Initial definition. ...
HTMLMediaElement.audioTracks - Web APIs
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 No change from HTML5 HTML5The definition of 'HTMLMediaElement.audioTracks' in tha...
HTMLMediaElement.autoplay - Web APIs
video from playing without permission or in the background. Do not rely on autoplay actually starting playback and instead use play event. Examples ... <video id="video" controls> <source src="https://player.vimeo.com/external/250688977.sd.mp4?s=d14b1f1a971dde13c79d6e436b88a6a928dfe26b&profile_id=165"> </video> *** Disable autoplay (recommended) *** false is the default value document.querySelector('#video').autoplay = false; Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.autoplay' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLMediaElement.autoplay' in that specification. Recommendation Initial definition. ...
HTMLMediaElement.buffered - Web APIs
ce that the browser has buffered (if any) at the moment the buffered property is accessed. Note: This feature is not available in Web Workers. Syntax var timeRange = audioObject.buffered Value A TimeRanges object. This object is normalized, which means that ranges are ordered, don't overlap, aren't empty, and don't touch (adjacent ranges are folded into one bigger range). Example var obj = document.createElement('video'); console.log(obj.buffered); // TimeRanges { length: 0 } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.buffered' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLMediaElement.buffered' in that specification. Recommendation Initial defin...
HTMLMediaElement.canPlayType() - Web APIs
ing will be one of the following values: probably Media of the type indicated by the mediaType parameter is probably playable on this device. maybe Not enough information is available to determine for sure whether or not the media will play until playback is actually attempted. "" (empty string) Media of the given type definitely can't be played on the current device. Example var obj = document.createElement('video'); console.log(obj.canPlayType('video/mp4')); // "maybe" Specifications Specification Status Comment HTML Living StandardThe definition of 'canplaytype' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.canplaytype' in that specification. Recommendation Initial definition. ...
HTMLMediaElement.captureStream() - Web APIs
other media processing code, or as a source for WebRTC. Example In this example, an event handler is established so that clicking a button starts capturing the contents of a media element with the ID "playback" into a MediaStream. The stream can then be used for other purposes--like a source for streaming over WebRTC, to allow sharing prerecorded videos with another person during a video call. document.querySelector('.playAndRecord').addEventListener('click', function() { var playbackElement = document.getElementById("playback"); var captureStream = playbackElement.captureStream(); playbackElement.play(); }); See Recording a media element for a longer and more intricate example and explanation. Specifications Specification Status Comment Media Capture from DOM ...
HTMLMediaElement.controls - Web APIs
The HTMLMediaElement.controls property reflects the controls HTML attribute, which controls whether user interface controls for playing the media item will be displayed. Syntax var ctrls = video.controls; audio.controls = true; Value A Boolean. A value of true means controls will be displayed. Example var obj = document.createElement('video'); obj.controls = true; Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.controls' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLMediaElement.controls' in that specification. Recommendation Initial definition. ...
HTMLMediaElement.currentSrc - Web APIs
orkState property is EMPTY. Syntax var mediaUrl = audioObject.currentSrc; Value A DOMString object containing the absolute URL of the chosen media source; this may be an empty string if networkState is EMPTY; otherwise, it will be one of the resources listed by the HTMLSourceElement contained within the media element, or the value or src if no <source> element is provided. Example var obj = document.createElement('video'); console.log(obj.currentSrc); // "" Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.currentSrc' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLMediaElement.currentSrc' in that specification. Recommendation Initial definition. ...
HTMLMediaElement.currentTime - Web APIs
ithout a known duration--such as media being streamed live--it's possible that the browser may not be able to obtain parts of the media that have expired from the media buffer. Also, media whose timeline doesn't begin at 0 seconds cannot be seeked to a time before its timeline's earliest time. The length of the media in seconds can be determined using the duration property. Example var video = document.createElement('video'); console.log(video.currentTime); Usage notes Reduced time precision To offer protection against timing attacks and fingerprinting, browsers may round or otherwise adjust the value returned by currentTime. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.currentTime' in that specification. Li...
HTMLMediaElement.defaultMuted - Web APIs
flects the muted HTML attribute, which indicates whether the media element's audio output should be muted by default. This property has no dynamic effect. To mute and unmute the audio output, use the muted property. Syntax var dMuted = video.defaultMuted; audio.defaultMuted = true; Value A Boolean. A value of true means that the audio output will be muted by default. Example var videoEle = document.createElement('video'); videoEle.defaultMuted = true; console.log(videoEle.outerHTML); // <video muted=""></video> Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.defaultMuted' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLMediaElement.defaultMuted' in that speci...
HTMLMediaElement.defaultPlaybackRate - Web APIs
ediaElement.defaultPlaybackRate property indicates the default playback rate for the media. Syntax var dSpeed = video.defaultPlaybackRate; audio.defaultPlaybackRate = 1.0; Value A double. 1.0 is "normal speed," values lower than 1.0 make the media play slower than normal, higher values make it play faster. The value 0.0 is invalid and throws a NOT_SUPPORTED_ERR exception. Example var obj = document.createElement('video'); console.log(obj.defaultPlaybackRate); // 1 Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.defaultPlaybackRate' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLMediaElement.defaultPlaybackRate' in that specification. Recommendation Ini...
HTMLMediaElement.disableRemotePlayback - Web APIs
The HTMLMediaElement.disableRemotePlayback property determines whether the media element is allowed to have a remote playback UI. Syntax var remotePlaybackDisabled = element.disableRemotePlayback; Value A Boolean indicating whether the media element may have a remote playback UI. (false means "not disabled", which means "enabled") Example var obj = document.createElement('audio'); obj.disableRemotePlayback = true; Specifications Specification Status Comment Remote Playback APIThe definition of 'disableRemotePlayback' in that specification. Candidate Recommendation Initial definition. ...
HTMLMediaElement.duration - Web APIs
dicates the length of the element's media in seconds. Syntax myDuration = htmlMediaElement.duration Value A double-precision floating-point value indicating the duration of the media in seconds. If no media data is available, the value NaN is returned. If the element's media doesn't have a known duration--such as for live media streams--the value of duration is +Infinity. Examples var obj = document.createElement('video'); console.log(obj.duration); // NaN Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.duration' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.duration' in that specification. Recommendation Initial definition. ...
HTMLMediaElement: emptied event - Web APIs
Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onemptied Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's emptied event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('emptied', (event) => { console.log('Uh oh. The media is empty. Did you call load()?'); }); Using the onemptied event handler property: const video = document.querySelector('video'); video.onemptied = (event) => { console.log('Uh oh. The media is empty. Did you call load()?'); }; Specifications Specification Status HTML...
HTMLMediaElement.ended - Web APIs
The HTMLMediaElement.ended indicates whether the media element has ended playback. Syntax var isEnded = HTMLMediaElement.ended Value A Boolean which is true if the media contained in the element has finished playing. If the source of the media is a MediaStream, this value is true if the value of the stream's active property is false. Example var obj = document.createElement('video'); console.log(obj.ended); // false Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.ended' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.ended' in that specification. Recommendation ...
HTMLMediaElement.error - Web APIs
can determine details about what happened by examining this object. Syntax var myError = HTMLMediaElement.error; Value A MediaError object describing the most recent error to occur on the media element or null if no errors have occurred. Example This example establishes a video element and adds an error handler to it; the error handler simply logs the details to console. var videoElement = document.createElement('video'); videoElement.onerror = function() { console.log("Error " + videoElement.error.code + "; details: " + videoElement.error.message); } videoElement.src = "https://example.com/bogusvideo.mp4"; Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.error' in that specification. Living Standard ...
HTMLMediaElement: error event - Web APIs
The error event is fired when the resource could not be loaded due to an error (for example, a network connectivity problem). ...
HTMLMediaElement.fastSeek() - Web APIs
The HTMLMediaElement.fastSeek() method quickly seeks the media to the new time with precision tradeoff. Note: If you need to seek with precision, you should set HTMLMediaElement.currentTime instead. Syntax HTMLMediaElement.fastSeek(time); Parameters time A double. Return value None. Example This example quickly seeks to 20-second position of the video element. let myVideo = document.getElementById("myVideoElement"); myVideo.fastSeek(20); Specifications Specification Status Comment HTML Living StandardThe definition of 'fastSeek()' in that specification. Living Standard Initial definition; living specification. ...
HTMLMediaElement.load() - Web APIs
. If resetting the playback position to the beginning of the media actually changes the playback position (that is, it was not already at the beginning), a timeupdate event is sent. Once media has been selected and loading is ready to begin, the loadstart event is delivered. From this point onward, events are sent just like any media load. Example This example finds a <video> element in the document and resets it by calling load(). var mediaElem = document.querySelector("video"); mediaElem.load(); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.load()' in that specification. Living Standard Initial definition. HTML5The definition of 'HTMLMediaElement.load()' in that specification. Recommendation...
HTMLMediaElement.loop - Web APIs
The HTMLMediaElement.loop property reflects the loop HTML attribute, which controls whether the media element should start over when it reaches the end. Syntax var loop = video.loop; audio.loop = true; Value A Boolean. Example var obj = document.createElement('video'); obj.loop = true; // true Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.loop' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.loop' in that specification. Recommendation ...
HTMLMediaElement.muted - Web APIs
The HTMLMediaElement.muted indicates whether the media element muted. Syntax var isMuted = audioOrVideo.muted audio.muted = true; Value A Boolean. true means muted and false means not muted. Example var obj = document.createElement('video'); console.log(obj.muted); // false Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.muted' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.muted' in that specification. Recommendation ...
HTMLMediaElement.networkState - Web APIs
ot using the network. NETWORK_LOADING 2 The browser is downloading HTMLMediaElement data. NETWORK_NO_SOURCE 3 No HTMLMediaElement src found. Examples This example will listen for the audio element to begin playing and then check if it is still loading data. <audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> var obj = document.getElementById('example'); obj.addEventListener('playing', function() { if (obj.networkState === 2) { // Still loading... } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.networkState' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.networkState' in that ...
HTMLMediaElement: pause event - Web APIs
Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onpause Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's pause event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('pause', (event) => { console.log('The Boolean paused property is now true. Either the ' + 'pause() method was called or the autoplay attribute was toggled.'); }); Using the onpause event handler property: const video = document.querySelector('video'); video.onpause = (event) => { console.log('The Boolean paused property is now true. Either...
HTMLMediaElement.paused - Web APIs
The read-only HTMLMediaElement.paused property tells whether the media element is paused. Syntax var isPaused = audioOrVideo.paused Value A Boolean. true is paused and false is not paused. Example var obj = document.createElement('video'); console.log(obj.paused); // true Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.paused' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.paused' in that specification. Recommendation ...
HTMLMediaElement: play event - Web APIs
Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onplay Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's play event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('play', (event) => { console.log('The Boolean paused property is now false. Either the ' + 'play() method was called or the autoplay attribute was toggled.'); }); Using the onplay event handler property: const video = document.querySelector('video'); video.onplay = (event) => { console.log('The Boolean paused property is now false. Either t...
HTMLMediaElement.playbackRate - Web APIs
d by default and is the same for every speed. Some browsers implement the non-standard HTMLMediaElement.preservesPitch property to control this. Syntax // video video.playbackRate = 1.5; // audio audio.playbackRate = 1.0; Value A double. 1.0 is "normal speed," values lower than 1.0 make the media play slower than normal, higher values make it play faster. (Default: 1.0) Example var obj = document.createElement('video'); console.log(obj.playbackRate); // Expected Output: 1 Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.playbackRate' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.playbackRate' in that specification. Recommendation ...
HTMLMediaElement.readyState - Web APIs
te is high enough--that the media can be played through to the end without interruption. Examples This example will listen for audio data to be loaded for the element `example`. It will then check if at least the current playback position has been loaded. If it has, the audio will play. <audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> var obj = document.getElementById('example'); obj.addEventListener('loadeddata', function() { if(obj.readyState >= 2) { obj.play(); } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.readyState' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.readyState' in that specificati...
HTMLMediaElement.seekable - Web APIs
The seekable read-only property of the HTMLMediaElement returns a TimeRanges object that contains the time ranges that the user is able to seek to, if any. Syntax var seekable = audioOrVideo.seekable; Value A TimeRanges object. Examples var video = document.querySelector("video"); var timeRangesObject = video.seekable; var timeRanges = []; //Go through the object and output an array for (let count = 0; count < timeRangesObject.length; count ++) { timeRanges.push([timeRangesObject.start(count), timeRangesObject.end(count)]); } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLMediaElement' in that specificat...
HTMLMediaElement.setSinkId() - Web APIs
hat resolves to undefined. Parameters sinkId The MediaDeviceInfo.deviceId of the audio output device. Exceptions Exception Explanation DOMException No permission to use the requested device Examples const devices = await navigator.mediaDevices.enumerateDevices(); const audioDevices = devices.filter(device => device.kind === 'audiooutput'); const audio = document.createElement('audio'); await audio.setSinkId(audioDevices[0].deviceId); console.log('Audio is being played on ' + audio.sinkId); Specifications Specification Status Comment Audio Output Devices APIThe definition of 'sinkId' in that specification. Candidate Recommendation Initial definition. Older versions of this spec were called "Media Capture Output". ...
HTMLMediaElement.src - Web APIs
attribute, which also takes into account selection of a best or preferred media resource from a list provided in an HTMLSourceElement (which represents a <source> element). Syntax var mediaUrl = HTMLMediaElement.src; Value A USVString object containing the URL of a media resource to use in the element; this property reflects the value of the HTML element's src attribute. Example var obj = document.createElement('video'); console.log(obj.src); // "" Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.src' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLMediaElement.src' in that specification. Recommendation Initial definition. ...
HTMLMedia​Element​.textTracks - Web APIs
adata" src="keyStage1.vtt" srclang="en" label="Key Stage 1"> <track kind="metadata" src="keyStage2.vtt" srclang="en" label="Key Stage 2"> <track kind="metadata" src="keyStage3.vtt" srclang="en" label="Key Stage 3"> </video> The HTMLMediaElement.textTracks returns a textTracksList thru which we can iterate. Here we print all the properties of each English track to the console. var tracks = document.querySelector('video').textTracks; for (var i = 0, L = tracks.length; i < L; i++) { /* tracks.length == 10 */ if (tracks[i].language == 'en') { console.dir(tracks[i]); } } Properties & Methods properties length Returns the number of text tracks in TextTrackList object. methods getTrackById() The getTrackById(id) method returns the first TextTrack in the TextTrackList o...
HTMLMediaElement: timeupdate event - Web APIs
tion None Event handler property GlobalEventHandlers.ontimeupdate Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's timeupdate event, then post a message when that event handler has reacted to the event firing. Remember, the event frequency is dependant on the system load. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('timeupdate', (event) => { console.log('The currentTime attribute has been updated. Again.'); }); Using the ontimeupdate event handler property: const video = document.querySelector('video'); video.ontimeupdate = (event) => { console.log('The currentTime attribute has been updated. Again.'); }; Specifications Specification Statu...
HTMLMediaElement.volume - Web APIs
The HTMLMediaElement.volume property sets the volume at which the media will be played. Syntax var volume = video.volume; //1 Value A double values must fall between 0 and 1, where 0 is effectively muted and 1 is the loudest possible value. Example var obj = document.createElement('audio'); console.log(obj.volume); // 1 obj.volume = 0.75; Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.volume' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.volume' in that specification. Recommendation ...
HTMLMeterElement.labels - Web APIs
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 Standard No change HTML5The definition of 'labels' in that specification. ...
HTMLModElement - Web APIs
e HTML attribute, containing a date-and-time string representing a timestamp for the change. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLAnchorElement' in that specification. Living Standard No change from HTML5. HTML5The definition of 'HTMLAnchorElement' in that specification. Recommendation No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLModElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLModElement' in that specification. Obsolete Initial definition.
HTMLOListElement - Web APIs
modern pages. Methods No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLOListElement' in that specification. Living Standard HTML5The definition of 'HTMLOListElement' in that specification. Recommendation Added the reversed property. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLOListElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLOListElement' in that specification. Obsolete Initial definition. ...
HTMLObjectElement.setCustomValidity - Web APIs
ers error The message to use for validity errors. Return value undefined Exceptions None. Examples In this example, we pass the ID of an input element, and set different error messages depending on whether the value is missing, too low or too high. Additionally you must call the reportValidity method on the same element or nothing will happen. ...
HTMLObjectElement.typeMustMatch - Web APIs
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. ...
HTMLOptGroupElement - Web APIs
enting the label for the group. Methods No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLOptgroupElement' in that specification. Living Standard HTML5The definition of 'HTMLOptGroupElement' in that specification. Recommendation No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLOptGroupElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLOptGroupElement' in that specification. Obsolete Initial d...
HTMLOptionsCollection - Web APIs
This object is returned only by the options property of select. ...
HTMLOrForeignElement.dataset - Web APIs
es When an attribute is set, its value is always converted into a string. For example: null is converted into the string "null". To remove an attribute, you can use the delete operator. Syntax const dataAttrMap = element.dataset Value A DOMStringMap. ...
HTMLOutputElement.labels - Web APIs
d 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 Standard No change HTML5The definition of 'labels' in that specification. ...
HTMLParagraphElement - Web APIs
o specific methods, inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLParagraphElement' in that specification. Living Standard HTML5The definition of 'HTMLParagraphElement' in that specification. Recommendation The following property is now obsolete: align. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLParagraphElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLParagraphElement' in that specification. Obsolete Initial definition. ...
HTMLParamElement - Web APIs
c methods, inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLParamElement' in that specification. Living Standard HTML5The definition of 'HTMLParamElement' in that specification. Recommendation The following properties are now obsolete: type, and valueType. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLParamElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLParamElement' in that specification. Obsolete Initial definition. ...
HTMLPreElement - Web APIs
Methods No specific method; inherits properties from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLPreElement' in that specification. Living Standard HTML5The definition of 'HTMLLIElement' in that specification. Recommendation The following property is now obsolete: width. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLPreElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLPreElement' in that specification. Obsolete Initial definition. ...
HTMLProgressElement.labels - Web APIs
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. Living Standard No change HTML5The definition of 'labels' in that specificatio...
HTMLQuoteElement - Web APIs
L for the source of the quotation. Methods No specific method; inherits properties from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLQuoteElement' in that specification. Living Standard HTML5The definition of 'HTMLQuoteElement' in that specification. Recommendation No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLQuoteElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLQuoteElement' in that specification. Obsolete Initial definit...
HTMLSelectElement.form - Web APIs
it" 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'); var vist = form_element.style; if (vist.display=='' || vist.display=='none') { vist.display = 'block'; } else { vist.display = 'none'; } </script> Specifications Specification Status Comment HTML Living StandardThe definition of 'form' in that specification. Living Standard HTML5The definition of 'HTMLSelectElement'...
HTMLSelectElement.item() - Web APIs
). 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 specification. Recommendation Initial definition, snapshot of HTML Livi...
HTMLSelectElement.labels - Web APIs
; 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 Standard No change HTML5The definition of 'labels' in that specification. ...
HTMLSelectElement.namedItem() - Web APIs
ing, 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 that specification.
HTMLSelectElement.options - Web APIs
t> 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 Standard No change HTML5The definition of 'options' in that specification. ...
HTMLSelectElement.type - Web APIs
r this isn't a SELECT element) } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLSelectElement' in that specification. Living Standard No change from HTML5, the latest snapshot. HTML5The definition of 'HTMLSelectElement' in that specification. Recommendation Is a snapshot of HTML Living Standard. No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLSelectElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLSelectElement' in that specification. Obsolete Initial defin...
HTMLStyleElement.scoped - Web APIs
The HTMLStyleElement.scoped property is a Boolean value indicating if the element applies to the whole document (false) or only to the parent's sub-tree (true). By default it contains the value of the scoped content attribute. Syntax value = style.scoped; style.scoped = true; ...
HTMLTableColElement - Web APIs
thod; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableColElement' in that specification. Living Standard No change from HTML5. HTML5The definition of 'HTMLTableColElement' in that specification. Recommendation The span property is now an unsigned long. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLTableColElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLTableColElement' in that specification. Obsolete Initial definition. ...
HTMLTableElement.align - Web APIs
The HTMLTableElement.align property represents the alignment of the table. Syntax HTMLTableElement.align = alignment; var alignment = HTMLTableElement.align; Parameters alignment DOMString with one of the following values: left center right Example // Set the alignmnet of a table var t = document.getElementById('TableA'); t.align = 'center'; Specification W3C DOM 2 HTML Specification HTMLTableElement .align. ...
HTMLTableElement.bgColor - Web APIs
The bgColor attribute is deprecated in HTML 4.01. ...
HTMLTableElement.border - Web APIs
The HTMLTableElement.border property represents the border width of the <table> element. Syntax HTMLTableElement.border = border; var border = HTMLTableElement.border; border is a string representing the width of the border in pixels. Example // Set the width of a table border to 2 pixels var t = document.getElementById('TableA'); t.border = '2'; Specification W3C DOM 2 HTML Specification HTMLTableElement .border. This attribute is deprecated in HTML 4.0. ...
HTMLTableElement.caption - Web APIs
ent.caption; Example if (table.caption) { // Do something with the caption } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement.caption' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLTableElement.caption' in that specification. Recommendation No change from Document Object Model (DOM) Level 2 HTML Specification Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLTableElement.caption' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLTableElement.caption' in that specification. Obsolete I...
HTMLTableElement.cellPadding - Web APIs
The HTMLTableElement.cellPadding property represents the padding around the individual cells of the table. Syntax HTMLTableElement.cellPadding = padding; var padding = HTMLTableElement.cellPadding; padding is either a number of pixels (e.g. "10") or a percentage value (e.g. "10%"). Example // Set cell padding to 10 pixels let t = document.getElementById('TableA'); t.cellPadding = '10'; Specification W3C DOM 2 HTML Specification HTMLTableElement .cellPadding. ...
HTMLTableElement.cellSpacing - Web APIs
ents representing a table's cells. Any two cells are separated by the sum of the cellSpacing of each of the two cells. Syntax HTMLTableElement.cellSpacing = spacing; var spacing = HTMLTableElement.cellSpacing; Value A DOMString which is either a number of pixels (such as "10") or a percentage value (like "10%"). Example This example sets cell spacing for a given table to 10 pixels. var t = document.getElementById('TableA'); t.cellSpacing = "10"; Specification W3C DOM 2 HTML Specification HTMLTableElement .cellSpacing. ...
HTMLTableElement.createCaption() - Web APIs
The HTMLTableElement.createCaption() method returns the <caption> element associated with a given <table>. If no <caption> element exists on the table, this method 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. 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.
HTMLTableElement.createTFoot() - Web APIs
The HTMLTableElement.createTFoot() method returns the <tfoot> element associated with a given <table>. If no footer exists in the table, this methods creates it, and then returns it. Note: If no footer exists, createTFoot() inserts a new footer directly into the table. The footer does not need to be added separately as would be the case if Document.createElement() had been used to create the new <tfoot> element. Syntax HTMLTableSectionElement = table.createTFoot(); Return value HTMLTableSectionElement Example let myfoot = mytable.createTFoot(); // Now this should be true: myfoot == mytable.tFoot Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement: createTFoot' in that specification. Living Standard ...
HTMLTableElement.createTHead() - Web APIs
The HTMLTableElement.createTHead() method returns the <thead> element associated with a given <table>. If no header exists in the table, this method creates it, and then returns it. Note: If no header exists, createTHead() inserts a new header directly into the table. The header does not need to be added separately as would be the case if Document.createElement() had been used to create the new <thead> element. Syntax HTMLTableSectionElement = table.createTHead(); Return value HTMLTableSectionElement Example let myhead = mytable.createTHead(); // Now this should be true: myhead == mytable.tHead Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement: createTHead' in that specification. Living Standard ...
HTMLTableElement.deleteCaption() - Web APIs
en <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.deleteRow() - Web APIs
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 ...
HTMLTableElement.deleteTFoot() - Web APIs
eElement.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.frame - Web APIs
frame; Parameters frameSides is a string whose value is one of the following values: void No sides. ...
HTMLTableElement.rules - Web APIs
rty indicates which cell borders to render in the table. ...
HTMLTableElement.tFoot - Web APIs
= HTMLTableSectionElementObject Example if (table.tFoot == my_foot) { // ... } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement.tFoot' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLTableElement.tFoot' in that specification. Recommendation No change from Document Object Model (DOM) Level 2 HTML Specification Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLTableElement.tFoot' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLTableElement.tFoot' in that specification. Obsolete Initi...
HTMLTableElement.tHead - Web APIs
s a HTMLTableSectionElement. Example if (table.tHead == my_head_el) { // ... } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement.tHead' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLTableElement.tHead' in that specification. Recommendation No change from Document Object Model (DOM) Level 2 HTML Specification Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLTableElement.tHead' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLTableElement.tHead' in that specification. Obsolete Initi...
HTMLTableRowElement - Web APIs
urns a reference to a HTMLTableCellElement [en-US]. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableRowElement' in that specification. Living Standard HTML5The definition of 'HTMLTableRowElement' in that specification. Recommendation The parameter of insertCell is now optional and default to -1. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLTableRowElement' in that specification. Obsolete The cells, rowIndex, and selectionRowIndex properties are now read-only. The methods insertCell and deleteCell can raise exceptions. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLTableRowElement' in that specification. Obsolete Ini...
HTMLTableSectionElement - Web APIs
n -1, it raises a DOMException with the IndexSizeError value. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableSectionElement' in that specification. Living Standard HTML5The definition of 'HTMLTableSectionElement' in that specification. Recommendation The parameter of insertCell is now optional. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLTableSectionElement' in that specification. Obsolete The methods insertRow and deleteRow can raise exceptions. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLTableSectionElement' in that specification. Obsolete Initial definition. ...
HTMLTemplateElement.content - Web APIs
Syntax var documentFragment = templateElement.content Example var templateElement = document.querySelector("#foo"); var documentFragment = templateElement.content.cloneNode(true); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTemplateElement interface' in that specification. ...
HTMLTemplateElement - Web APIs
stroke="#D4DDE4" stroke-width="2px" /><text x="396" y="94" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLTemplateElement</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties This interface inherits the properties of HTMLElement. content Read only A read-only DocumentFragment which contains the DOM subtree representing the <template> element's template contents. Methods This interface inherits the methods of HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTemplateElement interface' in that specification. Living Standard HTML5The definition of 'HTMLTemplateElement i...
HTMLTextAreaElement.labels - Web APIs
tarea> 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. Living Standard No change HTML5The definition of 'labels' in that specificatio...
HTMLTimeElement.dateTime - Web APIs
Living Standard No change from HTML 5.1. HTML 5.1The definition of 'HTMLTimeElement' in that specification. Recommendation No change from HTML5. HTML5The definition of '...
HTMLUListElement - Web APIs
No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLUListElement' in that specification. Living Standard HTML5The definition of 'HTMLUListElement' in that specification. Recommendation The compact and type properties have been obsoleted. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLUListElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLUListElement' in that specification. Obsolete Initial definition. ...
HTMLVideoElement.getVideoPlaybackQuality() - Web APIs
aybackQuality(); Return value A VideoPlaybackQuality object providing information about the video element's current playback quality. Example This example updates an element to indicate the total number of video frames that have elapsed so far in the playback process. This value includes any dropped or corrupted frames, so it's not the same as "total number of frames played." var videoElem = document.getElementById("my_vid"); var counterElem = document.getElementById("counter"); var quality = videoElem.getVideoPlaybackQuality(); counterElem.innerText = quality.totalVideoFrames; Specifications Specification Status Comment Media Playback QualityThe definition of 'HTMLVideoElement.getVideoPlaybackQuality()' in that specification. Editor's Draft Initial definitio...
HTMLVideoElement.msInsertVideoEffect() - Web APIs
tableClassId: DOMString, effectRequired: boolean, config); Parameters activatableClassId A DOMString defining the video effects class. ...
HTMLVideoElement.msZoom - Web APIs
f the video is trimmed. ...
HTMLVideoElement.videoHeight - Web APIs
es and the element's readyState isn't HAVE_NOTHING, a resize event will be sent to the <video> element. This can happen when the element switches from displaying the poster frame to displaying video content, or when the displayed video track changes. Example This example creates a handler for the resize event that resizes the <video> element to match the intrinsic size of its contents. let v = document.getElementById("myVideo"); v.addEventListener("resize", ev => { let w = v.videoWidth; let h = v.videoHeight; if (w && h) { v.style.width = w; v.style.height = h; } }, false); Note that this only applies the change if both the videoWidth and the videoHeight are non-zero. This avoids applying invalid changes when there's no true information available yet for dimensions. Specifi...
HTMLVideoElement.videoWidth - Web APIs
es and the element's readyState isn't HAVE_NOTHING, a resize event will be sent to the <video> element. This can happen when the element switches from displaying the poster frame to displaying video content, or when the displayed video track changes. Example This example creates a handler for the resize event that resizes the <video> element to match the intrinsic size of its contents. let v = document.getElementById("myVideo"); v.addEventListener("resize", ev => { let w = v.videoWidth; let h = v.videoHeight; if (w && h) { v.style.width = w; v.style.height = h; } }, false); Note that this only applies the change if both the videoWidth and the videoHeight are non-zero. This avoids applying invalid changes when there's no true information available yet for dimensions. Specifi...
In depth: Microtasks and the JavaScript runtime environment - Web APIs
is is frequently referred to as a "local context." Using the ill-advised eval() function also creates a new execution context. Each context is, in essence, a level of scope within your code. As one of these code segments begins execution, a new context is constructed in which to run it; that context is then destroyed when the code exits. ...
File drag and drop - Web APIs
The main steps to drag and drop are to define a drop zone (i.e. a target element for the file drop) and to define event handlers for the drop and dragover events. These steps are described below, including example code snippets. The full source code is available in MDN's drag-and-drop repository (pull requests and/or issues are welcome). Note: HTML drag and drop defines two different APIs to support dragging and dropping files. ...
HashChangeEvent - Web APIs
EventListener('hashchange', locationHashChanged); Polyfill There are several fallback scripts listed on the Modernizr GitHub page. Basically, those scripts check the location.hash at a regular interval. Here is a version that allows only one handler to be bound to the onhashchange property: ;(function(window) { // Exit if the browser implements that event if ( "onhashchange" in window.document.body ) { return; } var location = window.location, oldURL = location.href, oldHash = location.hash; // Check the location hash on a 100ms interval setInterval(function() { var newURL = location.href, newHash = location.hash; // If the hash has changed and a handler has been bound... if ( newHash != oldHash && typeof window.onhashchange === "function" ) { ...
History.back() - Web APIs
Web › API › History › back
tory.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. Brows...
History.forward() - Web APIs
Web › API › History › forward
ne 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. Browser ...
History API - Web APIs
ation of the browser session history (that is, the pages visited in the tab or frame that the current page is loaded in). Examples The following example assigns a listener to the onpopstate property. And then illustrates some of the methods of the history object to add, replace, and move within the browser history for the current tab. ...
IDBCursor.advance() - Web APIs
Web › API › IDBCursor › advance
e.foo. ...
IDBCursor.continue() - Web APIs
object using cursor.value.foo. For a complete working example, see our IDBCursor example (view example live.) function displayData() { var transaction = db.transaction(['rushAlbumList'], "readonly"); var objectStore = transaction.objectStore('rushAlbumList'); objectStore.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year; list.appendChild(listItem); cursor.continue(); } else { console.log('Entries all displayed.'); } }; }; Specifications Specification Status Comment Indexed Database API 2.0The definition of 'continue()' in that specification. Recommendati...
IDBCursor.delete() - Web APIs
Web › API › IDBCursor › delete
objectStore.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { if(cursor.value.albumTitle === 'Grace under pressure') { var request = cursor.delete(); request.onsuccess = function() { console.log('Deleted that mediocre album from 1984. ...
IDBCursor.direction - Web APIs
a complete working example, see our IDBCursor example (view example live.) function backwards() { list.innerHTML = ''; var transaction = db.transaction(['rushAlbumList'], 'readonly'); var objectStore = transaction.objectStore('rushAlbumList'); objectStore.openCursor(null,'prev').onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = '<strong>' + cursor.value.albumTitle + '</strong>, ' + cursor.value.year; list.appendChild(listItem); console.log(cursor.direction); cursor.continue(); } else { console.log('Entries displayed backwards.'); } }; }; Specifications Specification Status Comment Indexed Database A...
IDBCursor.key - Web APIs
Web › API › IDBCursor › key
object using cursor.value.foo. ...
IDBCursor.primaryKey - Web APIs
object using cursor.value.foo. ...
IDBCursor.request - Web APIs
Web › API › IDBCursor › request
t request object the cursor originated from. ...
IDBCursor.source - Web APIs
Web › API › IDBCursor › source
object using cursor.value.foo. ...
IDBCursor.update() - Web APIs
Web › API › IDBCursor › update
R...
IDBCursor - Web APIs
Web › API › IDBCursor
object using cursor.value.foo. For a complete working example, see our IDBCursor example (view example live.) function displayData() { var transaction = db.transaction(['rushAlbumList'], "readonly"); var objectStore = transaction.objectStore('rushAlbumList'); objectStore.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year; list.appendChild(listItem); cursor.continue(); } else { console.log('Entries all displayed.'); } }; } Specifications Specification Status Comment Indexed Database API 2.0The definition of 'cursor' in that specification. Recommendation Ini...
IDBCursorWithValue.value - Web APIs
object using cursor.value.foo. ...
IDBCursorWithValue - Web APIs
object using cursor.value.foo. For a complete working example, see our IDBCursor example (view example live.) function displayData() { var transaction = db.transaction(['rushAlbumList'], "readonly"); var objectStore = transaction.objectStore('rushAlbumList'); objectStore.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year; list.appendChild(listItem); cursor.continue(); } else { console.log('Entries all displayed.'); } }; }; Specifications Specification Status Comment Indexed Database API 2.0The definition of 'IDBCursorWithValue' in that specification. Recommen...
IDBFactory.open() - Web APIs
Web › API › IDBFactory › open
or a negative number or not a number. Example Example of calling open with the current specification's version parameter: var request = window.indexedDB.open("toDoList", 4); In the following code snippet, we make a request to open a database, and include handlers for the success and error cases. For a full working example, see our To-do Notifications app (view example live.) var note = document.querySelector("ul"); // In the following line, you should include the prefixes // of implementations you want to test. window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; // DON'T use "var indexedDB = ..." if you're not in a function. // Moreover, you may need references to some window.IDB* objects: window.IDBTransaction = window.IDBTransac...
IDBIndex.count() - Web APIs
Web › API › IDBIndex › count
.transaction(['contactsList'], 'readonly'); var objectStore = transaction.objectStore('contactsList'); var myIndex = objectStore.index('lName'); var countRequest = myIndex.count(); countRequest.onsuccess = function() { console.log(countRequest.result); } myIndex.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lName + '</td>' + '<td>' + cursor.value.fName + '</td>' + '<td>' + cursor.value.jTitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + curso...
IDBIndex.get() - Web APIs
Web › API › IDBIndex › get
.transaction(['contactsList'], 'readonly'); var objectStore = transaction.objectStore('contactsList'); var myIndex = objectStore.index('lName'); var getRequest = myIndex.get('Bungle'); getRequest.onsuccess = function() { console.log(getRequest.result); } myIndex.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lName + '</td>' + '<td>' + cursor.value.fName + '</td>' + '<td>' + cursor.value.jTitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + curso...
IDBIndex.getKey() - Web APIs
Web › API › IDBIndex › getKey
(['contactsList'], 'readonly'); var objectStore = transaction.objectStore('contactsList'); var myIndex = objectStore.index('lName'); var getKeyRequest = myIndex.getKey('Bungle'); getKeyRequest.onsuccess = function() { console.log(getKeyRequest.result); } myIndex.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lName + '</td>' + '<td>' + cursor.value.fName + '</td>' + '<td>' + cursor.value.jTitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + curso...
IDBIndex.isAutoLocale - Web APIs
function displayDataByIndex() { tableEntry.innerHTML = ''; var transaction = db.transaction(['contactsList'], 'readonly'); var objectStore = transaction.objectStore('contactsList'); var myIndex = objectStore.index('lName'); console.log(myIndex.isAutoLocale); myIndex.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lName + '</td>' + '<td>' + cursor.value.fName + '</td>' + '<td>' + cursor.value.jTitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + curso...
IDBIndex.keyPath - Web APIs
Web › API › IDBIndex › keyPath
e.) function displayDataByIndex() { tableEntry.innerHTML = ''; var transaction = db.transaction(['contactsList'], 'readonly'); var objectStore = transaction.objectStore('contactsList'); var myIndex = objectStore.index('lName'); console.log(myIndex.keyPath); myIndex.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lName + '</td>' + '<td>' + cursor.value.fName + '</td>' + '<td>' + cursor.value.jTitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + curso...
IDBIndex.locale - Web APIs
Web › API › IDBIndex › locale
ole. ...
IDBIndex.multiEntry - Web APIs
function displayDataByIndex() { tableEntry.innerHTML = ''; var transaction = db.transaction(['contactsList'], 'readonly'); var objectStore = transaction.objectStore('contactsList'); var myIndex = objectStore.index('lName'); console.log(myIndex.multiEntry); myIndex.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lName + '</td>' + '<td>' + cursor.value.fName + '</td>' + '<td>' + cursor.value.jTitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + curso...
IDBIndex.name - Web APIs
Web › API › IDBIndex › name
live). ...
IDBIndex.objectStore - Web APIs
function displayDataByIndex() { tableEntry.innerHTML = ''; var transaction = db.transaction(['contactsList'], 'readonly'); var objectStore = transaction.objectStore('contactsList'); var myIndex = objectStore.index('lName'); console.log(myIndex.objectStore); myIndex.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lName + '</td>' + '<td>' + cursor.value.fName + '</td>' + '<td>' + cursor.value.jTitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + curso...
IDBIndex.openCursor() - Web APIs
demo repo (View the example live.) function displayDataByIndex() { tableEntry.innerHTML = ''; var transaction = db.transaction(['contactsList'], 'readonly'); var objectStore = transaction.objectStore('contactsList'); var myIndex = objectStore.index('lName'); myIndex.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lName + '</td>' + '<td>' + cursor.value.fName + '</td>' + '<td>' + cursor.value.jTitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + curso...
IDBIndex.openKeyCursor() - Web APIs
enced record into an HTML table. ...
IDBIndex.unique - Web APIs
Web › API › IDBIndex › unique
ve.) function displayDataByIndex() { tableEntry.innerHTML = ''; var transaction = db.transaction(['contactsList'], 'readonly'); var objectStore = transaction.objectStore('contactsList'); var myIndex = objectStore.index('lName'); console.log(myIndex.unique); myIndex.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lName + '</td>' + '<td>' + cursor.value.fName + '</td>' + '<td>' + cursor.value.jTitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + curso...
IDBIndex - Web APIs
Web › API › IDBIndex
e demo repo (View the example live.) function displayDataByIndex() { tableEntry.innerHTML = ''; var transaction = db.transaction(['contactsList'], 'readonly'); var objectStore = transaction.objectStore('contactsList'); var myIndex = objectStore.index('lName'); myIndex.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lName + '</td>' + '<td>' + cursor.value.fName + '</td>' + '<td>' + cursor.value.jTitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + curso...
IDBKeyRange.bound() - Web APIs
Web › API › IDBKeyRange › bound
indexeddb-examples repo (view the example live too.) function displayData() { var keyRangeValue = IDBKeyRange.bound("A", "F"); var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = transaction.objectStore('fThings'); objectStore.openCursor(keyRangeValue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating; list.appendChild(listItem); cursor.continue(); } else { console.log('Entries all displayed.'); } }; }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'bound()' in that ...
IDBKeyRange.lower - Web APIs
Web › API › IDBKeyRange › lower
oo.) function displayData() { var keyRangeValue = IDBKeyRange.bound("F", "W", true, true); console.log(keyRangeValue.lower); var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = transaction.objectStore('fThings'); objectStore.openCursor(keyRangeValue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating; list.appendChild(listItem); cursor.continue(); } else { console.log('Entries all displayed.'); } }; }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'lower' in that ...
IDBKeyRange.lowerBound() - Web APIs
DBKeyRange-example repo (view the example live too.) function displayData() { var keyRangeValue = IDBKeyRange.lowerBound("F"); var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = transaction.objectStore('fThings'); objectStore.openCursor(keyRangeValue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating; list.appendChild(listItem); cursor.continue(); } else { console.log('Entries all displayed.'); } }; }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'lowerBound()' i...
IDBKeyRange.lowerOpen - Web APIs
function displayData() { var keyRangeValue = IDBKeyRange.bound("F", "W", true, true); console.log(keyRangeValue.lowerOpen); var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = transaction.objectStore('fThings'); objectStore.openCursor(keyRangeValue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating; list.appendChild(listItem); cursor.continue(); } else { console.log('Entries all displayed.'); } }; }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'lowerOpen' in that...
IDBKeyRange.only() - Web APIs
Web › API › IDBKeyRange › only
look at our IDBKeyRange repo (view the example live too.) function displayData() { var keyRangeValue = IDBKeyRange.only("A"); var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = transaction.objectStore('fThings'); objectStore.openCursor(keyRangeValue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating; list.appendChild(listItem); cursor.continue(); } else { console.log('Entries all displayed.'); } }; }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'only' in that spec...
IDBKeyRange.upper - Web APIs
Web › API › IDBKeyRange › upper
oo.) function displayData() { var keyRangeValue = IDBKeyRange.bound("F", "W", true, true); console.log(keyRangeValue.upper); var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = transaction.objectStore('fThings'); objectStore.openCursor(keyRangeValue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating; list.appendChild(listItem); cursor.continue(); } else { console.log('Entries all displayed.'); } }; }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'upper' in that ...
IDBKeyRange.upperBound() - Web APIs
DBKeyRange-example repo (view the example live too.) function displayData() { var keyRangeValue = IDBKeyRange.upperBound("F"); var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = transaction.objectStore('fThings'); objectStore.openCursor(keyRangeValue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating; list.appendChild(listItem); cursor.continue(); } else { console.log('Entries all displayed.'); } }; }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'upperBound()...
IDBKeyRange.upperOpen - Web APIs
function displayData() { var keyRangeValue = IDBKeyRange.bound("F", "W", true, true); console.log(keyRangeValue.upperOpen); var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = transaction.objectStore('fThings'); objectStore.openCursor(keyRangeValue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating; list.appendChild(listItem); cursor.continue(); } else { console.log('Entries all displayed.'); } }; }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'upperOpen' in t...
IDBKeyRange - Web APIs
ur IDBKeyRange-example repo (view the example live too.) function displayData() { var keyRangeValue = IDBKeyRange.bound("A", "F"); var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = transaction.objectStore('fThings'); objectStore.openCursor(keyRangeValue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating; list.appendChild(listItem); cursor.continue(); } else { console.log('Entries all displayed.'); } }; } Specifications Specification Status Comment Indexed Database API 2.0The definition of 'IDBKeyRange' in that specification...
IDBLocaleAwareKeyRange - Web APIs
amples function displayData() { var keyRangeValue = IDBLocaleAwareKeyRange.bound("A", "F"); var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = transaction.objectStore('fThings'); var myIndex = objectStore.index('lName'); myIndex.openCursor(keyRangeValue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '&lt;td&gt;' + cursor.value.id + '&lt;/td&gt;' + '&lt;td&gt;' + cursor.value.lName + '&lt;/td&gt;' + '&lt;td&gt;' + cursor.value.fName + '&lt;/td&gt;' + '&lt;td&gt;' + cursor.value.jTitle + '&lt;/td&gt;' + '&lt;td&gt;' + cursor.value.company...
IDBObjectStore.index() - Web APIs
e demo repo (View the example live.) function displayDataByIndex() { tableEntry.innerHTML = ''; var transaction = db.transaction(['contactsList'], 'readonly'); var objectStore = transaction.objectStore('contactsList'); var myIndex = objectStore.index('lName'); myIndex.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lName + '</td>' + '<td>' + cursor.value.fName + '</td>' + '<td>' + cursor.value.jTitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + curso...
IDBVersionChangeEvent.newVersion - Web APIs
in Web Workers. Syntax var newVersion = IDBVersionChangeEvent.newVersion Value A 64-bit integer. Example In the following code snippet, we make a request to open a database, and include handlers for the success and error cases. These events are fired via the custom IDBVersionChangeEvent interface. For a full working example, see our To-do Notifications app (view example live.) var note = document.querySelector("ul"); // In the following line, you should include the prefixes of // implementations you want to test. window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; // DON'T use "var indexedDB = ..." if you're not in a function. // Moreover, you may need references to some window.IDB* objects: window.IDBTransaction = window.IDBTransac...
IDBVersionChangeEvent - Web APIs
but inherits properties from its parent, Method. Example In the following code snippet, we make a request to open a database, and include handlers for the success and error cases. Upon a version change (after an upgradedneeded event), the success event will implement the IDBVersionChangeEvent interface. For a full working example, see our To-do Notifications app (view example live.) var note = document.querySelector("ul"); // In the following line, you should include the prefixes of implementations you want to test. window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; // DON'T use "var indexedDB = ..." if you're not in a function. // Moreover, you may need references to some window.IDB* objects: window.IDBTransaction = window.IDBTransactio...
ImageBitmapRenderingContext.transferFromImageBitmap() - Web APIs
nsferred 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); Specifications Sp...
ImageCapture() constructor - Web APIs
ing movie, or the stream from a webcam. Return value A new ImageCapture object which can be used to capture still frames from the specified video track. Example The following example shows how to use a call to MediaDevices.getUserMedia() to retrieve the MediaStreamTrack needed by the ImageCapture() constructor. navigator.mediaDevices.getUserMedia({video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream const track = mediaStream.getVideoTracks()[0]; imageCapture = new ImageCapture(track); }) .catch(error => console.log(error)); Specifications Specification Status Comment MediaStream Image CaptureThe definition of 'ImageCapture' in that specification. Working Draft Initial definition. ...
ImageData() - Web APIs
n 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. ...
ImageData.data - Web APIs
Web › API › ImageData › data
// 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. ...
Browser storage limits and eviction criteria - Web APIs
g) doesn't store any data on the client. What technologies use browser data storage? In Firefox, the following technologies make use of browser data storage to store data when required. We term them "quota clients" in this context: IndexedDB asm.js caching Cache API Cookies Note: In Firefox, Web Storage will soon start to use the same storage management tools too, as described in this document. Note: In private browsing mode, most data storage is not supported. Local storage data and cookies are still stored, but they are ephemeral -- the data is deleted when you close the last private browsing window. The "last access time" of origins is updated when any of these are activated/deactivated -- origin eviction will delete data for all these quota clients. In Chrome/Opera, the Quota...
Using IndexedDB - Web APIs
IndexedDB is a way for you to persistently store data inside a user's browser. Because it lets you create web applications with rich query abilities regardless of network availability, your applications can work both online and offline. About this document This tutorial walks you through using the asynchronous API of IndexedDB. If you are not familiar with IndexedDB, you should first read Basic Concepts About IndexedDB. For the reference documentation on the IndexedDB API, see the IndexedDB article and its subpages. This article documents the types of objects used by IndexedDB, as well as the methods of the asynchronous API (the synchronous API was removed from spec). Basic pattern The basic pattern that IndexedDB encourages is the following: Open a database. Create an object store ...
IndexedDB API - Web APIs
faces This specification fires events with the following custom interface: IDBVersionChangeEvent The IDBVersionChangeEvent interface indicates that the version of the database has changed, as the result of an IDBOpenDBRequest.onupgradeneeded event handler function. Obsolete interfaces An early version of the specification also defined the following, now removed, interfaces. They are still documented in case you need to update previously written code: IDBVersionChangeRequest Represents a request to change the version of a database. The way to change the version of the database has since changed (by calling IDBFactory.open without also calling IDBDatabase.setVersion), and the interface IDBOpenDBRequest now has the functionality of the removed IDBVersionChangeRequest. IDBDatabaseExcept...
InputEvent.data - Web APIs
Web › API › InputEvent › data
In the following simple example we've set up an event listener on the input event so that when any change is made to the contents of the <input> element (either by typing or pasting), the text that was added is retrieved via the InputEvent.data property and reported in the paragraph below the input. <p>Some text to copy and paste.</p> <input type="text"> <p class="result"></p> var editable = document.querySelector('input') var result = document.querySelector('.result'); editable.addEventListener('input', (e) => { result.textContent = "Inputted text: " + e.data; }); Specifications Specification Status Comment Input Events Level 2The definition of 'data' in that specification. Working Draft Initial definition. ...
InputEvent.dataTransfer - Web APIs
the content provided to see the effects. <p><span style="font-weight: bold; color: blue">Whoa, bold blue text!</span></p> <p><span style="font-style: italic; color: red">Exciting: italic red text!</span></p> <p>Boring normal text ;-(</p> <hr> <p contenteditable="true">Go on, try pasting some content into this editable paragraph and see what happens!</p> <p class="result"></p> var editable = document.querySelector('p[contenteditable]'); var result = document.querySelector('.result') var dataTransferObj; editable.addEventListener('input', (e) => { result.textContent = e.dataTransfer.getData('text/html'); }); Specifications Specification Status Comment Input Events Level 2The definition of 'dataTransfer' in that specification. Working Draft Initial definitio...
InputEvent.inputType - Web APIs
e <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 example. Specification...
InputEvent.isComposing - Web APIs
The InputEvent.isComposing read-only property returns a Boolean value indicating if the event is fired after compositionstart and before compositionend. Syntax var bool = event.isComposing; Example var inputEvent = new InputEvent('syntheticInput', false); console.log(inputEvent.isComposing); // return false Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'InputEvent.isComposing' in that specification. Obsolete Initial definition. ...
IntersectionObserver.IntersectionObserver() - Web APIs
entries An array of IntersectionObserverEntry objects, each representing one threshold which was crossed, either becoming more or less visible than the percentage specified by that threshold. observer The IntersectionObserver for which the callback is being invoked. options Optional An optional object which customizes the observer. If options isn't specified, the observer uses the document's viewport as the root, with no margin, and a 0% threshold (meaning that even a one-pixel change is enough to trigger a callback). You can provide any combination of the following options: root An Element or Document object which is an ancestor of the intended target, whose bounding rectangle will be considered the viewport. Any part of the target not visible in the visible area of the root...
IntersectionObserver.observe() - Web APIs
ting the intersection changes which occurred. Note that this design allows multiple elements' intersection changes to be processed by a single call to the callback. Syntax IntersectionObserver.observe(targetElement); Parameters targetElement An element whose visibility within the root is to be monitored. This element must be a descendant of the root element (or contained wtihin the current document, if the root is the document's viewport). Return value undefined. Examples <<<...>>> Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserver.observe()' in that specification. Working Draft Initial definition. ...
IntersectionObserver.unobserve() - Web APIs
nObserver.unobserve(target); Parameters target The Element to cease observing. If the specified element isn't being observed, this method does nothing and no exception is thrown. Return value undefined. Example This snippet simply shows an observer being created, an element being observed, and then being unobserved. var observer = new IntersectionObserver(callback); observer.observe(document.getElementById("elementToObserve")); /* ... */ observer.unobserve(document.getElementById("elementToObserve")); Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserver.unobserve()' in that specification. Working Draft Initial definition. ...
IntersectionObserverEntry.rootBounds - Web APIs
The IntersectionObserverEntry interface's read-only rootBounds property is a DOMRectReadOnly corresponding to the target's root intersection rectangle, offset by the IntersectionObserver.rootMargin if one is specified. Syntax var rootBounds = IntersectionObserverEntry.rootBounds; Value A DOMRectReadOnly which describes the root intersection rectangle. For roots which are the Document's viewport, this rectangle is the bounds rectangle of the entire document. Otherwise, it's the bounds of the root element. This rectangle is offset by the values in IntersectionObserver.rootMargin. Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserverEntry.rootBounds' in that specification. Working Draft Initial definit...
IntersectionObserverEntry.time - Web APIs
The IntersectionObserverEntry interface's read-only time property is a DOMHighResTimeStamp that indicates the time at which the intersection change occurred relative to the time at which the document was created. Syntax var time = IntersectionObserverEntry.time; Value A DOMHighResTimeStamp which indicates the time at which the target element experienced the intersection change described by the IntersectionObserverEntry. The time is specified in milliseconds since the creation of the containing document. Example See Timing element visibility with the Intersection Observer API for a complete example which uses the time property to track how long elements are visible to the user. Specifications Specification Status Comment Intersection ObserverThe definitio...
IntersectionObserverEntry - Web APIs
n. Instances of IntersectionObserverEntry are delivered to an IntersectionObserver callback in its entries parameter; otherwise, these objects can only be obtained by calling IntersectionObserver.takeRecords(). Properties IntersectionObserverEntry.boundingClientRect Read only Returns the bounds rectangle of the target element as a DOMRectReadOnly. The bounds are computed as described in the documentation for Element.getBoundingClientRect(). IntersectionObserverEntry.intersectionRatio Read only Returns the ratio of the intersectionRect to the boundingClientRect. IntersectionObserverEntry.intersectionRect Read only Returns a DOMRectReadOnly representing the target's visible area. IntersectionObserverEntry.isIntersecting Read only A Boolean value which is true if the target element int...
InterventionReportBody - Web APIs
So for example, a script was been stopped because it was significantly slowing down the browser, or the browser's autoplay policy blocked audio from playing without a user gesture to trigger it. ...
KeyboardEvent() - Web APIs
aulting to 0, of type unsigned long, that sets the value of the deprecated KeyboardEvent.which. The KeyboardEventInit dictionary also accepts fields from the UIEventInit and EventInit dictionaries. Specifications Specification Status Comment UI EventsThe definition of 'KeyboardEvent()' in that specification. Working Draft Current definition. Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'KeyboardEvent()' in that specification. Obsolete Initial definition. ...
KeyboardEvent.altKey - Web APIs
Obsolete Initial definition. ...
KeyboardEvent.ctrlKey - Web APIs
Obsolete Initial definition. ...
KeyboardEvent.getModifierState() - Web APIs
nd old Gecko // Do something different if ScrollLock is locked. event.preventDefault(); // consume the key event break; } } Although this example uses .getModifierState() with "Alt", "Control", "Meta" and "Shift", using event.altKey, event.ctrlKey, event.metaKey and event.shiftKey may be more preferable. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'getModifierState()' in that specification. Obsolete Initial definition (Modifier Keys spec) ...
KeyboardEvent.isComposing - Web APIs
after compositionstart and before compositionend. Syntax var bool = event.isComposing; Example var kbdEvent = new KeyboardEvent("syntheticKey", false); console.log(kbdEvent.isComposing); // return false Specifications Specification Status Comment UI EventsThe definition of 'KeyboardEvent.prototype.isComposing' in that specification. Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'KeyboardEvent.prototype.isComposing' in that specification. Obsolete Initial definition. ...
KeyboardEvent.keyCode - Web APIs
vent.key !== undefined) { // Handle the event with KeyboardEvent.key and set handled true. } else if (event.keyCode !== undefined) { // Handle the event with KeyboardEvent.keyCode and set handled true. } if (handled) { // Suppress "double action" if event handled event.preventDefault(); } }, true); Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'KeyboardEvent.keyCode' in that specification. Obsolete Initial definition; specified as deprecated ...
KeyboardEvent.location - Web APIs
fires trusted key events with DOM_KEY_LOCATION_JOYSTICK except on Android. Starting 18, native key events on Android may have this value. However, at Gecko 38, this is dropped. Syntax var location = event.location; Example function keyEvent(event) { console.log("Location of key pressed: " + event.location); } Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'KeyboardEvent.location' in that specification. Obsolete Initial definition. ...
KeyboardEvent.metaKey - Web APIs
not considered the "Meta" key. KeyboardEvent.metaKey is false when the ? Windows is pressed. Syntax var metaKeyPressed = instanceOfKeyboardEvent.metaKey Return value A Boolean Example function ismetaKey(e) { alert("metaKey = " + e.metaKey); } <button onclick="ismetaKey(event)">Click me with the meta key</button> Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'KeyboardEvent.metaKey' in that specification. Obsolete Initial definition ...
KeyboardEvent.repeat - Web APIs
Obsolete Initial definition. ...
KeyboardEvent.shiftKey - Web APIs
Obsolete Initial definition. ...
KeyboardEvent.which - Web APIs
Obsolete Initial definition; specified as deprecated ...
LargestContentfulPaint - Web APIs
ilable, // otherwise using `loadTime`. (Note: `renderTime` may not be available on // image elements loaded cross-origin without the `Timing-Allow-Origin` header.) lcp = lastEntry.renderTime || lastEntry.loadTime; }); po.observe({type: 'largest-contentful-paint', buffered: true}); // Send data to the server. addEventListener('visibilitychange', function fn() { if (lcp && document.visibilityState === 'hidden') { console.log('LCP:', lcp); removeEventListener('visibilitychange', fn, true); } }, true); } catch (e) { // Do nothing if the browser doesn't support this API. } Specifications Specification Status Comment Largest Contentful PaintThe definition of 'LargestContentfulPaint' in that specification. Editor's Draft Initi...
LayoutShift - Web APIs
s.webkit.org/show_bug.cgi?id=209216 try { let cumulativeLayoutShiftScore = 0; const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { // Only count layout shifts without recent user input. if (!entry.hadRecentInput) { cumulativeLayoutShiftScore += entry.value; } } }); observer.observe({type: 'layout-shift', buffered: true}); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') { // Force any pending records to be dispatched. observer.takeRecords(); observer.disconnect(); console.log('CLS:', cumulativeLayoutShiftScore); } }); } catch (e) { // Do nothing if the browser doesn't support this API. } Specifications Specification Status Comment ...
LinkStyle - Web APIs
Web › API › LinkStyle
ly Returns the CSSStyleSheet object associated with the given element, or null if there is none. Methods This interface implements no method. Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'LinkStyle' in that specification. Working Draft LinkStyle.sheet returns more specialized CSSStyleSheet instead of StyleSheet Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'LinkStyle' in that specification. Obsolete Initial definition ...
LocalFileSystem - Web APIs
tentStorage.queryUsageAndQuota(). To learn more, see this StackOverflow Answer. (An older version of the API is described at Managing HTML5 Offline Storage.) Working within a single origin The file system is sandboxed to a single origin. This means that your app cannot read, or write the files of another app's files. Your app cannot access files in an arbitrary folder (such as, My Pictures, My Documents) on the user's hard drive either. For more information about restrictions, see the Basic Concepts article. Example The following is a code snippet that shows how you can request a file system storage. //Taking care of the browser-specific prefix window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; // The first parameter defines the type of storage: persist...
Location: ancestorOrigins - Web APIs
The ancestorOrigins read-only property of the Location interface is a static DOMStringList containing, in reverse order, the origins of all ancestor browsing contexts of the document associated with the given Location object. You can use location.ancestorOrigins in the script for a document to determine, for example, whenever the document is being framed by a site which you don't expect it to be framed by. You can also use it to vary the behavior of the document based on what site or list of sites is framing it. Syntax const ancestors = location.ancestorOrigins; Specifications Specification Status Comment HTML Living StandardThe definition of 'ancestorOrigins ' in that specification. Living Standard ...
Location: assign() - Web APIs
Web › API › Location › assign
After the navigation occurs, the user can navigate back to the page that called Location.assign() by pressing the "back" button. If the assignment can't happen because of a security violation, a DOMException of the SECURITY_ERROR type is thrown. This happens if the origin of the script calling the method is different from the origin of the page originally described by the Location object, mostly when the script is hosted on a different domain. If the provided URL is not valid, a DOMException of the SYNTAX_ERROR type is thrown. ...
Location: hash - Web APIs
Web › API › Location › hash
rty of the Location interface returns a USVString containing a '#' followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string, "". Syntax string = object.hash; object.hash = string; Examples <a id="myAnchor" href="/docs/Location.href#Examples">Examples</a> <script> var anchor = document.getElementById("myAnchor"); console.log(anchor.hash); // Returns '#Examples' </script> Specifications Specification Status Comment HTML Living StandardThe definition of 'hash' in that specification. Living Standard Initial definition ...
Location: host - Web APIs
Web › API › Location › host
The host property of the Location interface is a USVString containing the host, that is the hostname, and then, if the port of the URL is nonempty, a ':', and the port of the URL. ...
Location: hostname - Web APIs
Web › API › Location › hostname
The hostname property of the Location interface is a USVString containing the domain of the URL. Syntax string = object.hostname; object.hostname = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org/docs/Location.hostname"> element be in the document var anchor = document.getElementById("myAnchor"); var result = anchor.hostname; // Returns:'developer.mozilla.org' Specifications Specification Status Comment HTML Living StandardThe definition of 'hostname' in that specification. Living Standard Initial definition. ...
Location: href - Web APIs
Web › API › Location › href
Location interface is a stringifier that returns a USVString containing the whole URL, and allows the href to be updated. Setting the value of href navigates to the provided URL. If you want redirection, use Location.replace(). Syntax string = object.href; object.href = string; Examples // Lets imagine an <a id="myAnchor" href="https://developer.mozilla.org/Location/href"> element is in the document var anchor = document.getElementById("myAnchor"); var result = anchor.href; // Returns: 'https://developer.mozilla.org/Location/href' Specifications Specification Status Comment HTML Living StandardThe definition of 'href' in that specification. Living Standard Initial definition. ...
Location: password - Web APIs
Web › API › Location › password
The password property of the Location interface is a USVString containing the password specified before the domain name. If it is set without first setting the username property, it silently fails. Syntax string = object.password; object.password = string; Examples // Let's <a id="myAnchor" href="https://anonymous:flabada@developer.mozilla.org/docs/location.username"> be in the document var anchor = document.getElementByID("myAnchor"); var result = anchor.password; // Returns:'flabada' ...
Location: pathname - Web APIs
Web › API › Location › pathname
The pathname property of the Location interface is a USVString containing an initial '/' followed by the path of the URL (or the empty string if there is no path). Syntax string = object.pathname; object.pathname = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org/docs/Location.pathname"> element be in the document var anchor = document.getElementById("myAnchor"); var result = anchor.pathname; // Returns:'/docs/Location.pathname' Specifications Specification Status Comment HTML Living StandardThe definition of 'pathname' in that specification. Living Standard Initial definition. ...
Location: port - Web APIs
Web › API › Location › port
The port property of the Location interface is a USVString containing the port number of the URL. If the URL does not contain an explicit port number, it will be set to ''. Syntax string = object.port; object.port = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org:443/docs/Location.port"> element be in the document var anchor = document.getElementByID("myAnchor"); var result = anchor.port; // Returns:'443' Specifications Specification Status Comment HTML Living StandardThe definition of 'Location.port' in that specification. Living Standard Initial definition. ...
Location: protocol - Web APIs
Web › API › Location › protocol
The protocol property of the Location interface is a USVString representing the protocol scheme of the URL, including the final ':'. Syntax string = object.protocol; object.protocol = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org/Location.protocol"> element be in the document var anchor = document.getElementById("myAnchor"); var result = anchor.protocol; // Returns:'https:' Specifications Specification Status Comment HTML Living StandardThe definition of 'protocol' in that specification. Living Standard Initial definition. ...
Location: search - Web APIs
Web › API › Location › search
a query string; that is, a USVString containing a '?' followed by the parameters of the URL. Modern browsers provide URLSearchParams and URL.searchParams to make it easy to parse out the parameters from the querystring. Syntax string = object.search; object.search = string; Examples // Let an <a id="myAnchor" href="https://developer.mozilla.org/docs/Location.search?q=123"> element be in the document var anchor = document.getElementById("myAnchor"); var queryString = anchor.search; // Returns:'?q=123' // Further parsing: let params = new URLSearchParams(queryString); let q = parseInt(params.get("q")); // is the number 123 Specifications Specification Status Comment HTML Living StandardThe definition of 'search' in that specification. Living Standard Initial d...
Location: username - Web APIs
Web › API › Location › username
The username property of the Location interface is a USVString containing the username specified before the domain name. Syntax string = object.username; object.username = string; Examples // Let's <a id="myAnchor" href="https://anonymous:flabada@developer.mozilla.org/docs/Location.username"> be in the document var anchor = document.getElementByID("myAnchor"); var result = anchor.username; // Returns:'anonymous' ...
MediaDevices.getDisplayMedia() - Web APIs
s of the returned promise are made by passing a DOMException error object to the promise's failure handler. Possible errors are: AbortError An error or failure that doesn't match any of the other exceptions below occurred. InvalidStateError The call to getDisplayMedia() was not made from code running due to a user action, such as an event handler. Another potential cause for this event: the document in whose context getDisplayMedia() was called is not fully active; for example, perhaps it is not the frontmost tab. NotAllowedError Permission to access a screen area was denied by the user, or the current browsing instance is not permitted access to screen sharing. NotFoundError No sources of screen video are available for capture. NotReadableError The user selected a screen, window, tab,...
MediaElementAudioSourceNode() - Web APIs
o context you want the node to be associated with. options A MediaElementAudioSourceOptions dictionary object defining the properties you want the MediaElementAudioSourceNode to have: mediaElement: An HTMLMediaElement that will be used as the source for the audio. Return value A new MediaElementAudioSourceNode object instance. Example var ac = new AudioContext(); var mediaElement = document.createElement('audio'); var options = { mediaElement : mediaElement } var myAudioSource = new MediaElementAudioSourceNode(ac, options); Specifications Specification Status Comment Web Audio APIThe definition of 'MediaElementAudioSourceNode' in that specification. Working Draft ...
MediaElementAudioSourceNode.mediaElement - Web APIs
ified when the node was first created, either using the MediaElementAudioSourceNode() constructor or the AudioContext.createMediaElementSource() method. Syntax audioSourceElement = mediaElementAudioSourceNode.mediaElement; Value An HTMLMediaElement representing the element which contains the source of audio for the node. Examples const audioCtx = new window.AudioContext(); const audioElem = document.querySelector('audio'); let options = { mediaElement: audioElem } let source = new MediaElementAudioSourceNode(audioCtx, options); console.log(source.mediaElement); Specifications Specification Status Comment Web Audio APIThe definition of 'MediaElementAudioSourceNode.mediaElement' in that specification. Working Draft ...
MediaError.code - Web APIs
Web › API › MediaError › code
an error. MEDIA_ERR_SRC_NOT_SUPPORTED 4 The associated resource or media provider object (such as a MediaStream) has been found to be unsuitable. Example This example creates a <video> element, establishes an error handler for it, and then sets the element's src attribute to the video resource to present in the element. The error handler simply outputs a message var obj = document.createElement('video'); obj.onerror = function() {console.log("Error with media: " + obj.error.code);} obj.src="https://example.com/blahblah.mp4"; Specifications Specification Status Comment HTML Living StandardThe definition of 'MediaError.code' in that specification. Living Standard Initial definition ...
MediaQueryList.matches - Web APIs
The matches read-only property of the MediaQueryList interface is a Boolean that returns true if the document currently matches the media query list, or false if not. You can be notified when the value of matches changes by watching for the change event to be fired at the MediaQueryList. Syntax var matches = <varm>MediaQueryList.matches; Value A Boolean which is true if the document currently matches the media query list; otherwise, it's false. Examples This example detects viewport orientation changes by creating a media query using the orientation media feature: function addMQListener(mq, callback) { if (mq.addEventListener) { mq.addEventListener("change", callback); } else { mq.addListener(callback); } } addMQListener(window.matchMedia("(orientation:landscape)"), event...
MediaQueryList.media - Web APIs
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: bold; color: #88f; padding: 0...
MediaRecorder: error event - Web APIs
The MediaRecorder interface's error event is fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec. Bubbles No Cancelable No Interface MediaRecorderErrorEvent Event handler property onerror For details of the all the possible errors see the documentation for the event handler property: onerror. Examples Using addEventListener to listen for error events: async function record() { const stream = await navigator.mediaDevices.getUserMedia({audio: true}); const recorder = new MediaRecorder(stream); recorder.addEventListener('error', (event) => { console.error(`error recording stream: ${event.error.name}`) }); recorder.start(); } record(); The same, but...
MediaRecorder.ondataavailable - Web APIs
ell. The Blob containing the media data is available in the dataavailable event's data property. Syntax MediaRecorder.ondataavailable = function(event) { ... } MediaRecorder.addEventListener('dataavailable', function(event) { ... }) Example ... var chunks = []; mediaRecorder.onstop = function(e) { console.log("data available after MediaRecorder.stop() called."); var audio = document.createElement('audio'); audio.controls = true; var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audioURL = window.URL.createObjectURL(blob); audio.src = audioURL; console.log("recorder stopped"); } mediaRecorder.ondataavailable = function(e) { chunks.push(e.data); } ... Specifications Specification Status Comment Me...
MediaRecorder.onstop - Web APIs
e stop event is preceded by a dataavailable event, making the Blob captured up to that point available for you to use in your application. Syntax MediaRecorder.onstop = function(event) { ... } MediaRecorder.addEventListener('stop', function(event) { ... }) Example ... mediaRecorder.onstop = function(e) { console.log("data available after MediaRecorder.stop() called."); var audio = document.createElement('audio'); audio.controls = true; var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audioURL = window.URL.createObjectURL(blob); audio.src = audioURL; console.log("recorder stopped"); } mediaRecorder.ondataavailable = function(e) { chunks.push(e.data); } ... Specifications Specification Status Comment Med...
MediaRecorder - Web APIs
function() { mediaRecorder.stop(); console.log(mediaRecorder.state); console.log("recorder stopped"); record.style.background = ""; record.style.color = ""; } mediaRecorder.onstop = function(e) { console.log("data available after MediaRecorder.stop() called."); var clipName = prompt('Enter a name for your sound clip'); var clipContainer = document.createElement('article'); var clipLabel = document.createElement('p'); var audio = document.createElement('audio'); var deleteButton = document.createElement('button'); clipContainer.classList.add('clip'); audio.setAttribute('controls', ''); deleteButton.innerHTML = "Delete"; clipLabel.innerHTML = clipName; clipContainer.appendChild(audio); ...
MediaSession.playbackState - Web APIs
none The browsing context doesn't currently know the current playback state, or the playback state is not available at this time. paused The browser's media session is currently paused. Playback may be resumed. playing The browser's media session is currently playing media, which can be paused. ...
MediaSession.setPositionState() - Web APIs
The MediaSession method setPositionState() is used to update the current document's media playback position and speed for presentation by user's device in any kind of interface that provides details about ongoing media. This can be particularly useful if your code implements a player for type of media not directly supported by the browser. Call this method on the navigator object's mediaSession object. Syntax navigator.mediaSession.setPositionState(stateDict); Parameters stateDict Optional An object conforming to the MediaPositionState dictionary, providing updated information about the playback position and speed of the document's ongoing media. If the object is empty, the existing playback state information is cleared. Return value undefined. Exceptions TypeError This error c...
MediaSession - Web APIs
se', function() {}); navigator.mediaSession.setActionHandler('seekbackward', function() {}); navigator.mediaSession.setActionHandler('seekforward', function() {}); navigator.mediaSession.setActionHandler('previoustrack', function() {}); navigator.mediaSession.setActionHandler('nexttrack', function() {}); } The following example sets up event handlers for pausing and playing: var audio = document.querySelector("#player"); audio.src = "song.mp3"; navigator.mediaSession.setActionHandler('play', play); navigator.mediaSession.setActionHandler('pause', pause); function play() { audio.play(); navigator.mediaSession.playbackState = "playing"; } function pause() { audio.pause(); navigator.mediaSession.playbackState = "paused"; } Specifications Specification Status Comm...
MediaSource.MediaSource() - Web APIs
The MediaSource() constructor of the MediaSource interface constructs and returns a new MediaSource object with no associated source buffers. Syntax var mediaSource = new MediaSource(); Parameters None. ...
MediaSource - Web APIs
if the given MIME type is supported by the current user agent -- this is, if it can successfully create SourceBuffer objects for that MIME type. Examples The following simple example loads a video with XMLHttpRequest, playing it as soon as it can. ...
active - Web APIs
whose source is the user's local camera and microphone is requested using getUserMedia(). When that stream becomes available (that is, when the returned Promise is fulfilled, a button on the page is updated based on whether or not the stream is currently active. var promise = navigator.mediaDevices.getUserMedia({ audio: true, video: true }); promise.then(function(stream) { var startBtn = document.querySelector('#startBtn'); startBtn.disabled = stream.active; };) Specifications Specification Status Comment Media Capture and StreamsThe definition of 'active' in that specification. Candidate Recommendation Initial definition. ...
MediaStream.getAudioTracks() - Web APIs
streams; however, this has since been merged into the main MediaStreamTrack interface. Example This example gets a webcam's audio and video in a stream using getUserMedia(), attaches the stream to a <video> element, then sets a timer that, upon expiring, will stop the first audio track found on the stream. navigator.mediaDevices.getUserMedia({audio: true, video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; // Stop the audio stream after 5 seconds setTimeout(() => { const tracks = mediaStream.getAudioTracks() tracks[0].stop() }, 5000) }) Specifications Specification Status Comment Media Capture and StreamsThe definition of 'getAudioTracks()' in that specification. Candidate Recommendation Initial defin...
MediaStream.getTracks() - Web APIs
) method of the MediaStream interface returns a sequence that represents all the MediaStreamTrack objects in this stream's track set, regardless of MediaStreamTrack.kind. Syntax var mediaStreamTracks = mediaStream.getTracks() Parameters None. Return value An array of MediaStreamTrack objects. Example navigator.mediaDevices.getUserMedia({audio: false, video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; // Stop the stream after 5 seconds setTimeout(() => { const tracks = mediaStream.getTracks() tracks[0].stop() }, 5000) }) Specifications Specification Status Comment Media Capture and StreamsThe definition of 'getTracks()' in that specification. Candidate Recommendation Initial definition. Br...
MediaStream.getVideoTracks() - Web APIs
h entry in the list of video streams; however, this has since been merged into the main MediaStreamTrack interface. Example The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses getVideoTracks() to retrieve a track for passing to the ImageCapture() constructor. var imageCapture; navigator.mediaDevices.getUserMedia({video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; const track = mediaStream.getVideoTracks()[0]; imageCapture = new ImageCapture(track); return imageCapture.getPhotoCapabilities(); }) Specifications Specification Status Comment Media Capture and StreamsThe definition of 'getVideoTracks()' in that specification. Candidate Recommendation Initial definition. ...
MediaStream.onaddtrack - Web APIs
ting the addtrack event which has occurred. The MediaStreamTrack representing the track which was added is specified in the event's track property. Example This example adds a listener which, when a new track is added to the stream, appends a new item to a list of tracks; the new item shows the track's kind ("audio" or "video") and label. stream.onaddtrack = function(event) { let trackList = document.getElementById("tracks"); let label = document.createElement("li"); label.innerHTML = event.track.kind + ": " + event.track.label; trackList.appendChild(label); }; Specifications Specification Status Comment Media Capture and StreamsThe definition of 'MediaStream.onaddtrack' in that specification. Candidate Recommendation Initial specification. ...
MediaStream.onremovetrack - Web APIs
ovide 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. Example This example adds a listener which, when a track is removed from the stream, logs the track that was removed. stream.onremovetrack = function(event) { let trackList = document.getElementById("tracks"); let label = document.createElement("li"); label.innerHTML = "Removed: " + event.track.kind + ": " + event.track.label; trackList.appendChild(label); }; Specifications Specification Status Comment Media Capture and StreamsThe definition of 'MediaStream.onremovetrack' in that specification. Candidate Recommendation Initial specif...
MediaStreamTrack.onended - Web APIs
k.onended = function; Value A function to serve as an EventHandler for the ended event. The event handler function receives a single parameter: the event object, which is a simple Event object. Examples This example sets up an event handler for the ended event which changes an on-screen icon to indicate that the track is no longer active. track.onended = function(event) { let statusElem = document.getElementById("status-icon"); statusElem.src = "/images/stopped-icon.png"; } Specifications Specification Status Comment Media Capture and StreamsThe definition of 'MediaStreamTrack.onended' in that specification. Candidate Recommendation Initial specification. ...
MediaStream Image Capture API - Web APIs
the first item in the MediaStreamTrack array is the one to use. You can use the properties of the MediaStreamTrack objects to select the one you need. const track = mediaStream.getVideoTracks()[0]; At this point, you might want to configure the device capabilities before capturing an image. You can do this by calling applyConstraints() on the track object before doing anything else. let zoom = document.querySelector('#zoom'); const capabilities = track.getCapabilities(); // Check whether zoom is supported or not. if(!capabilities.zoom) { return; } track.applyConstraints({ advanced : [{ zoom: zoom.value }] }); Finally, pass the MediaStreamTrack object to the ImageCapture() constructor. Though a MediaStream holds several types of tracks and provides multiple methods for retrieving them, the I...
MediaTrackConstraints - Web APIs
or sharing. logicalSurface A ConstrainBoolean value which may contain a single Boolean value or a set of them, indicating whether or not to allow the user to choose source surfaces which do not directly correspond to display areas. These may include backing buffers for windows to allow capture of window contents that are hidden by other windows in front of them, or buffers containing larger documents that need to be scrolled through to see the entire contents in their windows. Specifications Specification Status Comment Media Capture and Streams Candidate Recommendation Initial definition. MediaStream Image Capture Working Draft Adds image constraints. ...
MediaTrackSettings.logicalSurface - Web APIs
en at once. Since the window that contains the surface has to be scrolled to show the rest of the contents, the surface is a logical one. A visible display surface (that is, a surface for which logicalSurface returns false) is the portion of a logical display surface which is currently visible onscreen. For example, a user agent may choose to allow the user to choose whether to share the entire document (a browser with logicalSurface value of true), or just the currently visible portion of the document (where the logicalSurface of the browser surface is false). Specifications Specification Status Comment Screen CaptureThe definition of 'MediaTrackSettings.logicalSurface' in that specification. Working Draft Initial definition ...
MediaTrackSupportedConstraints.aspectRatio - Web APIs
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 Recommendation Initial specificatio...
MediaTrackSupportedConstraints.autoGainControl - Web APIs
f 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. Candidate Recommendation Initial spec...
MediaTrackSupportedConstraints.channelCount - Web APIs
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 Recommendation Initial specification.
MediaTrackSupportedConstraints.deviceId - Web APIs
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 Initial specification. ...
MediaTrackSupportedConstraints.echoCancellation - Web APIs
ionary (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 Recommendation Initial specif...
MediaTrackSupportedConstraints.facingMode - Web APIs
roperty 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 Initial specification.
MediaTrackSupportedConstraints.frameRate - Web APIs
sent 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
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 Initial specification. ...
MediaTrackSupportedConstraints.height - Web APIs
n 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 Initial specification. ...
MediaTrackSupportedConstraints.latency - Web APIs
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 Initial specification. ...
MediaTrackSupportedConstraints.noiseSuppression - Web APIs
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. Candidate Recommendation Initial sp...
MediaTrackSupportedConstraints.sampleRate - Web APIs
e 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 Recommendation Initial specification. ...
MediaTrackSupportedConstraints.sampleSize - Web APIs
e 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 Recommendation Initial specification. ...
MediaTrackSupportedConstraints.volume - Web APIs
n the dictionary (and its value is always true) if the user agent supports the volume constraint. ...
MediaTrackSupportedConstraints.width - Web APIs
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 Initial specification. ...
Media Session API - Web APIs
mediaSession.setActionHandler('nexttrack', function() { /* Code excerpted. */ }); } Some user agents disable autoplay for media elements on mobile devices and require a user gesture to start media. The following example adds a pointerup event to an on-page play button, which is then used to kick off the media session code: playButton.addEventListener('pointerup', function(event) { var audio = document.querySelector('audio'); // User interacted with the page. Let's play audio... audio.play() .then(_ => { /* Set up media session controls, as shown above. */ }) .catch(error => { console.log(error) }); }); Specifications Specification Status Comment Media Session Standard Draft Initial definition. ...
MessageEvent - Web APIs
The MessageEvent interface represents a message received by a target object. This is used to represent messages in: Server-sent events (see EventSource.onmessage). Web sockets (see the onmessage property of the WebSocket interface). Cross-document messaging (see Window.postMessage() and Window.onmessage). Channel messaging (see MessagePort.postMessage() and MessagePort.onmessage). Cross-worker/document messaging (see the above two entries, but also Worker.postMessage(), Worker.onmessage, ServiceWorkerGlobalScope.onmessage, etc.) Broadcast channels (see Broadcastchannel.postMessage()) and BroadcastChannel.onmessage). WebRTC data channels (see RTCDataChannel.onmessage). The action triggered by this event is defined in a function set as the event handler for the relevant message event (e...
MessagePort.close() - Web APIs
Web › API › MessagePort › close
The close() method of the MessagePort interface disconnects the port, so it is no longer active. This stops the flow of messages to that port. Note: This feature is available in Web Workers. Syntax port.close() Returns Void. Parameters None. Example In the following code block, you can see a handleMessage handler function, run when a message is sent back to this document using EventTarget.addEventListener. channel.port1.addEventListener('message', handleMessage, false); function handleMessage(e) { para.innerHTML = e.data; textInput.value = ''; } channel.port1.start(); You could stop messages being sent at any time using channel.port1.close(); Specifications Specification Status Comment HTML Living StandardThe definition of 'close()' in that specificatio...
MessagePort: message event - Web APIs
ageEvent Event handler property onmessage Examples Suppose a script creates a MessageChannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new MessageChannel(); const myPort = channel.port1; const targetFrame = window.top.frames[1]; const targetOrigin = 'https://example.org'; const messageControl = document.querySelector('#message'); const channelMessageButton = document.querySelector('#channel-message'); channelMessageButton.addEventListener('click', () => { myPort.postMessage(messageControl.value); }) targetFrame.postMessage('init', targetOrigin, [channel.port2]); The target can receive the port and start listening for messages on it using code like this: window.addEventListener('message',...
MessagePort: messageerror event - Web APIs
ent Event handler property onmessageerror Examples Suppose a script creates a MessageChannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new MessageChannel(); const myPort = channel.port1; const targetFrame = window.top.frames[1]; const targetOrigin = 'https://example.org'; const messageControl = document.querySelector('#message'); const channelMessageButton = document.querySelector('#channel-message'); channelMessageButton.addEventListener('click', () => { myPort.postMessage(messageControl.value); }) targetFrame.postMessage('init', targetOrigin, [channel.port2]); The target can receive the port and start listening for messages and message errors on it using code like this: window.addEvent...
Microsoft API extensions - Web APIs
ereo3DPackingMode msStereo3DRenderMode onMSVideoFormatChanged onMSVideoFrameStepCompleted onMSVideoOptimalLayoutChanged msFirstPaint Pinned Sites APIs MSSiteModeEvent mssitemodejumplistitemremoved msthumbnailclick Other APIs x-ms-aria-flowfrom x-ms-acceleratorkey x-ms-format-detection msCaching msCachingEnabled msCapsLockWarningOff Event.msConvertURL() mselementresize Document.msElementsFromRect() msIsStaticHTML Navigator.msLaunchUri() msLaunchUriCallback Element.msMatchesSelector() msProtocols msPutPropertyEnabled msWriteProfilerMark ...
MimeTypeArray - Web APIs
s the MimeType object with the specified index. MimeTypeArray.namedItem() Returns the MimeType object with the specified name. Example The following example tests whether a plugin is available for the application/pdf mime type and if so, which plugin that is. var mimeTypes = navigator.MimeType; var flashPlugin = mimeTypes['video/x-flv']; if (typeof flashPlugin === "undefined") { var vid = document.createElement('video'); // Use vid.canPlayType() to test for a supported mime type. } else { // Notify the user that flash is being deprecated and they // should upgrade their browser. } Specifications Specification Status Comment HTML Living StandardThe definition of 'MimeTypeArray' in that specification. Living Standard Initial definition. ...
MouseEvent() - Web APIs
reen and client fields will throw a TypeError. The MouseEventInit dictionary also accepts fields from UIEventInit and from EventInit dictionaries. Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'MouseEvent' in that specification. Working Draft Redefines screen and client fields long to double. Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent()' in that specification. Obsolete Initial definition. ...
MouseEvent.movementX - Web APIs
eOfMouseEvent.movementX; 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.insertAdjacentHTML('afterbegin', `movement: ${event.movementX}, ${event.movementY}<br>`); while (log.childNodes.length > 128) log.lastChild.remove() } const log = document.getElementById('log'); document.addEventListener('mousemove', logMovement); Result Specifications Specification Status Comment Pointer LockThe definition of 'MouseEvent.movementX' in that specification. Candidate Recommendation Initial definition ...
MouseEvent.movementY - Web APIs
tEvent.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 Recommendation Initial definition. ...
MouseEvent.pageY - Web APIs
Web › API › MouseEvent › pageY
This property takes into account any vertical scrolling of the page. Syntax var pos = event.pageY; Originally, this property was defined as a long integer. The CSSOM View Module redefined it as a double float. See the Browser compatibility section for details. Examples var pageY = event.pageY; Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'pageY' in that specification. ...
MouseEvent.region - Web APIs
Web › API › MouseEvent › region
property returns the id of the canvas hit region affected by the event. If no hit region is affected, null is returned. Syntax var hitRegion = instanceOfMouseEvent.region Return value A DOMString representing the id of the hit region. ...
msPlayToSource - Web APIs
pe="text/javascript"> // Step 1: Obtain PlayToManager object for app's current view. var ptm = Windows.Media.PlayTo.PlayToManager.getForCurrentView(); // Step 2: Register for the sourcerequested event (user swipes Devices charm). ptm.addEventListener("sourcerequested", function(e) { // Step 3: Specify the media to be streamed (to filter devices). e.sourceRequest.setSource(document.getElementById("videoplayer").msPlayToSource); // The media will then be streamed to the device chosen by the user in the UI. }); ...
MutationObserver.MutationObserver() - Web APIs
er sees changes matching the configuration of the observation request specified when calling observe() to begin watching the DOM. The kind of change that took place (either a change to the list of children, or a change to an attribute) is detected by looking at the mutation.type property. Creating and starting the observer This code actually sets up the observation process. const targetNode = document.querySelector("#someElement"); const observerOptions = { childList: true, attributes: true, // Omit (or set to false) to observe only changes to the parent node subtree: true } const observer = new MutationObserver(callback); observer.observe(targetNode, observerOptions); The desired subtree is located by finding an element with the ID someElement. A set of options for the observer is ...
MutationObserver.disconnect() - Web APIs
ve already been detected, but not yet reported to the observer, are discarded. Usage notes If the element being observed is removed from the DOM, and then subsequently released by the browser's garbage collection mechanism, the MutationObserver is likewise deleted. Example This example creates an observer, then disconnects from it, leaving it available for possible reuse. const targetNode = document.querySelector("#someElement"); const observerOptions = { childList: true, attributes: true } const observer = new MutationObserver(callback); observer.observe(targetNode, observerOptions); /* some time later... */ observer.disconnect(); Specifications Specification Status Comment DOMThe definition of 'MutationObserver.disconnect()' in that specification. Li...
MutationObserver.observe() - Web APIs
rd objects describing the changes that occur, you should be able to "undo" the changes, rewinding the DOM back to its initial state. Example In this example, we demonstrate how to call the method observe() on an instance of MutationObserver, once it has been set up, passing it a target element and a MutationObserverInit options object. ...
MutationObserver - Web APIs
takeRecords() Removes all pending notifications from the MutationObserver's notification queue and returns them in a new Array of MutationRecord objects. Mutation Observer & customize resize event listener & demo https://codepen.io/webgeeker/full/YjrZgg/ Example The following example was adapted from this blog post. ...
MutationObserverInit.attributeFilter - Web APIs
For any items representing an attrib...
MutationObserverInit.attributeOldValue - Web APIs
away from keyboard (AFK) or offline. function callback(mutationList) { mutationList.forEach(function(mutation) { switch(mutation.type) { case "attributes": notifyUser("Attribute name " + mutation.attributeName + " changed to " + mutation.target[mutation.attributeName] + " (was " + mutation.oldValue + ")"); break; } }); } var targetNode = document.querySelector("#target"); var observer = new MutationObserver(callback); observer.observe(targetNode, { attributes: true, attributeOldValue: true }); The callback() function--which will be passed into the observe() method when starting the observer, looks at each item in the list of MutationRecord objects. For any items representing an attribute change (which can be detected by the value of...
MutationObserverInit.attributes - Web APIs
away from keyboard (AFK) or offline. function callback(mutationList) { mutationList.forEach(function(mutation) { switch(mutation.type) { case "attributes": notifyUser("Attribute name " + mutation.attributeName + " changed to " + mutation.target[mutation.attributeName] + " (was " + mutation.oldValue + ")"); break; } }); } var targetNode = document.querySelector("#target"); var observer = new MutationObserver(callback); observer.observe(targetNode, { attributes: true, attributeOldValue: true }); The callback() function--which will be passed into the observe() method when starting the observer, looks at each item in the list of MutationRecord objects. For any items representing an attribute change (which can be detected by the value of...
NameList - Web APIs
Web › API › NameList
ccessed by a 0-based index. The DOM spec does not specify how the collection is to be implemented. Properties NameList.length Read only Methods NameList.contains() Returns a Boolean. NameList.containsNS() Returns a Boolean. NameList.getName() Returns a DOMString. NameList.getNamespaceURI() Returns a DOMString. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'NameList' in that specification. Obsolete Initial definition ...
NamedNodeMap - Web APIs
Replaces, or adds, the Attr identified in the map by the given namespace and related local name. NamedNodeMap.removeNamedItemNS() Removes the Attr identified by the given namespace and related local name. Specifications Specification Status Comment DOMThe definition of 'NamedNodeMap' in that specification. Living Standard Deals with Attr instead of Node Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'NamedNodeMap' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'NamedNodeMap' in that specification. Obsolete Added getNamedItemNS(), setNamedItemNS() and removeNamedItemNS() Docum...
Navigation Timing API - Web APIs
e window's load handler, and so forth. Interfaces Performance The window.performance property returns a Performance object. While this interface is defined by the High Resolution Time API, the Navigation Timing API adds two properties: timing and navigation, of the types below. PerformanceNavigationTiming Provides methods and properties to store and retrieve metrics regarding the browser's document navigation events. For example, this interface can be used to determine how much time it takes to load or unload a document. PerformanceTiming Used as the type for the value of timing, objects of this type contain timing information that can provide insight into web page performance. PerformanceNavigation The type used to return the value of navigation, which contains information explain...
Navigator.clipboard - Web APIs
be obtained from the Permissions API using the "clipboard-read" and/or "clipboard-write" permissions. Syntax theClipboard = navigator.clipboard; Value The Clipboard object used to access the system clipboard. Examples The following code uses navigator.clipboard to access the system clipboard in order to read the contents of the clipboard. navigator.clipboard.readText().then( clipText => document.querySelector(".cliptext").innerText = clipText); This snippet replaces the contents of the element whose class is "cliptext" with the text contents of the clipboard. Perhaps this code is being used in a browser extension that displays the current clipboard contents, automatically updating periodically or when specific events fire. If the clipboard is empty or doesn't contain text, the "cliptex...
Navigator.msLaunchUri() - Web APIs
tocol. The Uniform Resource Identifier (URI) contains the protocol for the default service or app, such as mailto://test@contoso.com. This proprietary method is specific to Internet Explorer, and Microsoft Edge versions 18 and lower. Syntax navigator.msLaunchUri(uri, successCallback, noHandlerCallback); Parameters uri A DOMString specifying the URL containing including the protocol of the document or resource to be displayed. successCallbackOptional A function matching the signature of MSLaunchUriCallback to be executed if the protocol handler is present. noHandlerCallbackOptional A function matching MSLaunchUriCallback to be executed if the protocol handler is not present. Return value undefined. Usage notes If a default protocol handler is available on the system that matc...
Navigator.productSub - Web APIs
The Navigator.productSub read-only property returns the build number of the current browser. Syntax prodSub = window.navigator.productSub prodSub is a string. Example <script> function prodsub() { var dt = document.getElementById("d").childNodes[0]; dt.data = window.navigator.productSub; } </script> <button onclick="prodsub();">productSub</button> // returns: 20010725 Notes On IE, this property returns undefined. On Apple Safari and Google Chrome this property always returns 20030107. Specifications Specification Status Comment HTML Living StandardThe definition of 'NavigatorID: productSub' in that specification. Living Standard Initial definition ...
Navigator.serviceWorker - Web APIs
The feature may not be available in private mode. Syntax var workerContainerInstance = navigator.serviceWorker; Value ServiceWorkerContainer Examples This code checks if the browser supports service workers. ...
Navigator.wakeLock - Web APIs
While a screen wake lock is active, the user agent will try to prevent the device from dimming the screen, turning it off completely, or showing a screensaver. ...
Node.baseURIObject - Web APIs
It's similar to Node.baseURI, except it returns an nsIURI instead of a string. This property exists on all nodes (HTML, XUL, SVG, MathML, etc.), but only if the script trying to use it has UniversalXPConnect privileges. See Node.baseURI for details on what the base URL is. Syntax uriObj = node.baseURIObject Value An nsIURI. This property is read-only; attempting to write to it will throw an exception. ...
Node.contains() - Web APIs
Web › API › Node › contains
node itself, one of its direct children (childNodes), one of the children's direct children, and so on. Syntax node.contains( otherNode ) Example This function checks to see if an element is in the page's body. As contains is inclusive and determining if the body contains itself isn't the intention of isInPage this case explicitly returns false. function isInPage(node) { return (node === document.body) ? false : document.body.contains(node); } Specifications Specification Status Comment DOMThe definition of 'Node.contains()' in that specification. Living Standard Initial definition ...
Node.getUserData() - Web APIs
Web › API › Node › getUserData
etUserData(). The Node.setUserData and Node.getUserData methods are no longer available from Web content. Element.dataset or WeakMap can be used instead. Syntax userData = someNode.getUserData(userKey); Parameters userKey is the key to choose the specific data sought for the given node. More than one key may have been assigned on a given node, containing its own value. Example var d = document.setUserData('key', 15, null); console.log(document.getUserData('key')); // 15 Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.getUserData()' in that specification. Obsolete Initial definition. ...
Node.hasChildNodes() - Web APIs
The Node.hasChildNodes() method returns a Boolean value indicating whether the given Node has child nodes or not. Syntax bool = node.hasChildNodes(); Return value A Boolean that is true if the node has child nodes, and false otherwise. ...
Node.isDefaultNamespace() - Web APIs
is the default namespace on the given node or false if not. Syntax result = node.isDefaultNamespace(namespaceURI); Parameters namespaceURI is a string representing the namespace against which the element will be checked. Return value result is a Boolean that holds the return value true or false. Example var XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var el = document.getElementsByTagNameNS(XULNS, 'textbox')[0]; alert(el.isDefaultNamespace(XULNS)); // true Specifications Specification Status Comment DOMThe definition of 'Node: isDefaultNamespace' in that specification. Living Standard ...
Node.isSupported() - Web APIs
Web › API › Node › isSupported
OM Level 2 Conformance Section. version Is a DOMString containing the version number of the feature to test. In DOM Level 2, version 1, this is the string 2.0. If the version is not specified, supporting any version of the feature will cause the method to return true. Example <div id="doc"> </div> <script> // Get an element and check to see if its supports the DOM2 HTML Module. var main = document.getElementById('doc'); var output = main.isSupported('HTML', '2.0'); </script> Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.isSupported()' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification. Document Object Model (DOM) Level...
Node.parentNode - Web APIs
Web › API › Node › parentNode
The Node.parentNode read-only property returns the parent of the specified node in the DOM tree. Syntax parentNode = node.parentNode parentNode is the parent of the current node. The parent of an element is an Element node, a Document node, or a DocumentFragment node. Example if (node.parentNode) { // remove a node from the tree, unless // it's not in the tree already node.parentNode.removeChild(node); } Notes Document and DocumentFragment nodes can never have a parent, so parentNode will always return null. It also returns null if the node has just been created and is not yet attached to the tree. Specifications Specification Status Comment DOMThe definition of 'Node: parentNode' in that specification. Living Standard ...
Node.prefix - Web APIs
Web › API › Node › prefix
Node.prefix read-only property returns the namespace prefix of the specified node, or null if no prefix is specified. In DOM4 this API was moved from Node to the Element and Attr interfaces. Syntax string = node.prefix Examples The following logs "x" to the console. <x:div onclick="console.log(this.prefix)"/> Notes This will only work when a namespace-aware parser is used, i.e. when a document is served with an XML MIME type. This will not work for HTML documents. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.prefix' in that specification. Obsolete Specifies the behavior when it's set to null. Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'I...
Node.rootNode - Web APIs
Web › API › Node › rootNode
rns a Node object representing the topmost node in the tree, or the current node if it's the topmost node in the tree. This is found by walking backward along Node.parentNode until the top is reached. Syntax rootNode = node.rootNode; Value A Node object representing the topmost node in the tree. Example Running the following line in supporting browsers should return a reference to the HTML/document node: console.log(document.body.rootNode); Notes Gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. Therefore a node obtained, for example, using Node.firstChild or Node.previousSibling may refer to a whitespace text node rather than the actual element the author intended to get. See Whitespace in the DOM and W3C DOM 3 FAQ: Why are some Text ...
NodeIterator.pointerBeforeReferenceNode - Web APIs
The NodeIterator.pointerBeforeReferenceNode read-only property returns a Boolean flag that indicates whether the NodeFilter is anchored before (if this value is true) or after (if this value is false) the anchor node indicated by the NodeIterator.referenceNode property. Syntax flag = nodeIterator.pointerBeforeReferenceNode; Example var nodeIterator = document.createNodeIterator( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); flag = nodeIterator.pointerBeforeReferenceNode; Specifications Specification Status Comment DOMThe definition of 'NodeIterator.pointerBeforeReferenceNode' in that specification. Living Standard Initial definition. ...
NodeIterator.referenceNode - Web APIs
The NodeIterator.referenceNode read-only returns the Node to which the iterator is anchored; as new nodes are inserted, the iterator remains anchored to the reference node as specified by this property. Syntax node = nodeIterator.referenceNode; Example var nodeIterator = document.createNodeIterator( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); node = nodeIterator.referenceNode; Specifications Specification Status Comment DOMThe definition of 'NodeIterator.referenceNode' in that specification. Living Standard Initial definition. ...
NodeIterator.root - Web APIs
Web › API › NodeIterator › root
The NodeIterator.root read-only property represents the Node that is the root of what the NodeIterator traverses. Syntax root = nodeIterator.root; Example var nodeIterator = document.createNodeIterator( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); root = nodeIterator.root; // document.body in this case Specifications Specification Status Comment DOMThe definition of 'NodeIterator.root' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Specification. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'NodeIterator.root' in that specification. Obsolete Initial defi...
NodeList.item() - Web APIs
Web › API › NodeList › item
s 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. Alternate Syntax JavaScript also offers an array-like bracketed syntax for obtaining an item from a NodeList by index: nodeItem = nodeList[index] Example var tables = document.getElementsByTagName("table"); var firstTable = tables.item(1); // or simply tables[1] - returns the second table in the DOM Specifications Specification Status Comment DOMThe definition of 'NodeList: item' in that specification. Living Standard ...
Notification.close() - Web APIs
called creates an options object and then a new notification. At the end of the function, it also calls close() inside a addEventListener() function to remove the notification when the relevant content has been read on the webpage. function spawnNotification(theBody, theIcon, theTitle) { var options = { body: theBody, icon: theIcon }; var n = new Notification(theTitle,options); document.addEventListener('visibilitychange', function() { if (document.visibilityState === 'visible') { // The tab has become visible so clear the now-stale Notification. n.close(); } }); } Specifications Specification Status Comment Notifications API Living Standard Living standard ...
OVR_multiview2 - Web APIs
NE, the framebuffer is considered incomplete. Calling checkFramebufferStatus for a framebuffer in this state returns FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR. Methods framebufferTextureMultiviewOVR() Simultaneously renders to multiple elements of a 2D texture array. Examples This example is taken from the specification. See also this three.js demo for a live multiview example. ...
OscillatorNode.OscillatorNode() - Web APIs
illator() factory method instead. Syntax var oscillatorNode = new OscillatorNode(context, options) Parameters Inherits parameters from the AudioNodeOptions dictionary. context A reference to an AudioContext. options Optional An object whose properties specify the initial values for the oscillator node's properties. Any properties omitted from the object will take on the default value as documented. type The shape of the wave produced by the node. Valid values are 'sine', 'square', 'sawtooth', 'triangle' and 'custom'. The default is 'sine'. detune A detuning value (in cents) which will offset the frequency by the given amount. Its default is 0. frequency The frequency (in hertz) of the periodic waveform. Its default is 440. periodicWave An arbitrary period waveform descr...
PaintWorklet.registerPaint - Web APIs
ror Thrown when one of the arguments is invalid or missing. InvalidModificationError Thrown when the a worklet already exists with the specified name. Examples The following shows registering an example worklet module. This should be in a separate js file. Note that registerPaint() is called without a reference to PaintWorklet. The file itself is loaded through CSS.paintWorklet.addModule() (documented here on the parent class of PaintWorklet, at Worklet.addModule(). /* checkboardWorklet.js */ class CheckerboardPainter { paint(ctx, geom, properties) { // Use `ctx` as if it was a normal canvas const colors = ['red', 'green', 'blue']; const size = 32; for(let y = 0; y < geom.height/size; y++) { for(let x = 0; x < geom.width/size; x++) { const color = colors[(x ...
PannerNode.distanceModel - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
PannerNode.maxDistance - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
PannerNode.panningModel - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
PannerNode.setOrientation() - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
PannerNode.setPosition() - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
PannerNode.setVelocity() - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
PannerNode - Web APIs
tTime(0, audioCtx.currentTime); listener.forwardY.setValueAtTime(0, audioCtx.currentTime); listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime); listener.upX.setValueAtTime(0, audioCtx.currentTime); listener.upY.setValueAtTime(1, audioCtx.currentTime); listener.upZ.setValueAtTime(0, audioCtx.currentTime); } else { listener.setOrientation(0,0,-1,0,1,0); } var source; var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); var boomBox = document.querySelector('.boom-box'); var listenerData = document.querySelector('.listener-data'); var pannerData = document.querySelector('.panner-data'); leftBound = (-xPos) + 50; rightBound = xPos - 50; xIterator = WIDTH/150; // listener will always be in the same place for this demo if(listener.positionX) {...
ParentNode.children - Web APIs
ren = 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 HTMLCollection. ;(function(constructor) { if (constructor && constructor.prototype && constructor.prototype.children == null) { ...
ParentNode - Web APIs
See Locating DOM elements using selectors to learn how to use CSS selectors to find nodes or elements of interest. Properties ParentNode.childElementCount Read only Returns the number of children of this ParentNode which are elements. ParentNode.children Read only Returns a live HTMLCollection containing all of the Element objects that are children of this ParentNode, omitting all of its non-element nodes. ...
PasswordCredential - Web APIs
the form element. <form id="form" method="post"> <input type="text" name="id" autocomplete="username" /> <input type="password" name="password" autocomplete="current-password" /> <input type="hidden" name="csrf_token" value="*****" /> </form> Then, a reference to this form element, using it to create a PasswordCredential object, and storing it in the browser's password system. var form = document.querySelector('#form'); var creds = new PasswordCredential(form); // Store the credentials. navigator.credentials.store(creds) .then(function(creds) { // Do something with the credentials if you need to. }); Specifications Specification Status Comment Credential Management Level 1 Working Draft Initial definition. ...
PasswordCredential.additionalData - Web APIs
, or null. Example The following example creates a FormData object with an appended CSRF token. It then stores the form object in the additionalData parameter, before sending it to server in a call to fetch. //The options object was previously created. navigator.credentials.get(options).then(function(creds) { if (creds.type == 'password') { var form = new FormData(); var csrf_token = document.querySelector('csrf_token').value; form.append('csrf_token', csrf_token); creds.additionalData = form; fetch('https://www.example.com', { method: 'POST', credentials: creds }); }; }); Specifications Specification Status Comment Credential Management Level 1 Working Draft Initial definition. ...
PaymentDetailsBase - Web APIs
Properties displayItemsOptional An array of PaymentItem objects, each describing one line item for the payment request. These represent the line items on a receipt or invoice. modifiersOptional An array of PaymentDetailsModifier objects, each describing a modifier for particular payment method identifiers. ...
PaymentResponse.complete() - Web APIs
empty string, "", was used instead of unknown to indicate a completion without a known result state. See the Browser compatibility section below for details. Return value A Promise which resolves with no input value once the payment interface has been fully closed. If an error occurs, the promise instead rejects, returning one of the exceptions listed below. Exceptions AbortError The document in which the payment request is taking place became inactive while the user interface was shown. InvalidStateError The payment has already completed, or complete() was called while a request to retry the payment is pending. You can't treat a payment as complete after requesting that the payment be tried again. Examples The following example sends payment information to a secure server using ...
PerformanceEntry.entryType - Web APIs
entryType; Return value The return value depends on the subtype of the PerformanceEntry object and affects the value of the PerformanceEntry.name property as shown by the table below. Performance entry type names Value Subtype Type of name property Description of name property frame, navigation PerformanceFrameTiming, PerformanceNavigationTiming URL The document's address. resource PerformanceResourceTiming URL The resolved URL of the requested resource. This value doesn't change even if the request is redirected. mark PerformanceMark DOMString The name used when the mark was created by calling performance.mark(). measure PerformanceMeasure DOMString name used when the measure was created by calling p...
PerformanceEntry.name - Web APIs
e: This feature is available in Web Workers. Syntax var name = entry.name; Return value The return value depends on the subtype of the PerformanceEntry object and the value of PerformanceEntry.entryType, as shown by the table below. Value Subtype entryType values Description URL PerformanceFrameTiming, PerformanceNavigationTiming frame, navigation The document's address. URL PerformanceResourceTiming resource The resolved URL of the requested resource. This value doesn't change even if the request is redirected. DOMString PerformanceMark mark The name used when the mark was created by calling performance.mark(). DOMString PerformanceMeasure measure name used when the measure was created by calling p...
PerformanceEventTiming - Web APIs
const inputSyncProcessingTime = entry.processingEnd - entry.processingStart; }); }); // Register observer for event. observer.observe({entryTypes: ["event"]}); We can also directly query the first input delay. // Keep track of whether (and when) the page was first hidden, see: // https://github.com/w3c/page-visibility/issues/29 // NOTE: ideally this check would be performed in the document <head> // to avoid cases where the visibility state changes before this code runs. let firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity; document.addEventListener('visibilitychange', (event) => { firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp); }, {once: true}); // Sends the passed data to an analytics endpoint. This code // uses `/analytics`; you can replace...
PerformanceFrameTiming - Web APIs
="middle">PerformanceFrameTiming</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties This interface has no properties but it extends the following PerformanceEntry properties (for "frame" performance entry types) by qualifying and constraining the properties as follows: PerformanceEntry.entryType Returns "frame". PerformanceEntry.name Returns the document's address. PerformanceEntry.startTime Returns the timestamp when the frame was started. PerformanceEntry.duration Returns a timestamp indicating the difference between the startTimes of two successive frames. Methods This interface has no methods. Example See the example in Using the Frame Timing API. Specifications Specification Status Comment Frame TimingThe d...
PerformanceNavigation - Web APIs
An object of this type can be obtained by calling the Performance.navigation read-only attribute. Properties The PerformanceNavigation interface doesn't inherit any properties. ...
PerformanceNavigationTiming.redirectCount - Web APIs
.getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM complete = " + p.domComplete); console.log("DOM interactive = " + p.interactive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Specifications Specification Status Comment Navigation Timing Level 2The...
PerformanceNavigationTiming.type - Web APIs
.getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM complete = " + p.domComplete); console.log("DOM interactive = " + p.interactive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Specifications Specification Status Comment Navigation Timing Level 2The...
PerformanceObserver.observe() - Web APIs
When a matching performance entry is recorded, the performance observer's callback function--set when creating the PerformanceObserver--is invoked. ...
PerformanceResourceTiming.redirectEnd - Web APIs
The redirectEnd read-only property returns a timestamp immediately after receiving the last byte of the response of the last redirect. When fetching a resource, if there are multiple HTTP redirects, and any of the redirects have an origin that is different from the current document, and the timing allow check algorithm passes for each redirected resource, this property returns the time immediately after receiving the last byte of the response of the last redirect; otherwise, zero is returned. Note: This feature is available in Web Workers. Syntax resource.redirectEnd; Return value A timestamp immediately after receiving the last byte of the response of the last redirect. Example In the following example, the value of the *Start and *End properties of all "resource" type events are logged...
PerformanceResourceTiming.redirectStart - Web APIs
Note: This feature is available in Web Workers. ...
PerformanceTiming.domComplete - Web APIs
This interface of this property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead. The legacy PerformanceTiming.domComplete read-only property returns an unsigned long long representing the moment, in miliseconds since the UNIX epoch, when the parser finished its work on the main document, that is when its Document.readyState changes to 'complete' and the corresponding readystatechange event is thrown. Syntax time = performanceTiming.domComplete; Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceTiming.domComplete' in that specification. Recommendation Initial definition. ...
PerformanceTiming.domInteractive - Web APIs
This interface of this property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead. The legacy PerformanceTiming.domInteractive read-only property returns an unsigned long long representing the moment, in miliseconds since the UNIX epoch, when the parser finished its work on the main document, that is when its Document.readyState changes to 'interactive' and the corresponding readystatechange event is thrown. This property can be used to measure the speed of loading Web sites that users feels. Nevertheless there are a few caveats that happens if scripts are blocking rendering and not loaded asynchronously or with custom Web fonts. Check if you are in one of these cases before using this property as a proxy for the user ex...
PerformanceTiming.domLoading - Web APIs
This interface of this property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead. The legacy PerformanceTiming.domLoading read-only property returns an unsigned long long representing the moment, in miliseconds since the UNIX epoch, when the parser started its work, that is when its Document.readyState changes to 'loading' and the corresponding readystatechange event is thrown. Syntax time = performanceTiming.domLoading; Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceTiming.domLoading' in that specification. Recommendation Initial definition. ...
PerformanceTiming.fetchStart - Web APIs
This interface of this property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead. The legacy PerformanceTiming.fetchStart read-only property returns an unsigned long long representing the moment, in miliseconds since the UNIX epoch, the browser is ready to fetch the document using an HTTP request. This moment is before the check to any application cache. Syntax time = performance.timing.fetchStart; Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceTiming.fetchStart' in that specification. Recommendation Initial definition. ...
PerformanceTiming.loadEventStart - Web APIs
roperty is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface's PerformanceNavigationTiming.loadEventStart read-only property instead.. The legacy PerformanceTiming.loadEventStart read-only property returns an unsigned long long representing the moment, in miliseconds since the UNIX epoch, when the load event was sent for the current document. If this event has not yet been sent, it returns 0. Syntax time = performanceTiming.loadEventStart; Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceTiming.loadEventStart' in that specification. Recommendation Initial definition. ...
PerformanceTiming.navigationStart - Web APIs
This interface of this property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead. The legacy PerformanceTiming.navigationStart read-only property returns an unsigned long long representing the moment, in milliseconds since the UNIX epoch, right after the prompt for unload terminates on the previous document in the same browsing context. If there is no previous document, this value will be the same as PerformanceTiming.fetchStart. Syntax time = performanceTiming.navigationStart; Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceTiming.navigationStart' in that specification. Recommendation Initial definition. ...
PerformanceTiming.requestStart - Web APIs
This interface of this property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead. The legacy PerformanceTiming.requestStart read-only property returns an unsigned long long representing the moment, in miliseconds since the UNIX epoch, when the browser sent the request to obtain the actual document, from the server or from a cache. If the transport layer fails after the start of the request and the connection is reopened, this property will be set to the time corresponding to the new request. Syntax time = performanceTiming.requestStart; Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceTiming.requestStart' in that specification. Recommendation Ini...
PerformanceTiming.unloadEventEnd - Web APIs
This interface of this property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead. The legacy PerformanceTiming.unloadEventEnd read-only property returns an unsigned long long representing the moment, in miliseconds since the UNIX epoch, the unload event handler finishes. If there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value returned is 0. Syntax time = performanceTiming.unloadEventEnd; Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceTiming.unloadEventEnd' in that specification. Recommendation Initial definition. ...
PerformanceTiming.unloadEventStart - Web APIs
This interface of this property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead. The legacy PerformanceTiming.unloadEventStart read-only property returns an unsigned long long representing the moment, in miliseconds since the UNIX epoch, the unload event has been thrown. If there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value returned is 0. Syntax time = performanceTiming.unloadEventStart; Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceTiming.unloadEventStart' in that specification. Recommendation Initial definition. ...
Performance API - Web APIs
re An abstract interface for performance entries with an entry type of "measure". Entries of this type are created by calling performance.measure() to add a namedDOMHighResTimeStamp (the measure) between two marks to the browser's performance timeline. PerformanceNavigationTiming Provides methods and properties to store and retrieve high resolution timestamps or metrics regarding the browser's document navigation events. PerformanceObserver Provides methods and properties used to observe performance measurement events and be notified of new performance entries as they are recorded in the browser's performance timeline. PerformanceResourceTiming Provides methods and properties for retrieving and analyzing detailed network timing data regarding the loading of an application's resources. Spe...
Performance Timeline - Web APIs
rmance interface to support client-side latency measurements within applications. The extensions provide interfaces to retrieve performance entry metrics based on specific filter criteria. The standard also includes interfaces that allow an application to define performance observer callbacks that are notified when specific performance events are added to the browser's performance timeline. This document provides an overview of the standard's interfaces. For more details about the interfaces, see the reference pages and Using Performance Timeline. Performance extensions The Performance Timeline API extends the Performance interface with three methods that provide different mechanisms to get a set of performance records (metrics), depending on the specified filter criteria. The methods are: g...
Using the Permissions API - Web APIs
voking permissions Starting in Firefox 47, you can now revoke existing permissions, using the Permissions.revoke() method. This works in exactly the same way as the Permissions.query() method, except that it causes an existing permission to be reverted back to its default state when the promise successfully resolves (which is usually prompt). See the following code in our demo: var revokeBtn = document.querySelector('.revoke'); ... revokeBtn.onclick = function() { revokePermission(); } ... function revokePermission() { navigator.permissions.revoke({name:'geolocation'}).then(function(result) { report(result.state); }); } The revoke() function has been disabled by default starting in Firefox 51, since its design has been brought into question in the Web Applications Security W...
PointerEvent - Web APIs
vices (such as a mouse, pen or contact point on a touch-enable surface). The pointer can target a specific coordinate (or set of coordinates) on the contact surface such as a screen. A pointer's hit test is the process a browser uses to determine the target element for a pointer event. Typically, this is determined by considering the pointer's location and also the visual layout of elements in a document on screen media. Constructors PointerEvent() Creates a synthetic--and untrusted--PointerEvent. Properties This interface inherits properties from MouseEvent and Event. PointerEvent.pointerId Read only A unique identifier for the pointer causing the event. PointerEvent.width Read only The width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer. Point...
ProgressEvent.initProgressEvent() - Web APIs
ProgressEvent created that way are untrusted. Note: this method has been dropped during the standard process. It has been deprecated and removed from most implementation. Do not use it anymore, use the standard constructor, ProgressEvent(), to create a synthetic ProgressEvent Syntax Progress.initProgressEvent(typeArg, canBubbleArg, cancelableArg, lengthComputable, loaded, total); Parameters typeArg Is a DOMString identifying the specific type of animation event that occurred. ...
ProgressEvent - Web APIs
nly Is an unsigned long long representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this only represent the content itself, not headers and other overhead. Methods Also inherits methods from its parent Event. ProgressEvent.initProgressEvent() Initializes a ProgressEvent created using the deprecated Document.createEvent("ProgressEvent") method. Examples The following example adds a ProgressEvent to a new XMLHTTPRequest and uses it to display the status of the request. var progressBar = document.getElementById("p"), client = new XMLHttpRequest() client.open("GET", "magical-unicorns") client.onprogress = function(pe) { if(pe.lengthComputable) { progressBar.max = pe.total progressBar.v...
PublicKeyCredentialCreationOptions.rp - Web APIs
ch requested the credential creation (via navigator.credentials.create()). Syntax relyingPartyObj = publicKeyCredentialCreationOptions.rp Properties icon Optional An URL as a USVString value which points to an image resource which can be the logo/icon of the relying party. id A DOMString uniquely identifying a relying party. The default value of this property is the domain of the current document (e.g. "login.example.com"). It may be overridden with a suffix of the current domain (e.g. "example.com"). name A DOMString giving a human-readable name for the relying party. This property is intended for display (e.g. "Example CORP"). Examples var publicKey = { challenge: /* from the server */, rp: { name: "Example CORP", id : "login.example.com", icon: "https://login.exam...
PushManager.getSubscription() - Web APIs
the service worker registration to check for a subscription navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { // Do we already have a push message subscription? serviceWorkerRegistration.pushManager.getSubscription() .then(function(subscription) { // Enable any UI which subscribes / unsubscribes from // push messages. ...
Web Push API Notifications best practices - Web APIs
cate, but today you're happily working somewhere, and problem comes up. Say your program manager found a hiccup in the approvals and wants to get your feedback on something before she proceeds. After a few failed attempts to get your attention, they send you an email, and your email app produces a push notification that successfully alerts you, even though your mail web app is not open. In this document, we'll talk about the ethical use of web push notifications. Sometimes they can eliminate frustration and annoyance, and sometimes they can cause them, and it's up to you as a developer to make wise recommendations (and decisions) about the use of push notifications. What are you hoping to achieve with this push notification? As with everything, with great power comes great responsibility. Ever...
RTCDTMFToneChangeEvent.tone - Web APIs
DTMFSender.toneBuffer is empty). Syntax var tone = dtmfToneChangeEvent.tone; Example This example establishes a handler for the tonechange event which updates an element to display the currently playing tone in its content, or, if all tones have played, the string "<none>". dtmfSender.ontonechange = function( ev ) { let tone = ev.tone; if (tone === "") { tone = "&lt;none&gt;" } document.getElementById("playingTone").innerText = tone; }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDTMFToneChangeEvent.tone' in that specification. Candidate Recommendation Initial specification. ...
RTCDataChannel.bufferedAmount - Web APIs
ata currently queued to be sent over the data channel but have not yet been sent. Example The snippet below includes a function which changes the contents of a block with the ID "bufferSize" to a string indicating the number of bytes currently buffered on an RTCDataChannel. var dc = peerConnection.createDataChannel("File Transfer"); /* ... */ function showBufferedAmount(channel) { let el = document.getElementbyId("bufferSize"); el.innerHTML = channel.bufferedAmount + " bytes"; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.bufferedAmount' in that specification. Candidate Recommendation Initial specification. ...
RTCDataChannel.label - Web APIs
ed by the Web site or app when the data channel was created, as specified when RTCPeerConnection.createDataChannel() was called to create the channel. Example This sample creates a data channel on an RTCPeerConnection, then, some time later, sets the content of a UI element to display the channel's name. var pc = new RTCPeerConnection(); var dc = pc.createDataChannel("my channel"); /* ... */ document.getElementById("channel-name").innerHTML = "<span class='channelName'>" + dc.label + "</span>"; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.label' in that specification. Candidate Recommendation Initial specification. ...
RTCDataChannel.onclose - Web APIs
a data channel is created, then handlers for the open and close events are set up to enable and disable user interface objects based on the state of the channel. This way, the message entry field and the send button are only enabled for use when the connection is actually open. let pc = new RTCPeerConnection(); let dc = pc.createDataChannel("MessageChannel")}}; dc.onopen = function(event) { document.getElementById("messageBox").disabled = false; document.getElementById("sendButton").disabled = false; }; dc.onclose = function(event) { document.getElementById("messageBox").disabled = true; document.getElementById("sendButton").disabled = true; } /* Now negotiate the connection, etc... */ Specifications Specification Status Comment WebRTC 1.0: Real-time Com...
RTCDataChannel.onopen - Web APIs
event itself, of type Event. Example This example adds a new data channel to an existing RTCPeerConnection, myPeerConnection. It then establishes an open event handler which updates some user interface elements to prepare them for being used to send messages over the data channel. let dc = myPeerConnection.createDataChannel("Message Channel"); dc.onopen = function(event) { let messageBox = document.getElementById("messageBox"); let sendButton = document.getElementById("sendButton"); messageBox.disabled = false; messageBox.focus(); sendButton.disabled = false; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.onopen' in that specification. Candidate Recommendation I...
RTCIceCandidateStats.deleted - Web APIs
Candidate Recommendation Initial specification. ...
RTCIceCandidateStats.networkType - Web APIs
mestamp}<br>\n`; // Now the statistics for this report; we intentially drop the ones we // sorted to the top above Object.keys(report).forEach(statName => { if (statName !== "id" && statName !== "timestamp" && statName !== "type") { statsOutput += `<strong>${statName}:</strong> ${report[statName]}<br>\n`; } }); } }); document.querySelector(".stats-box").innerHTML = statsOutput; }); }, 1000); ...
RTCIceServer.url - Web APIs
Web › API › RTCIceServer › url
This property has been removed from the specification; while it's still supported by many browsers, it should no longer be used. ...
RTCPeerConnection.addIceCandidate() - Web APIs
ucted from a message received over the signaling channel, describing a newly received ICE candidate that's ready to be delivered to the local ICE agent. If no candidate object is specified, or its value is null, an end-of-candidates signal is sent to the remote peer using the end-of-candidates a-line, formatted simply like this: a=end-of-candidates Deprecated parameters In older code and documentation, you may see a callback-based version of this function. This has been deprecated and its use is strongly discouraged. You should update any existing code to use the Promise-based version of addIceCandidate() instead. The parameters for this form of addIceCandidate() are described below, to aid in updating existing code. successCallback A function to be called when the ICE candidate has...
RTCPeerConnection.connectionState - Web APIs
ng", "checking", "failed", or "disconnected", or all of the connection's transports are in the "closed" state. "connecting" One or more of the ICE transports are currently in the process of establishing a connection; that is, their RTCIceConnectionState is either "checking" or "connected", and no transports are in the "failed" state. <<< Make this a link once I know where that will be documented "connected" Every ICE transport used by the connection is either in use (state "connected" or "completed") or is closed (state "closed"); in addition, at least one transport is either "connected" or "completed". "disconnected" At least one of the ICE transports for the connection is in the "disconnected" state and none of the other transports are in the state "failed", "...
RTCPeerConnection.createAnswer() - Web APIs
sent to the source of the offer to continue the negotiation process. Syntax aPromise = RTCPeerConnection.createAnswer([options]); RTCPeerConnection.createAnswer(successCallback, failureCallback[, options]); Parameters options Optional An object which contains options which customize the answer; this is based on the RTCAnswerOptions dictionary. Deprecated parameters In older code and documentation, you may see a callback-based version of this function. This has been deprecated and its use is strongly discouraged. You should update any existing code to use the Promise-based version of createAnswer() instead. The parameters for this form of createAnswer() are described below, to aid in updating existing code. successCallback An RTCSessionDescriptionCallback which will be passed a...
RTCPeerConnection.createOffer() - Web APIs
y sending audio data when there's actually something to broadcast. However, in some cases, this is unwanted. For example, in the case of music or other non-voice transmission, this can cause loss of important low-volume sounds. Also, emergency calls should never cut audio when quiet. This option defaults to true (voice activity detection enabled). Deprecated parameters In older code and documentation, you may see a callback-based version of this function. This has been deprecated and its use is strongly discouraged. You should update any existing code to use the Promise-based version of createOffer() instead. The parameters for this form of createOffer() are described below, to aid in updating existing code. successCallback An RTCSessionDescriptionCallback which will be passed a s...
RTCPeerConnection.onaddstream - Web APIs
t doesn't wait for a particular stream to be accepted or rejected using SDP negotiation. Example This code, based on an older version of our Signaling and video calling sample, responds to addstream events by setting the video source for a <video> element to the stream specified in the event, and then enabling a "hang up" button in the app's user interface. pc.onaddstream = function(event) { document.getElementById("received_video").srcObject = event.stream; document.getElementById("hangup-button").disabled = false; }; You can also use addEventListener() to add a handler for addstream events to an RTCPeerConnection. ...
RTCPeerConnection.onicegatheringstatechange - Web APIs
w information. The status is simply presented as text in a <div> element: <div id="iceStatus"></div> The actual event handler looks like this: pc.onicegatheringstatechange = function() { let label = "Unknown"; switch(pc.iceGatheringState) { case "new": case "complete": label = "Idle"; break; case "gathering": label = "Determining route"; break; } document.getElementById("iceStatus").innerHTML = label; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.onicegatheringstatechange' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.ontrack - Web APIs
k object representing the new track, the RTCRtpReceiver and RTCRtpTransceiver, and a list of MediaStream objects which indicates which stream or streams the track is part of.. Example This example, taken from the code for the article Signaling and video calling, connects the incoming track to the <video> element which will be used to display the incoming video. pc.ontrack = function(event) { document.getElementById("received_video").srcObject = event.streams[0]; document.getElementById("hangup-button").disabled = false; }; The first line of our ontrack event handler takes the first stream in the incoming track and sets the srcobject attribute to that. This connects that stream of video to the element so that it begins to be presented to the user. The second line of code simply enables a "...
RTCPeerConnection.removeStream() - Web APIs
negotiationneeded is sent on the RTCPeerConnection. ...
RTCPeerConnection.removeTrack() - Web APIs
InvalidStateError The connection is not open. Example This example adds a video track to a connection and sets up a listener on a close button which removes the track when the user clicks the button. var pc, sender; navigator.getUserMedia({video: true}, function(stream) { pc = new RTCPeerConnection(); var track = stream.getVideoTracks()[0]; sender = pc.addTrack(track, stream); }); document.getElementById("closeButton").addEventListener("click", function(event) { pc.removeTrack(sender); pc.close(); }, false); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.removeTrack()' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.setLocalDescription() - Web APIs
illment handler receives no input parameters. The process of changing descriptions actually involves intermediary steps handled by the WebRTC layer to ensure that an active connection can be changed without losing the connection if the change does not succeed. See Pending and current descriptions in WebRTC connectivity for more details on this process. Deprecated parameters In older code and documentation, 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. successCallbac...
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
function itself. It takes as input the RTCPeerConnection being tested, calls getStats() to get a new RTCStatsReport with current statistics, then computes the results it's looking for, outputting those results as appropriate to the user by appending appropriate HTML to the contents of the <div> element whose class is stats-box. ...
RTCRtpCodecParameters - Web APIs
to being the type of the RTCRtpParameters.codecs property, it's used when calling RTCRtpTransceiver.setCodecPreferences() to configure a transceiver's codecs before beginning the offer/answer process to establish a WebRTC peer connection. Most of the fields in this property take values which are defined and maintained by the Internet Assigned Numbers Authority (IANA). References to relevant IANA documents are provided in the see also section at the end of this article. Properties payloadType Optional The RTP payload type used to identify this codec. mimeType Optional The codec's MIME media type and subtype specified as a DOMString of the form "type/subtype". IANA maintains a registry of valid MIME types. clockRate Optional An unsigned long integer value specifying the codec's clock rate ...
RTCRtpReceiver.getStats() - Web APIs
r 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 lost. receiver.getStats().then(function(stats) { document.getElementById("lostpackets").innerText = stats.packetsLost; }); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpReceiver.getStats()' in that specification. Candidate Recommendation Initial specification. ...
RTCRtpReceiver.getSynchronizationSources() - Web APIs
on source) identifier received by the current RTCRtpReceiver in the last ten seconds. Syntax var rtcRtpContributingSources = rtcRtpReceiver.getContributingSources() Parameters None. Return value An array of RTCRtpSynchronizationSource instances. Each instance describes one of the synchronization sources that provided data to the incoming stream in the past ten seconds. As you'll see in the documentarion for RTCRtpSynchronizationSource, it inherits the properties of RTCRtpContributingSource, including timestamp, source, and audioLevel. The synchronization source objects add a voiceActivityFlag property, which indicates if the last RTP packet received contained voice activity. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between Br...
RTCRtpSender.getStats() - Web APIs
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 the current round trip time for requests on the sender. sender.getStats().then(function(stats) { document.getElementById("currentRTT").innerText = stats.roundTripTime; }); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpSender.getStats()' in that specification. Candidate Recommendation Initial specification. ...
RTCTrackEvent - Web APIs
l addTrack() to add a track to the far end of the connection, thereby triggering a track event on the remote peer. Example This simple example creates an event listener for the track event which sets the srcObject of the <video> element with the ID videobox to the first stream in the list passed in the event's streams array. peerConnection.addEventListener("track", e => { let videoElement = document.getElementById("videobox"); videoElement.srcObject = e.streams[0]; }, false); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCTrackEvent' in that specification. Candidate Recommendation Initial specification. ...
RadioNodeList.value - Web APIs
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.cloneRange() - Web APIs
Web › API › Range › cloneRange
The Range.cloneRange() method returns a Range object with boundary points identical to the cloned Range. The returned clone is copied by value, not reference, so a change in either Range does not affect the other. Syntax clone = range.cloneRange(); Example range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); clone = range.cloneRange(); Specifications Specification Status Comment DOMThe definition of 'Range.cloneRange()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.cloneRange()' in that specification. Obsolete Initial specification. ...
Range.collapse() - Web APIs
Web › API › Range › collapse
e of its boundary points. A collapsed Range is empty, containing no content, specifying a single-point in a DOM tree. To determine if a Range is already collapsed, see the Range.collapsed property. Syntax range.collapse(toStart); Parameters toStart Optional A Boolean value: true collapses the Range to its start, false to its end. If omitted, it defaults to false . Example var range = document.createRange(); referenceNode = document.getElementsByTagName("div").item(0); range.selectNode(referenceNode); range.collapse(true); Specifications Specification Status Comment DOMThe definition of 'Range.collapse()' in that specification. Living Standard The parameter is now optional and default to false. Document Object Model (DOM) Level 2 Traversal and...
Range.collapsed - Web APIs
Web › API › Range › collapsed
ng whether the start and end points of the Range are at the same position. It returns true if the start and end boundary points of the Range are the same point in the DOM, false if not. A collapsed Range is empty (containing no content), and specifies a single point in a DOM tree. To collapse a range, see the Range.collapse() method. Syntax isCollapsed = range.collapsed; Example let range = document.createRange(); range.setStart(startNode, startOffset); range.setEnd(endNode, endOffset); isCollapsed = range.collapsed; Specifications Specification Status Comment DOMThe definition of 'Range.collapsed' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.collapsed...
Range.comparePoint() - Web APIs
r of characters from the start of reference node. For other Node types, offset is the number of child nodes between the start of the reference node. Syntax returnValue = range.comparePoint(referenceNode, offset) Parameters referenceNode The Node to compare with the Range. offset An integer greater than or equal to zero representing the offset inside the referenceNode. Example range = document.createRange(); range.selectNode(document.getElementsByTagName('div').item(0)); returnValue = range.comparePoint(document.getElementsByTagName('p').item(0), 1); Specification Specification Status Comment DOMThe definition of 'Range.comparePoint()' in that specification. Living Standard Initial specification. ...
Range.deleteContents() - Web APIs
The Range.deleteContents() method removes the contents of the Range from the Document. Unlike Range.extractContents(), this method does not return a DocumentFragment containing the deleted content. Syntax range.deleteContents() Example range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); range.deleteContents(); Specifications Specification Status Comment DOMThe definition of 'Range.deleteContents()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.deleteContents()' in that specification. Obsolete Initial specification. ...
Range.detach() - Web APIs
Web › API › Range › detach
The Range.detach() method does nothing. It used to disable the Range object and enable the browser to release associated resources. The method has been kept for compatibility. Syntax range.detach(); Example var range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); range.detach(); Specifications Specification Status Comment DOMThe definition of 'Range.detach()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.detach()' in that specification. Obsolete Initial specification. ...
Range.endContainer - Web APIs
The Range.endContainer read-only property returns the Node within which the Range ends. To change the end position of a node, use the Range.setEnd() method or a similar one. Syntax endRangeNode = range.endContainer; Example var range = document.createRange(); range.setStart(startNode,startOffset); range.setEnd(endNode,endOffset); endRangeNode = range.endContainer; Specifications Specification Status Comment DOMThe definition of 'Range.endContainer' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.endContainer' in that specification. Obsolete Initial specification. ...
Range.endOffset - Web APIs
Web › API › Range › endOffset
number of characters from the start of the endContainer to the boundary point of the Range. For other Node types, the endOffset is the number of child nodes between the start of the endContainer and the boundary point of the Range. This property is read-only. To change the endOffset of a Range, use one of the Range.setEnd methods. Syntax endRangeOffset = range.endOffset; Example var range = document.createRange(); range.setStart(startNode,startOffset); range.setEnd(endNode,endOffset); endRangeOffset = range.endOffset; Specifications Specification Status Comment DOMThe definition of 'Range.endOffset' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.endOffset...
Range.getClientRects() - Web APIs
The Range.getClientRects() method returns a list of DOMRect objects representing the area of the screen occupied by the range. This is created by aggregating the results of calls to Element.getClientRects() for all the elements in the range. Syntax rectList = range.getClientRects() Example range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); rectList = range.getClientRects(); Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'Range.getClientRects()' in that specification. Working Draft Initial specification. ...
Range.intersectsNode() - Web APIs
The Range.intersectsNode() method returns a boolean indicating whether the given Node intersects the Range. Syntax bool = range.intersectsNode( referenceNode ) Parameters referenceNode The Node to compare with the Range. Example var range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); var bool = range.intersectsNode(document.getElementsByTagName("p").item(0)); Specification Specification Status Comment DOMThe definition of 'Range.intersectNode()' in that specification. Living Standard Initial definition. ...
Range.isPointInRange() - Web APIs
ge() method returns a boolean indicating whether the given point is in the Range. It returns true if the point (cursor position) at offset within ReferenceNode is within this range. Syntax bool = range.isPointInRange( referenceNode, offset ) Parameters referenceNode The Node to compare with the Range. offset The offset into Node of the point to compare with the Range. Example range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); bool = range.isPointInRange(document.getElementsByTagName("p").item(0),1); Specification Specification Status Comment DOMThe definition of 'Range.isPointInRange()' in that specification. Living Standard Initial definition. ...
Range.selectNode() - Web APIs
Web › API › Range › selectNode
The Range.selectNode() method sets the Range to contain the Node and its contents. The parent Node of the start and end of the Range will be the same as the parent of the referenceNode. Syntax range.selectNode(referenceNode); Parameters referenceNode The Node to select within a Range. Example let range = document.createRange(); let referenceNode = document.getElementsByTagName('div').item(0); range.selectNode(referenceNode); Specifications Specification Status Comment DOMThe definition of 'Range.selectNode()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.selectNode()' in that specification. Obsolete Initial specification. ...
Range.setEndAfter() - Web APIs
Web › API › Range › setEndAfter
The Range.setEndAfter() method sets the end position of a Range relative to another Node. The parent Node of end of the Range will be the same as that for the referenceNode. Syntax range.setEndAfter(referenceNode); Parameters referenceNode The Node to end the Range after. Example var range = document.createRange(); var referenceNode = document.getElementsByTagName('div').item(0); range.setEndAfter(referenceNode); Specifications Specification Status Comment DOMThe definition of 'Range.setEndAfter()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.setEndAfter()' in that specification. Obsolete Initial specification. ...
Range.setEndBefore() - Web APIs
The Range.setEndBefore() method sets the end position of a Range relative to another Node. The parent Node of end of the Range will be the same as that for the referenceNode. Syntax range.setEndBefore(referenceNode); Parameters referenceNode The Node to end the Range before. Example var range = document.createRange(); var referenceNode = document.getElementsByTagName("div").item(0); range.setEndBefore(referenceNode); Specifications Specification Status Comment DOMThe definition of 'Range.setEndBefore()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.setEndBefore()' in that specification. Obsolete Initial specification. ...
Range.setStartAfter() - Web APIs
The Range.setStartAfter() method sets the start position of a Range relative to a Node. The parent Node of the start of the Range will be the same as that for the referenceNode. Syntax range.setStartAfter(referenceNode); Parameters referenceNode The Node to start the Range after. Example var range = document.createRange(); var referenceNode = document.getElementsByTagName("div").item(0); range.setStartAfter(referenceNode); Specifications Specification Status Comment DOMThe definition of 'Range.setStartAfter()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.setStartAfter()' in that specification. Obsolete Initial specification. ...
Range.setStartBefore() - Web APIs
The Range.setStartBefore() method sets the start position of a Range relative to another Node. The parent Node of the start of the Range will be the same as that for the referenceNode. Syntax range.setStartBefore(referenceNode); Parameters referenceNode The Node before which the Range should start. Example var range = document.createRange(); var referenceNode = document.getElementsByTagName("div").item(0); range.setStartBefore(referenceNode); Specifications Specification Status Comment DOMThe definition of 'Range.setStartBefore()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.setStartBefore()' in that specification. Obsolete Initial specific...
Range.startContainer - Web APIs
The Range.startContainer read-only property returns the Node within which the Range starts. To change the start position of a node, use one of the Range.setStart() methods. Syntax startRangeNode = range.startContainer; Example range = document.createRange(); range.setStart(startNode,startOffset); range.setEnd(endNode,endOffset); startRangeNode = range.startContainer; Specifications Specification Status Comment DOMThe definition of 'Range.endContainer' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.startContainer' in that specification. Obsolete Initial specification. ...
Range.startOffset - Web APIs
Web › API › Range › startOffset
hen the offset is the number of characters from the start of the startContainer to the boundary point of the Range. For other Node types, the startOffset is the number of child nodes between the start of the startContainer and the boundary point of the Range. To change the startOffset of a Range, use the Range.setStart method. Syntax startRangeOffset = range.startOffset; Example var range = document.createRange(); range.setStart(startNode,startOffset); range.setEnd(endNode,endOffset); var startRangeOffset = range.startOffset; Specifications Specification Status Comment DOMThe definition of 'Range.startOffset' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range...
Range.surroundContents() - Web APIs
xt 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 (DOM) Level 2 Traversal and...
ReadableStream.ReadableStream() - Web APIs
ed, the stream is closed using ReadableStreamDefaultController.close(), and another function is run, which reads the data back out of the stream. ...
ReadableStream.getReader() - Web APIs
lt objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = value; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild(listItem); result += chunk; // Read some more, and call this function again return reader.read().then(processText); }); } Specifications Specification Status Comment StreamsThe definition of 'getReader()' in t...
ReadableStream.tee() - Web APIs
t({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Read ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list.appendChild(listItem); // Read some more, and call this function again return reader.read().then(processText); }); } Specifications Specification Status Comment StreamsThe definition of 'tee()' in that specification. Living Stan...
ReadableStreamDefaultController.close() - Web APIs
ed, the stream is closed using ReadableStreamDefaultController.close(), and another function is run, which reads the data back out of the stream. ...
ReadableStreamDefaultController.enqueue() - Web APIs
ed, the stream is closed using ReadableStreamDefaultController.close(), and another function is run, which reads the data back out of the stream. ...
ReadableStreamDefaultController - Web APIs
ed, the stream is closed using ReadableStreamDefaultController.close(), and another function is run, which reads the data back out of the stream. ...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
t objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild(listItem); result += chunk; // Read some more, and call this function again return reader.read().then(processText); }); } Specifications Specification Status Comment StreamsThe definition of 'ReadableStreamDef...
ReadableStreamDefaultReader.cancel() - Web APIs
roperties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); reader.cancel(); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild(listItem); result += chunk; // Read some more, and call this function again return reader.read().then(processText); }); } Specifications Specification Status Comment StreamsThe definition of 'cancel()' in that...
ReadableStreamDefaultReader.read() - Web APIs
t objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild(listItem); result += chunk; // Read some more, and call this function again return reader.read().then(processText); }); } Example 2 - handling text line by line This example shows how you might fetch a text file and handle it as a st...
Report.url - Web APIs
Web › API › Report › url
The url read-only property of the Report interface returns the URL of the document that generated the report. Syntax let reportURL = reportInstance.url Returns A string representing the URL of the document that generated the report. Examples let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { let firstReport = reports[0]; // Log the URL of the document that generated the first report // e.g. "https://www.example.com/cats.html" console.log(firstReport.url); }, options); Specifications Specification Status Comment Reporting APIThe definition of 'Report.url' in that specification. Editor's Draft ...
Request.destination - Web APIs
script> elements, as well as any of the Worklet-based destinations (including AudioWorklet and PaintWorklet), and the Worker-based destinations, including ServiceWorker and SharedWorker. Syntax var destination = request.destination; Value A string from the RequestDestination enumerated type which indicates the type of content the request is asking for. This type is much broader than the usual document type values (such as "document" or "manifest"), and may include contextual cues such as "image" or "worker" or "audioworklet". Example In the following snippet, we create a new request using the Request() constructor (for an image file in the same directory as the script), then save the request's destination: var myRequest = new Request('flowers.jpg'); var myDestination = myRequest.destination...
Request.mode - Web APIs
Web › API › Request › mode
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 are exposed in the Response, but the body is readable. navigate -- A mode for supporting navigation. The navigate value is intended to be used only by HTML navigation. A navigate request is created only while navigating between documents. Default mode Requests can be initiated in a variety of ways, and the mode for a request depends on the particular means by which it was initiated. For example, when a Request object is created using the Request.Request constructor, the value of the mode property for that Request is set to cors. However, for requests created other than by the Request.Request constructor, no-cors is typi...
RequestDestination - Web APIs
potential types of content that a request may try to retrieve. Values "" The default value of destination is used for destinations that do not have their own value. navigator.sendBeacon(), EventSource, <a ping>, <area ping>, fetch(), XMLHttpRequest, WebSocket, Cache and more. "audio" The target is audio data. "audioworklet" The target is data being fetched for use by an audio worklet. "document" The target is a document (HTML or XML). "embed" The target is embedded content. "font" The target is a font. "image" The target is an image. "manifest" The target is a manifest. "object" The target is an object. "paintworklet" The target is a paint worklet. "report" The target is a report. "script" The target is a script. "serviceworker" The target is a service worker. "share...
ResizeObserverEntry.borderBoxSize - Web APIs
Editor's Draft Initial definition. ...
ResizeObserverEntry.contentBoxSize - Web APIs
Editor's Draft Initial definition. ...
ResizeObserverEntry.target - Web APIs
Editor's Draft Initial definition. ...
Resize Observer API - Web APIs
...
Using the Resource Timing API - Web APIs
. The interface's properties create a resource loading timeline with high-resolution timestamps for network events such as redirect start and end times, fetch start, DNS lookup start and end times, response start and end times, etc. The interface also includes other properties that provide data about the size of the fetched resource as well as the type of resource that initiated the fetch. This document shows the use of Resource Timing interfaces. For more details about the interfaces, including examples, see each interface's reference page and the references in the See also section. A live version of the examples is available on Github, as is the source code. Pull requests and bug reports are welcome. Resource loading phases An application can get timestamps for the various phases of resourc...
Resource Timing API - Web APIs
The interface's properties create a resource loading timeline with high-resolution timestamps for network events such as redirect start and end times, DNS lookup start and end times, request start, response start and end times, etc. The interface also includes other properties that provide data about the size of the fetched resource as well as the type of resource that initiated the fetch. This document provides an overview of the Resource Timing interfaces. For more details about the interfaces including examples see each interface's reference page, Using the Resource Timing API, and the references in the See also section. For a graphical representation of the resource timing processing model see the resource timing phases figure. The PerformanceResourceTiming interface extends the Performance...
Response.headers - Web APIs
Web › API › Response › headers
see Fetch Response live) we create a new Request object using the Request() constructor, passing it a JPG path. We then fetch this request using fetch(), extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch() block we log the response headers value to the console. ...
Response.ok - Web APIs
Web › API › Response › ok
ample (see Fetch Response live) we create a new Request object using the Request() constructor, passing it a JPG path. We then fetch this request using fetch(), extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note: at the top of the fetch() block we log the response ok value to the console. ...
Response.status - Web APIs
Web › API › Response › status
(see Fetch Response live) we create a new Request object using the Request() constructor, passing it a JPG path. We then fetch this request using fetch(), extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch() block we log the response status value to the console. ...
Response.statusText - Web APIs
Fetch Response live) we create a new Request object using the Request() constructor, passing it a JPG path. We then fetch this request using fetch(), extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch() block we log the response statusText value to the console. ...
Response.type - Web APIs
Web › API › Response › type
example (see Fetch Response live) we create a new Request object using the Request() constructor, passing it a JPG path. We then fetch this request using fetch(), extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch() block we log the response type to the console. ...
Response.url - Web APIs
Web › API › Response › url
example (see Fetch Response live) we create a new Request object using the Request() constructor, passing it a JPG path. We then fetch this request using fetch(), extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch() block we log the response URL to the console. ...
Response - Web APIs
Web › API › Response
fetch example (run example live) we use a simple fetch() call to grab an image and display it in an <img> element. The fetch() call returns a promise, which resolves to the Response object associated with the resource fetch operation. You'll notice that since we are requesting an image, we need to run Body.blob (Response implements Body) to give the response its correct MIME type. ...
SVGAElement.target - Web APIs
The SVGAElement.target read-only property of SVGAElement returns an SVGAnimatedString object that specifies the portion of a target window, frame, pane into which a document is to be opened when a link is activated. This property is used when there are multiple possible targets for the ending resource, like when the parent document is a mlti-frame HTML or XHTML document. Syntax myLink.target = 'value'; Value An SVGAnimatedString indicating the ending resource target that opens the document when the link is activated. Sample values can be found here Example The code is taken from the "SVGAElement example code" ... var linkRef = document.querySelector('a'); linkRef.target ='_blank'; ... Specifications Specification Status Comment Scalable Vector Graphics (SVG) 1...
SVGAElement - Web APIs
Element.type Is a DOMString that reflects the type attribute, indicating the MIME type of the linked resource. Methods This interface has no methods but inherits methods from its parent, SVGGraphicsElement. Example In the example below, the target attribute of the <a> element is set to _blank and when the link is clicked, it logs to notify whether the condition is met or not. ...
SVGAnimatedAngle - Web APIs
SVG animated angle interface The SVGAnimatedAngle interface is used for attributes of basic type <angle> which can be animated. Interface overview Also implement None Methods None Properties readonly SVGAngle baseVal readonly SVGAngle animVal Normative document SVG 1.1 (2nd Edition) Properties Name Type Description baseVal SVGAngle The base value of the given attribute before applying any animations. animVal SVGAngle A read only SVGAngle representing the current animated value of the given attribute. If the given attribute is not currently being animated, then the SVGAngle will have the same contents as baseVal. The object referenced by animVal will always be distin...
SVGAnimatedBoolean - Web APIs
SVG animated boolean interface The SVGAnimatedBoolean interface is used for attributes of type boolean which can be animated. Interface overview Also implement None Methods None Properties readonly boolean baseVal readonly boolean animVal Normative document SVG 1.1 (2nd Edition) Properties Name Type Description baseVal boolean The base value of the given attribute before applying any animations. animVal boolean If the given attribute or property is being animated, contains the current animated value of the attribute or property. If the given attribute or property is not currently being animated, contains the same value as baseVal. Methods The SVGAnimatedBool...
SVGAnimatedEnumeration - Web APIs
SVG animated enumeration interface The SVGAnimatedEnumeration interface is used for attributes whose value must be a constant from a particular enumeration and which can be animated. Interface overview Also implement None Methods None Properties unsigned short baseVal readonly unsigned short animVal Normative document SVG 1.1 (2nd Edition) Properties Name Type Description baseVal unsigned short The base value of the given attribute before applying any animations. animVal unsigned short If the given attribute or property is being animated, contains the current animated value of the attribute or property. If the given attribute or property is not currently being anima...
SVGAnimatedInteger - Web APIs
SVG animated integer interface The SVGAnimatedInteger interface is used for attributes of basic type <integer> which can be animated. Interface overview Also implement None Methods None Properties readonly long baseVal readonly long animVal Normative document SVG 1.1 (2nd Edition) Properties Name Type Description baseVal long The base value of the given attribute before applying any animations. animVal long If the given attribute or property is being animated, contains the current animated value of the attribute or property. If the given attribute or property is not currently being animated, contains the same value as baseVal. Methods The SVGAnimatedInteger ...
SVGAnimatedLength - Web APIs
SVG animated length interface The SVGAnimatedLength interface is used for attributes of basic type <length> which can be animated. Interface overview Also implement None Methods None Properties readonly SVGLength baseVal readonly SVGLength animVal Normative document SVG 1.1 (2nd Edition) Properties Name Type Description baseVal SVGLength The base value of the given attribute before applying any animations. animVal SVGLength If the given attribute or property is being animated, contains the current animated value of the attribute or property. If the given attribute or property is not currently being animated, contains the same value as baseVal. Methods The SV...
SVGAnimatedLengthList - Web APIs
SVG animated length list interface The SVGAnimatedLengthList interface is used for attributes of type SVGLengthList which can be animated. Interface overview Also implement None Methods None Properties readonly SVGLengthList baseVal readonly SVGLengthList animVal Normative document SVG 1.1 (2nd Edition) Properties Name Type Description baseVal SVGLengthList The base value of the given attribute before applying any animations. animVal SVGLengthList A read only SVGLengthList representing the current animated value of the given attribute. If the given attribute is not currently being animated, then the SVGLengthList will have the same contents as baseVal. The object re...
SVGAnimatedNumber - Web APIs
SVG animated number interface The SVGAnimatedNumber interface is used for attributes of basic type <Number> which can be animated. Interface overview Also implement None Methods None Properties float baseVal readonly float animVal Normative document SVG 1.1 (2nd Edition) Properties Name Type Description baseVal float The base value of the given attribute before applying any animations. animVal float If the given attribute or property is being animated, contains the current animated value of the attribute or property. If the given attribute or property is not currently being animated, contains the same value as baseVal. Methods The SVGAnimatedNumber interface...
SVGAnimatedNumberList - Web APIs
SVG animated number list interface The SVGAnimatedNumber interface is used for attributes which take a list of numbers and which can be animated. Interface overview Also implement None Methods None Properties readonly SVGNumberList baseVal readonly SVGNumberList animVal Normative document SVG 1.1 (2nd Edition) Properties SVGAnimatedNumberList.baseVal Read only Is a SVGNumberList that represents the base value of the given attribute before applying any animations. SVGAnimatedNumberList.animVal Read only Is a read only SVGNumberList that represents the current animated value of the given attribute. If the given attribute is not currently being animated, then the SVGNumberList will have the same contents as b...
SVGAnimatedPathData - Web APIs
Name Type Description animatedNormalizedPathSegList SVGPathSegList Provides access to the current animated content...
SVGAnimatedPoints - Web APIs
, the points attribute on the original element accessed via the XML DOM (e.g., using the getAttribute() method call) will reflect any changes made to the SVGAnimatedPoints.points attribut. Interface overview Also implement None Methods None Properties readonly SVGPointList points readonly SVGPointList animatedPoints Normative document SVG 1.1 (2nd Edition) Properties Name Type Description points SVGPointList Provides access to the base (i.e., static) contents of the points attribute. animatedPoints SVGPointList Provides access to the current animated contents of the points attribute. If the given attribute or property is being animated, contains the current animated v...
SVGAnimatedPreserveAspectRatio - Web APIs
SVG animated preserveAspectRatio interface The SVGAnimatedPreserveAspectRatio interface is used for attributes of type SVGPreserveAspectRatio which can be animated. Interface overview Also implement None Methods None Properties readonly float baseVal readonly float animVal Normative document SVG 1.1 (2nd Edition) Properties SVGAnimatedPreserveAspectRatio.baseVal Read only Is a SVGPreserveAspectRatio that represents the base value of the given attribute before applying any animations. SVGAnimatedPreserveAspectRatio.animVal Read only Is a SVGPreserveAspectRatio that represents the current animated value of the given attribute. If the given attribute is not currently being animated, then the SVGPreserveAspectR...
SVGAnimatedRect - Web APIs
The SVGAnimatedRect interface is used for attributes of basic SVGRect which can be animated. Interface overview Also implement None Methods None Properties readonly SVGRect baseVal readonly SVGRect animVal Normative document SVG 1.1 (2nd Edition) Properties Name Type Description baseVal SVGRect The base value of the given attribute before applying any animations. animVal SVGRect A read only SVGRect representing the current animated value of the given attribute. If the given attribute is not currently being animated, then the SVGRect will have the same contents as baseVal. The object referenced by animVal will always be distinct from the one referenced by baseVal, eve...
SVGAnimatedTransformList - Web APIs
SVG animated transform list interface The SVGAnimatedTransformList interface is used for attributes which take a list of numbers and which can be animated. Interface overview Also implement None Methods None Properties readonly SVGTransformList baseVal readonly SVGTransformList animVal Normative document SVG 1.1 (2nd Edition) Properties Name Type Description baseVal SVGTransformList The base value of the given attribute before applying any animations. animVal SVGTransformList A read only SVGTransformList representing the current animated value of the given attribute. If the given attribute is not currently being animated, then the SVGTransformList will have the same...
SVGAnimationElement: beginEvent event - Web APIs
2000/svg" width="300px" height="100px"> <title>SVG SMIL Animate with Path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animateMotion path="M 0 0 H 300 Z" dur="5s" repeatCount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgElem = document.querySelector('svg'); let animateElem = document.querySelector('animateMotion'); let list = document.querySelector('ul'); animateElem.addEventListener('beginEvent', () => { let listItem = document.createElement('li'); listItem.textContent = 'beginEvent fired'; list.appendChild(listItem); }) animateElem.addEventListener('repeatEvent', (e) => { let listItem = document.createElement('li')...
SVGAnimationElement: repeatEvent event - Web APIs
2000/svg" width="300px" height="100px"> <title>SVG SMIL Animate with Path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animateMotion path="M 0 0 H 300 Z" dur="5s" repeatCount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgElem = document.querySelector('svg'); let animateElem = document.querySelector('animateMotion'); let list = document.querySelector('ul'); animateElem.addEventListener('beginEvent', () => { let listItem = document.createElement('li'); listItem.textContent = 'beginEvent fired'; list.appendChild(listItem); }) animateElem.addEventListener('repeatEvent', (e) => { let listItem = document.createElement('li');...
cx - Web APIs
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 specification. Recommendation...
cy - Web APIs
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 specification. Recommendation...
r - Web APIs
d 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 specification. Recommendation ...
SVGCircleElement - Web APIs
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. ...
SVGElement: resize event - Web APIs
This event is only applicable to outermost SVG elements and is dispatched after the resize operation has taken place. This basically implements the standard resize DOM event. Bubbles No Cancelable No Interface SVGEvent Event handler property onresize Examples svgElem.addEventListener('resize', () => { console.log('SVG resized.'); }) Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'event changes in SVG2' in that specification. ...
SVGElement: scroll event - Web APIs
This basically implements the standard scroll DOM event. Bubbles No Cancelable No Interface SVGEvent Event handler property onscroll Examples svgElem.addEventListener('scroll', () => { console.log('SVG scrolled.'); }) Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'event changes in SVG2' in that specification. ...
SVGElement: unload event - Web APIs
The unload event is fired when the DOM implementation removes an SVG document from a window or frame. Bubbles No Cancelable No Interface SVGEvent Event handler property onunload Examples svgElem.addEventListener('unload', () => { console.log('SVG unloaded.'); }) Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'unload' in that specification. Candidate Recommendation Initial definition ...
SVGElement: zoom event - Web APIs
The zoom event occurs when the user initiates an action which causes the current view of the SVG document fragment to be rescaled. Bubbles Yes Cancelable No Interface SVGEvent Event handler property onzoom Examples svgElem.addEventListener('zoom', () => { console.log('SVG zoomed.'); }) ...
SVGEllipseElement - Web APIs
ellipse> element. Methods This interface doesn't implement any specific methods, but inherits methods from its parent interface, SVGGeometryElement. ...
SVGFitToViewBox - Web APIs
ort these two attributes. Interface overview Also implement None Methods None Properties SVGAnimatedPreserveAspectRatio preserveAspectRatio SVGAnimatedRect viewBox Normative document SVG 1.1 (2nd Edition) Properties Name Type Description preserveAspectRatio SVGAnimatedPreserveAspectRatio Corresponds to attribute preserveAspectRatio on the given element. viewBox SVGAnim...
SVGGeometryElement.isPointInFill() - Web APIs
dicating whether the given point is within the fill or not. ...
SVGGeometryElement.isPointInStroke() - Web APIs
e or not. ...
getBBox() - Web APIs
e(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); var boundingClientRectGro...
SVGGraphicsElement - Web APIs
ounding box of the current element. SVGGraphicsElement.getCTM() Returns a DOMMatrix representing the matrix that transforms the current element's coordinate system to its SVG viewport's coordinate system. SVGGraphicsElement.getScreenCTM() Returns a DOMMatrix representing the matrix that transforms the current element's coordinate system to the coordinate system of the SVG viewport for the SVG document fragment. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGGraphicsElement' in that specification. Candidate Recommendation Initial definition ...
SVGLength - Web APIs
Web › API › SVGLength
ing valueAsString Constants SVG_LENGTHTYPE_UNKNOWN = 0 SVG_LENGTHTYPE_NUMBER = 1 SVG_LENGTHTYPE_PERCENTAGE = 2 SVG_LENGTHTYPE_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.un...
SVGLengthList - Web APIs
length unsigned long The number of items in the list. Methods Name & Arguments Return Description clear() void Clears all existing current items from the list, with the resul...
SVGMarkerElement - Web APIs
It is invalid to attempt to define a new value of this type or to attem...
SVGNumberList - Web APIs
length unsigned long The number of items in the list. Methods Name & Arguments Return Description clear() void Clears all existing current items from the list, with the resu...
SVGPathSeg - Web APIs
It is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this...
SVGPathSegList - Web APIs
Methods clear() ...
SVGPoint - Web APIs
Web › API › SVGPoint
An SVGPoint represents a 2D or 3D point in the SVG coordinate system. Syntax retObject = SVGSVGElement.createSVGPoint() Value The returned value is an SVGPoint object. ...
SVGPointList - Web APIs
Methods Name & Arguments Return Description ...
SVGPreserveAspectRatio - Web APIs
It is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type. SVG_PRESERVEASPECTRATIO_NONE 1 Corresponds to value none for attri...
SVGRectElement - Web APIs
Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGRectElement' in that specification.
SVGStringList - Web APIs
length unsigned long A mirror of the value in numberOfItems, for consistency with other interfaces. Methods Name & Arguments Return Description clear() void Clears all existi...
SVGStylable - Web APIs
ll objects corresponding to SVG elements that can have style, class and presentation attributes specified on them. Interface overview Also implement None Methods CSSValue getPresentationAttribute(in DOMString name) Properties readonly SVGAnimatedString className readonly CSSStyleDeclaration style Normative document SVG 1.1 (2nd Edition) Properties Name Type Description className SVGAnimatedString Corresponds to attribute class on the given element. style CSSStyleDeclaration Corresponds to attribute style on the given element. Methods Name & Arguments Return Description getPresentationAttribute(in DOMString name) ...
SVGTransform - Web APIs
It is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type. SVG_TRANSFORM_MATRIX 1 A matrix(...) transformation SVG_TRANSFORM_TRANSLATE 2 A tr...
SVGTransformList - Web APIs
length unsigned long The number of items in the list. Methods Name & Arguments Return Description clear() void Clears all existing current items from the list, with the resu...
SVGTransformable - Web APIs
SVG transformable interface Interface SVGTransformable contains properties and methods that apply to all elements which have attribute transform. Interface overview Also implement None Methods None Properties readonly SVGAnimatedTransformList transform Normative document SVG 1.1 (2nd Edition) Properties Name Type Description transform SVGAnimatedTransformList Corresponds to attribute transform on the given element. Methods The SVGTransformable interface do not provide any specific methods. 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...
Screen.pixelDepth - Web APIs
Web › API › Screen › pixelDepth
Returns the bit depth of the screen. Per the CSSOM, some implementations return 24 for compatibility reasons. See the browser compatibility section for those that don't. Syntax let depth = window.screen.pixelDepth Example // if there is not adequate bit depth // choose a simpler color if ( window.screen.pixelDepth > 8 ) { document.style.color = "#FAEBD7"; } else { document.style.color = "#FFFFFF"; } Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'Screen.pixelDepth' in that specification. Working Draft Initial definition. ...
ScreenOrientation.angle - Web APIs
Syntax angle = ScreenOrientation.angle Value An unsigned short integer. Specifications Specification Status Comment Screen Orientation APIThe definition of 'angle' in that specification. Working Draft Initial definition. 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. ...
ScreenOrientation.lock() - Web APIs
Syntax ScreenOrientation.lock(orientation) Parameters orientation An orientation lock type. One of the following: "any" "natural" "landscape" "portrait" "portrait-primary" "portrait-secondary" "landscape-primary" "landscape-secondary" Return value A Promise. Specifications Specification Status Comment Screen Orientation APIThe definition of 'lock()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
ScreenOrientation.type - Web APIs
Syntax type = ScreenOrientation.type Value A String. Specifications Specification Status Comment Screen Orientation APIThe definition of 'type' in that specification. Working Draft Initial definition. 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. ...
ScreenOrientation.unlock() - Web APIs
Syntax ScreenOrientation.unlock() Parameters None. Return value Void. Specifications Specification Status Comment Screen Orientation APIThe definition of 'unlock()' in that specification. Working Draft Initial definition. 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. ...
ScreenOrientation - Web APIs
The ScreenOrientation interface of the the Screen Orientation API provides information about the current orientation of the document. Properties ScreenOrientation.typeRead only Returns the document's current orientation type, one of "portrait-primary", "portrait-secondary", "landscape-primary", or "landscape-secondary". ScreenOrientation.angleRead only Returns the document's current orientation angle. Event handlers ScreenOrientation.onchange The EventHandler called whenever the screen changes orientation. Methods ScreenOrientation.lock() Locks the orientation of the containing document to its default orientation and returns a Promise. ScreenOrientation.unlock() Unlocks the orientation of the containing document from its default orientation. Specifications Sp...
Screen Capture API - Web APIs
straints and settings objects, and has the possible values application, browser, monitor, and window. Feature Policy validation User agents that support Feature Policy (either using HTTP's Feature-Policy header or the <iframe> attribute allow) can specify a desire to use the Screen Capture API using the policy control directive display-capture: <iframe allow="display-capture" src="/some-other-document.html"> The default allow list is self, which lets the any content within the document use Screen Capture. See Using Feature Policy for a more in-depth explanation of how Feature Policy is used. Specifications Specification Status Comment Screen Capture Working Draft Initial definition ...
SecurityPolicyViolationEvent.SecurityPolicyViolationEvent() - Web APIs
ou do include an eventInitDict, certain properties must be included (marked below with required): blockedURI: The blockedURI of the SecurityPolicyViolationEvent. If not included, the default value is "". columnNumber: The columnNumber of the SecurityPolicyViolationEvent. If not included, the default value is 0. disposition: The disposition of the SecurityPolicyViolationEvent (required). documentURI: The documentURI of the SecurityPolicyViolationEvent (required). effectiveDirective: The effectiveDirective of the SecurityPolicyViolationEvent (required). lineNumber: The lineNumber of the SecurityPolicyViolationEvent. If not included, the default value is 0. originalPolicy: The originalPolicy of the SecurityPolicyViolationEvent (required). referrer: The referrer of the SecurityPolicy...
SecurityPolicyViolationEvent.blockedURI - Web APIs
The blockedURI read-only property of the SecurityPolicyViolationEvent interface is a USVString representing the URI of the resource that was blocked because it violates a policy. Syntax let blockedURI = violationEventInstance.blockedURI; Value A USVString representing the URI of the blocked resource. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.blockedURI); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'blockedURI' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.columnNumber - Web APIs
The columnNumber read-only property of the SecurityPolicyViolationEvent interface is the column number in the document or worker at which the violation occurred. Syntax let colNum = violationEventInstance.columnNumber; Value A number representing the column number where the violation occurred. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.columnNumber); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'columnNumber' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.disposition - Web APIs
The disposition read-only property of the SecurityPolicyViolationEvent interface indicates how the violated policy is configured to be treated by the user agent. Syntax let disposition = violationEventInstance.disposition; Value A value defined in the SecurityPolicyViolationEventDisposition enum representing the URI of the blocked resource. Possible values are "enforce" or "report" Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.disposition); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'disposition' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.effectiveDirective - Web APIs
The effectiveDirective read-only property of the SecurityPolicyViolationEvent interface is a DOMString representing the directive whose enforcement uncovered the violation. Syntax let effDir = violationEventInstance.effectiveDirective; Value A DOMString representing the directive whose enforcement uncovered the violation. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.effectiveDirective); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'effectiveDirective' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.lineNumber - Web APIs
The lineNumber read-only property of the SecurityPolicyViolationEvent interface is the line number in the document or worker at which the violation occurred. Syntax let lineNumber = violationEventInstance.lineNumber; Value A number representing the line number at which the violation occurred. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.lineNumber); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'lineNumber' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.originalPolicy - Web APIs
The originalPolicy read-only property of the SecurityPolicyViolationEvent interface is a DOMString containing the policy whose enforcement uncovered the violation. Syntax let origPolicy = violationEventInstance.originalPolicy; Value A DOMString representing the policy whose enforcement uncovered the violation. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.originalPolicy); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'originalPolicy' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.referrer - Web APIs
The referrer read-only property of the SecurityPolicyViolationEvent interface is a USVString representing the referrer of the resources whose policy was violated. This will be a URL or null. Syntax let referrer = violationEventInstance.referrer; Value A USVString representing the URL of the referrer of the violating resources. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.referrer); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'referrer' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.sample - Web APIs
resenting a sample of the resource that caused the violation. Syntax let sample = violationEventInstance.sample; Value A DOMString containing a sample of the resource that caused the violation, usually the first 40 characters. This will only be populated if the resource is an inline script, event handler, or style -- external resources causing a violation will not generate a sample. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.sample); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'sample' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.sourceFile - Web APIs
The sourceFile read-only property of the SecurityPolicyViolationEvent interface is a USVString representing the URI of the document or worker in which the violation was found. Syntax let source = violationEventInstance.sourceFile; Value A USVString representing the URI of the document or worker in which the violation was found. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.sourceFile); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'sourceFile' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.statusCode - Web APIs
The statusCode read-only property of the SecurityPolicyViolationEvent interface is a number representing the HTTP status code of the document or worker in which the violation occurred. Syntax let status = violationEventInstance.statusCode; Value A number representing the status code of the document or worker in which the violation occurred. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.statusCode); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'statusCode' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.violatedDirective - Web APIs
The violatedDirective read-only property of the SecurityPolicyViolationEvent interface is a DOMString representing the directive whose enforcement uncovered the violation. Syntax let violatedDir = violationEventInstance.violatedDirective; Value A DOMString representing the directive whose enforcement uncovered the violation. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.violatedDirective); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'violatedDirective' in that specification. Working Draft Initial definition ...
Selection.anchorNode - Web APIs
The anchor is where the user began the selection. This can be visualized by holding the Shift key and pressing the arrow keys on your keyboard. The selection's anchor does not move, but the selection's focus, the other end of the selection, does move. ...
Selection.focusNode - Web APIs
The focus is where the user ended the selection. This can be visualized by holding the Shift key and pressing the arrow keys on your keyboard to modify the current selection. The selection's focus moves, but the selection's anchor, the other end of the selection, does not move. ...
Selection.rangeCount - Web APIs
reshly loaded page, the rangeCount is 0. After the user clicks on the page, rangeCount is 1, even if no selection is visible. A user can normally only select one range at a time, so the rangeCount will usually be 1. Scripting can be used to make the selection contain more than one range. Gecko browsers allow multiple 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().rangeC...
Selection.selectAllChildren() - Web APIs
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 definition ...
Selection.type - Web APIs
Web › API › Selection › type
The selection is collapsed (i.e. the caret is placed on some text, but no range has been selected). Range: A range has been selected. Example In this example, the event handler will fire each time a new selection is made. console.log(selection.type) will return Caret or Range depending on whether the caret is placed at a single point in the text, or a range has been selected. var selection; document.onselectionchange = function() { console.log('New selection made'); selection = document.getSelection(); console.log(selection.type); }; Specifications Specification Status Comment Selection APIThe definition of 'Selection.type' in that specification. Working Draft Current ...
ServiceWorker.scriptURL - Web APIs
Returns the ServiceWorker serialized script URL defined as part of ServiceWorkerRegistration. Must be on the same origin as the document that registers the ServiceWorker. Syntax someURL = ServiceWorker.scriptURL Value A USVString (see the WebIDL definition of USVString.) Examples TBD Specifications Specification Status Comment Service WorkersThe definition of 'scriptURL' in that specification. Working Draft Initial definition ...
ServiceWorkerContainer.getRegistrations() - Web APIs
ner, in an array. The method returns a Promise that resolves to an array of ServiceWorkerRegistration. Syntax serviceWorkerContainer.getRegistrations().then(function(serviceWorkerRegistrations) { ... }); Parameters None. Return value A Promise that resolves to an array of ServiceWorkerRegistration objects. Example navigator.serviceWorker.getRegistrations().then(function(registrations) { document.querySelector('#status').textContent = 'ServiceWorkerRegistrations found.'; }); Specifications Specification Status Comment Service WorkersThe definition of 'getRegistrations()' in that specification. Working Draft Initial definition. ...
ServiceWorkerContainer.oncontrollerchange - Web APIs
Syntax serviceWorkerContainer.oncontrollerchange = function(controllerchangeevent) { ... ...
ServiceWorkerContainer.startMessages() - Web APIs
ed from a service worker to pages under its control (e.g. sent via Client.postMessage()). This can be used to react to sent messages earlier, even before that page's content has finished loading. Explanation By default, all messages sent from a page's controlling service worker to the page (using Client.postMessage()) are queued while the page is loading, and get dispatched once the page's HTML document has been loaded and parsed (i.e. after the DOMContentLoaded event fires). It's possible to start dispatching these messages earlier by calling ServiceWorkerContainer.startMessages(), for example if you've invoked a message handler using EventTarget.addEventListener() before the page has finished loading, but want to start processing the messages right away. Note: The messages start being sent a...
ServiceWorkerRegistration.scope - Web APIs
Note: This feature is available in Web Workers. ...
ServiceWorkerRegistration - Web APIs
responding service worker clients. The browser maintains a persistent list of active ServiceWorkerRegistration objects. Note: This feature is available in Web Workers. Properties Also implements properties from its parent interface, EventTarget. ServiceWorkerRegistration.scope Read only Returns a unique identifier for a service worker registration. This must be on the same origin as the document that registers the ServiceWorker. ServiceWorkerRegistration.installing Read only Returns a service worker whose state is installing. This is initially set to null. ServiceWorkerRegistration.waiting Read only Returns a service worker whose state is installed. This is initially set to null. ServiceWorkerRegistration.active Read only Returns a service worker whose state is activated. This i...
ShadowRoot.delegatesFocus - Web APIs
of the ShadowRoot interface returns a boolean that indicates whether delegatesFocus was set when the shadow was attached (see Element.attachShadow()). This is currently an experimental non-standard feature, available only in Chrome. Syntax var df = shadowRoot.delegatesFocus Value A boolean value -- true if the shadow root does delegate focus, false if it doesn't. Examples let customElem = document.querySelector('my-shadow-dom-element'); let shadow = customElem.shadowRoot; ... // Does it delegate focus? let hostElem = shadow.delegatesFocus; Specifications This feature is not currently in a specification. ...
ShadowRoot.host - Web APIs
Web › API › ShadowRoot › host
The host read-only property of the ShadowRoot returns a reference to the DOM element the ShadowRoot is attached to. Syntax const someElement = shadowRoot.host Value A DOM Element. Examples let customElem = document.querySelector('my-shadow-dom-element'); let shadow = customElem.shadowRoot; ... // return the original host element some time later let hostElem = shadow.host; Specifications Specification Status Comment DOMThe definition of 'ShadowRoot.host' in that specification. Living Standard ...
ShadowRoot.innerHTML - Web APIs
The innerHTML property of the ShadowRoot interface sets or returns a reference to the DOM tree inside the ShadowRoot. Syntax var domString = shadowRoot.innerHTML shadowRoot.innerHTML = domString Value A DOMString. Examples let customElem = document.querySelector('my-shadow-dom-element'); let shadow = customElem.shadowRoot; shadow.innerHTML = '<strong>This element should be more important!</strong>'; Specifications This property is not defined by any specifications yet; see this open spec issue to specify it. ...
ShadowRoot.mode - Web APIs
Web › API › ShadowRoot › mode
e of a shadow root is "closed", the shadow root's implementation internals are inaccessible and unchangeable from JavaScript--in the same way the implementation internals of, for example, the <video> element are inaccessible and unchangeable from JavaScript. Syntax var mode = shadowRoot.mode Value A value defined in the ShadowRootMode enum -- either open or closed. ...
SharedWorker() - Web APIs
r. The value can be omit, same-origin, or include. If not specified, or if type is classic, the default used is omit (no credentials required). name: A DOMString specifying an identifying name for the SharedWorkerGlobalScope representing 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() construct...
SourceBuffer - Web APIs
s in the specified range from the SourceBuffer. Returns a Promise which is fulfilled once all matching segments have been removed. Examples The following simple example loads a video chunk by chunk as fast as possible, playing it as soon as it can. ...
SpeechRecognition.abort() - Web APIs
oon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new SpeechRecognition(); var speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; var diagnostic = document.querySelector('.output'); var bg = document.querySelector('html'); document.body.onclick = function() { recognition.start(); console.log('Ready to receive a color command.'); } abortBtn.onclick = function() { recognition.abort(); console.log('Speech recognition aborted.'); } recognition.onspeechend = function() { recognition.stop(); console.log('Speech recognition has stopped.'); }...
SpeechRecognition.start() - Web APIs
oon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new SpeechRecognition(); var speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; var diagnostic = document.querySelector('.output'); var bg = document.querySelector('html'); document.body.onclick = function() { recognition.start(); console.log('Ready to receive a color command.'); } abortBtn.onclick = function() { recognition.abort(); console.log('Speech recognition aborted.'); } recognition.onspeechend = function() { recognition.stop(); console.log('Speech recognition has stopped.'); }...
SpeechRecognition.stop() - Web APIs
oon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new SpeechRecognition(); var speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; var diagnostic = document.querySelector('.output'); var bg = document.querySelector('html'); document.body.onclick = function() { recognition.start(); console.log('Ready to receive a color command.'); } abortBtn.onclick = function() { recognition.abort(); console.log('Speech recognition aborted.'); } recognition.onspeechend = function() { recognition.stop(); console.log('Speech recognition has stopped.'); }...
SpeechRecognition - Web APIs
l | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new SpeechRecognition(); var speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; recognition.continuous = false; recognition.lang = 'en-US'; recognition.interimResults = false; recognition.maxAlternatives = 1; var diagnostic = document.querySelector('.output'); var bg = document.querySelector('html'); document.body.onclick = function() { recognition.start(); console.log('Ready to receive a color command.'); } recognition.onresult = function(event) { var color = event.results[0][0].transcript; diagnostic.textContent = 'Result received: ' + color; bg.style.backgroundColor = color; } Specifications Specifica...
SpeechRecognitionEvent.emma - Web APIs
The emma read-only property of the SpeechRecognitionEvent interface returns an Extensible MultiModal Annotation markup language (EMMA) -- XML -- representation of the result. Note: EMMA is defined in the specification EMMA: Extensible MultiModal Annotation markup language. You can see muliple EMMA examples in the spec. Syntax var myEmma = event.emma; Value A valid XML document. The exact contents can vary across user agents and recognition engines, but all supporting implementations will expose a valid XML document complete with an EMMA namespace. If the speech recognition system does not supply EMMA data then the user agent will return null. Examples recognition.onresult = function(event) { var color = event.results[0][0].transcript; diagnostic.textContent = 'Result received: ' +...
SpeechSynthesis.onvoiceschanged - Web APIs
) Note that Firefox doesn't support it at present, and will just return a list of voices when SpeechSynthesis.getVoices() is fired. With Chrome however, you have to wait for the event to fire before populating the list, hence the bottom if statement seen below. ...
SpeechSynthesisErrorEvent.error - Web APIs
ble The voice set in SpeechSynthesisUtterance.voice was not available. text-too-long The contents of the SpeechSynthesisUtterance.text attribute was too long to synthesize. invalid-argument The content of the SpeechSynthesisUtterance.rate, SpeechSynthesisUtterance.pitch or SpeechSynthesisUtterance.volume property was not valid. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.
SpeechSynthesisErrorEvent - Web APIs
ace, which inherits properties from its parent interface, Event. SpeechSynthesisErrorEvent.error Read only Returns an error code indicating what has gone wrong with a speech synthesis attempt. Methods SpeechSynthesisErrorEvent extends the SpeechSynthesisEvent interface, which inherits methods from its parent interface, Event. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.
SpeechSynthesisUtterance.SpeechSynthesisUtterance() - Web APIs
he SpeechSynthesisUtterance interface returns a new SpeechSynthesisUtterance object instance. Syntax var utterThis = new SpeechSynthesisUtterance(text); Parameters text A DOMString containing the text that will be synthesized when the utterance is spoken.. Examples The following snippet is excerpted from our Speech synthesizer demo. var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.
SpeechSynthesisUtterance.lang - Web APIs
erface gets and sets the language of the utterance. If unset, the app's (i.e. the <html> lang value) lang will be used, or the user-agent default if that is unset too. Syntax var myLang = speechSynthesisUtteranceInstance.lang; speechSynthesisUtteranceInstance.lang = 'en-US'; Value A DOMString representing a BCP 47 language tag. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.
SpeechSynthesisUtterance.onboundary - Web APIs
The onboundary property of the SpeechSynthesisUtterance interface represents an event handler that will run when the spoken utterance reaches a word or sentence boundary (when the boundary event fires.) Syntax speechSynthesisUtteranceInstance.onboundary = function() { ... }; Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === sele...
SpeechSynthesisUtterance.onend - Web APIs
The onend property of the SpeechSynthesisUtterance interface represents an event handler that will run when the utterance has finished being spoken (when the end event fires.) Syntax speechSynthesisUtteranceInstance.onend = function() { ... }; Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedOption) { utterThis.vo...
SpeechSynthesisUtterance.onerror - Web APIs
The onerror property of the SpeechSynthesisUtterance interface represents an event handler that will run when an error occurs that prevents the utterance from being succesfully spoken (when the error event fires.) Syntax speechSynthesisUtteranceInstance.onerror = function() { ... }; Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name ...
SpeechSynthesisUtterance.onmark - Web APIs
The onmark property of the SpeechSynthesisUtterance interface represents an event handler that will run when the spoken utterance reaches a named SSML mark tag (when the mark event fires.) Syntax speechSynthesisUtteranceInstance.onmark = function() { ... }; Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedOption) { ...
SpeechSynthesisUtterance.onpause - Web APIs
The onpause property of the SpeechSynthesisUtterance interface represents an event handler that will run when the utterance is paused part way through (when the pause event fires.) This occurs when the SpeechSynthesis.pause() method is invoked. Syntax speechSynthesisUtteranceInstance.onpause = function() { ... }; Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length...
SpeechSynthesisUtterance.onresume - Web APIs
roperty of the SpeechSynthesisUtterance interface represents an event handler that will run when a paused utterance is resumed (when the resume event fires.) This occurs when the SpeechSynthesis.resume() method is invoked on a paused speech synthesis instance. Syntax speechSynthesisUtteranceInstance.onresume = function() { ... }; Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.
SpeechSynthesisUtterance.onstart - Web APIs
The onstart property of the SpeechSynthesisUtterance interface represents an event handler that will run when the utterance has begun to be spoken (when the start event fires.) This occurs when the SpeechSynthesis.speak() method is invoked. Syntax speechSynthesisUtteranceInstance.onstart = function() { ... }; Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length ; i...
SpeechSynthesisUtterance.pitch - Web APIs
5; Value A float representing the pitch value. It can range between 0 (lowest) and 2 (highest), with 1 being the default pitch for the current platform or voice. Some speech synthesis engines or voices may constrain the minimum and maximum rates further. If SSML is used, this value will be overridden by prosody tags in the markup. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.
SpeechSynthesisUtterance.rate - Web APIs
which should correspond to a normal speaking rate. Other values act as a percentage relative to this, so for example 2 is twice as fast, 0.5 is half as fast, etc. Some speech synthesis engines or voices may constrain the minimum and maximum rates further. If SSML is used, this value will be overridden by prosody tags in the markup. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.
SpeechSynthesisUtterance.text - Web APIs
The text property of the SpeechSynthesisUtterance interface gets and sets the text that will be synthesised when the utterance is spoken. The text may be provided as plain text, or a well-formed SSML document. The SSML tags will be stripped away by devices that don't support SSML. Syntax var myText = speechSynthesisUtteranceInstance.text; speechSynthesisUtteranceInstance.text = 'Hello I am speaking'; Value A DOMString representing the text to the synthesised. The maximum length of the text that can be spoken in each utterance is 32,767 characters. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... ...
SpeechSynthesisUtterance.voice - Web APIs
s.getVoices(). If not set by the time the utterance is spoken, the voice used will be the most suitable default voice available for the utterance's lang setting. Syntax var myVoice = speechSynthesisUtteranceInstance.voice; speechSynthesisUtteranceInstance.voice = speechSynthesisVoiceInstance; Value A SpeechSynthesisVoice object. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.
SpeechSynthesisUtterance.volume - Web APIs
spoken at. If not set, the default value 1 will be used. Syntax var myVolume = speechSynthesisUtteranceInstance.volume; speechSynthesisUtteranceInstance.volume = 0.5; Value A float that represents the volume value, between 0 (lowest) and 1 (highest.) If SSML is used, this value will be overridden by prosody tags in the markup. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices(); ... inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.
SpeechSynthesisVoice.default - Web APIs
whether the voice is the default voice for the current app (true), or not (false.) Note: For some devices, it might be the default voice for the voice's language. The spec is not very clear on which it should be, so some implementations may differ. Syntax var amIDefault = speechSynthesisVoiceInstance.default; Value A Boolean. ...
SpeechSynthesisVoice.lang - Web APIs
The lang read-only property of the SpeechSynthesisVoice interface returns a BCP 47 language tag indicating the language of the voice. Syntax var myLang = speechSynthesisVoiceInstance.lang; Value A DOMString representing the language of the device. Examples for(i = 0; i < voices.length ; i++) { var option = document.createElement('option'); option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textContent += ' -- DEFAULT'; } option.setAttribute('data-lang', voices[i].lang); option.setAttribute('data-name', voices[i].name); voiceSelect.appendChild(option); } Specifications Specification Status Comment Web Speech APIThe definition of 'lang' in that specification. Draft ...
SpeechSynthesisVoice.localService - Web APIs
operty is provided to allow differentiation in the case that some voice options are provided by a remote service; it is possible that remote voices might have extra latency, bandwidth or cost associated with them, so such distinction may be useful. Syntax var amILocal = speechSynthesisVoiceInstance.localService; Value A Boolean. ...
SpeechSynthesisVoice.name - Web APIs
The name read-only property of the SpeechSynthesisVoice interface returns a human-readable name that represents the voice. Syntax var voiceName = speechSynthesisVoiceInstance.name; Value A DOMString representing the name of the voice. Examples for(i = 0; i < voices.length ; i++) { var option = document.createElement('option'); option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textContent += ' -- DEFAULT'; } option.setAttribute('data-lang', voices[i].lang); option.setAttribute('data-name', voices[i].name); voiceSelect.appendChild(option); } Specifications Specification Status Comment Web Speech APIThe definition of 'name' in that specification. Draft ...
SpeechSynthesisVoice.voiceURI - Web APIs
he type of URI and location of the speech synthesis service for this voice. Syntax var myVoiceURI = speechSynthesisVoiceInstance.voiceURI; Value A DOMString representing the URI of the voice. This is a generic URI and can point to local or remote services, e.g. it could be a proprietary system URN or a a URL to a remote service. ...
SpeechSynthesisVoice - Web APIs
e Read only Returns a human-readable name that represents the voice. SpeechSynthesisVoice.voiceURI Read only Returns the type of URI and location of the speech synthesis service for this voice. Examples The following snippet is excerpted from our Speech synthesiser demo. ...
StaticRange.StaticRange() - Web APIs
offset into the node indicated by endOffset at which the last character in the range is located. Return value A new StaticRange object initialized with the values given in the rangeSpec object. Exceptions InvalidNodeTypeError A DOMException fired if either or both of the startContainer and/or endContainer are a type of node which you can't include in a range. Those node types are Node.DOCUMENT_TYPE_NODE (representing the DocumentType node derived from the DTD identified using the doctype preamble in the HTML, for example) and the Attr node describing an attribute of an element on the DOM.. Specifications Specification Status Comment DOMThe definition of 'StaticRange()' in that specification. Living Standard Initial definition. ...
StaticRange - Web APIs
eger value indicating the offset into the node specified by startContainer at which the first character of the range is located. Methods StaticRange.toRange() Returns a new Range object which describes the same range as the source StaticRange, but is "live" with values that change to reflect changes in the contents of the DOM tree. Usage notes A DOM range specifies a span of content in a document, potentially beginning inside one node (or element) and ending inside another one. Unlike a Range, a StaticRange represents a range which is fixed in time; it does not change to try to keep the same content within it as the document changes. If any changes are made to the DOM, the actual data contained within the range specified by a StaticRange may change. This lets the user agent avoid a lot of...
Storage.getItem() - Web APIs
Web › API › Storage › getItem
A DOMString containing the value of the key. If the key does not exist, null is returned. Example The following function retrieves three data items from local storage, then uses them to set custom styles on a page. function setStyles() { var currentColor = localStorage.getItem('bgcolor'); var currentFont = localStorage.getItem('font'); var currentImage = localStorage.getItem('image'); document.getElementById('bgcolor').value = currentColor; document.getElementById('font').value = currentFont; document.getElementById('image').value = currentImage; htmlElem.style.backgroundColor = '#' + currentColor; pElem.style.fontFamily = currentFont; imgElem.setAttribute('src', currentImage); } Note: To see this used within a real world example, see our Web Storage Demo. Specifications...
StorageEstimate.quota - Web APIs
l 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 ...
StorageEstimate.usage - Web APIs
l 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 'usage' in that specification. Living Standard Initial definition ...
StorageManager.estimate() - Web APIs
marking, adding to homescreen, or accepting push notifications 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 'estimate()' in that specification. Living Standard Initial definition. ...
Using writable streams - Web APIs
queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink error:", err); } }, queuingStrategy...
Streams API - Web APIs
eveloper (e.g. a custom ReadableStream() constructor). ReadableByteStreamController Represents a controller allowing control of a ReadableStream's state and internal queue. Byte stream controllers are for byte streams. ReadableStreamBYOBRequest Represents a pull into request in a ReadableByteStreamController. Examples We have created a directory of examples to go along with the Streams API documentation -- see mdn/dom-examples/streams. The examples are as follows: Simple stream pump: This example shows how to consume a ReadableStream and pass its data to another. Grayscale a PNG: This example shows how a ReadableStream of a PNG can be turned into grayscale. Simple random stream: This example shows how to use a custom stream to generate random strings, enqueue them as chunks, and then r...
Stylesheet.href - Web APIs
Web › API › StyleSheet › href
The href property of the StyleSheet interface returns the location of the style sheet. Syntax uri = stylesheet.href Parameters uri is a string containing the stylesheet's URI. Example // on a local machine: <html> <head> <link rel="StyleSheet" href="example.css" type="text/css" /> <script> function sref() { alert(document.styleSheets[0].href); } </script> </head> <body> <div class="thunder">Thunder</div> <button onclick="sref()">ss</button> </body> </html> // returns "file:////C:/Windows/Desktop/example.css Notes If the style sheet is a linked style sheet, the value of its attribute is its location. For inline style sheets, the value of this attribute is NULL. This property is read-only in Firefox, Opera, Google Chrome, and Safari, and it is re...
StyleSheet.ownerNode - Web APIs
The ownerNode property of the StyleSheet interface returns the node that associates this style sheet with the document. This is usually an HTML <link> or <style> element, but can also return a processing instruction node in the case of <?xml-stylesheet ?>. Syntax nodeRef = stylesheet.ownerNode Example <html lang="en"> <head> <link rel="stylesheet" href="example.css"> </head> <body> <button onclick="alert(document.styleSheets[0].ownerNode)">Show example.css's ownerNode</button> </body> </html> // Displays "object HTMLLinkElement" Notes For style sheets that are included by other style sheets, such as with @import, the value of this property is null. Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'StyleSheet: own...
StyleSheetList - Web APIs
The StyleSheetList interface represents a list of StyleSheet. It is an array-like object but can't be iterated over using Array methods. However It can be iterated over in a standard for loop over its indices, or converted to an Array. Examples Get document styleSheet objects with for loop for (let i = 0; i < document.styleSheets.length; i++) { let styleSheet = document.styleSheets[i]; } Get all CSS rules for the document using Array methods const allCSS = [...document.styleSheets] .map(styleSheet => { try { return [...styleSheet.cssRules] .map(rule => rule.cssText) .join(''); } catch (e) { console.log('Access to stylesheet %s is denied. Ignoring...', styleSheet.href); } }) .filter(Boolean) .join('\n'); Specifications Specificatio...
SubmitEvent.submitter - Web APIs
the value of submitter is null. Examples In this example, a shopping cart may have an assortment of different submit buttons depending on factors such as the user's settings, the shop's settings, and any minimum or maximum shopping card totals established by the payment processors. Each of the submit elements' id is used to identify which payment processor the button corresponds to. let form = document.querySelector("form"); form.addEventListener("submit", (event) => { let submitter = event.submitter; let handler = submitter.id; if (handler) { processOrder(form, handler); } else { showAlertMessage("An unknown or unaccepted payment type was selected. Please try again.", "OK"); } }); The handler ID is obtained by using the submit event's submitter property to get the submit ...
SubmitEvent - Web APIs
by its parent interface, Event. Examples In this example, a shopping cart may have an assortment of different submit buttons depending on factors such as the user's settings, the shop's settings, and any minimum or maximum shopping card totals established by the payment processors. Each of the submit elements' id is used to identify which payment processor the button corresponds to. let form = document.querySelector("form"); form.addEventListener("submit", (event) => { let submitter = event.submitter; let handler = submitter.id; if (handler) { processOrder(form, handler); } else { showAlertMessage("An unknown or unaccepted payment type was selected. Please try again.", "OK"); } }); The handler ID is obtained by using the submit event's submitter property to get the submit ...
SubtleCrypto.unwrapKey() - Web APIs
,248,63,93,107,156,8,96,85,32,189,118, 66,114,126,64,203,97,235,13,18,102,192,51,59,5,122,171,96,129,40,32,154,4, 191,234,75,184,112,201,244,110,50,216,44,88,139,175,58,112,7,52,25,64,112, 40,148,187,39,234,96,151,16,158,114,113,109,164,47,108,94,148,35,232,221, 33,110,126,170,25,234,45,165,180,210,193,120,247,155,127]; /* The unwrapped signing key. */ let signingKey; const signButton = document.querySelector(".pkcs8 .sign-button"); /* Convert an array of byte values to an ArrayBuffer. */ function bytesToArrayBuffer(bytes) { const bytesAsArrayBuffer = new ArrayBuffer(bytes.length); const bytesUint8 = new Uint8Array(bytesAsArrayBuffer); bytesUint8.set(bytes); return bytesAsArrayBuffer; } /* Get some key material to use as input to the deriveKey method. The key material is a pass...
Text.replaceWholeText() - Web APIs
Obsolete Initial definition. ...
TextDecoder.prototype.decode() - Web APIs
in chunks, and false for the final chunk or if the data is not chunked. It defaults to false. Example This example encodes and decodes the euro symbol, EUR. HTML <p>Encoded value: <span id="encoded-value"></span></p> <p>Decoded value: <span id="decoded-value"></span></p> JavaScript const encoder = new TextEncoder(); const array = encoder.encode('EUR'); // Uint8Array(3) [226, 130, 172] document.getElementById('encoded-value').textContent = array; const decoder = new TextDecoder(); const str = decoder.decode(array); // String "EUR" document.getElementById('decoded-value').textContent = str; Result Specifications Specification Status Comment EncodingThe definition of 'TextDecoder.decode()' in that specification. Living Standard Initial definition. ...
TextEncoder.prototype.encode() - Web APIs
input, and returns a Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. Syntax b1 = encoder.encode(string); Parameters string Is a USVString containing the text to encode. Return value A Uint8Array object. Examples <p class="source">This is a sample paragraph.</p> <p class="result">Encoded result: </p> const sourcePara = document.querySelector('.source'); const resultPara = document.querySelector('.result'); const string = sourcePara.textContent; const textEncoder = new TextEncoder(); let encoded = textEncoder.encode(string); resultPara.textContent += encoded; Specifications Specification Status Comment EncodingThe definition of 'TextEncoder.prototype.encode()' in that specification. Livin...
TextMetrics.actualBoundingBoxAscent - Web APIs
The read-only actualBoundingBoxAscent property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline attribute to the top of the bounding rectangle used to render the text, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.actualBoundingBoxAscent; // 8; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.actualBoundingBoxAscent' in that specification. ...
TextMetrics.actualBoundingBoxDescent - Web APIs
The read-only actualBoundingBoxDescent property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline attribute to the bottom of the bounding rectangle used to render the text, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.actualBoundingBoxDescent; // 0; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.actualBoundingBoxDescent' in that specification. ...
TextMetrics.actualBoundingBoxLeft - Web APIs
The read-only actualBoundingBoxLeft property of the TextMetrics interface is a double giving the distance parallel to the baseline from the alignment point given by the CanvasRenderingContext2D.textAlign property to the left side of the bounding rectangle of the given text, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.actualBoundingBoxLeft; // 0; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.actualBoundingBoxLeft' in that specification. ...
TextMetrics.actualBoundingBoxRight - Web APIs
The read-only actualBoundingBoxRight property of the TextMetrics interface is a double giving the distance parallel to the baseline from the alignment point given by the CanvasRenderingContext2D.textAlign property to the right side of the bounding rectangle of the given text, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.actualBoundingBoxRight; // 15.633333333333333; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.actualBoundingBoxRight' in that specification. ...
TextMetrics.alphabeticBaseline - Web APIs
The read-only alphabeticBaseline property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline property to the alphabetic baseline of the line box, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.alphabeticBaseline; // -0; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.alphabeticBaseline' in that specification. ...
TextMetrics.emHeightAscent - Web APIs
The read-only emHeightAscent property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline property to the top of the em square in the line box, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.emHeightAscent; // 7.59765625; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.emHeightAscent' in that specification. ...
TextMetrics.emHeightDescent - Web APIs
The read-only emHeightDescent property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline property to the bottom of the em square in the line box, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.emHeightDescent; // -2.40234375; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.emHeightDescent' in that specification. ...
TextMetrics.fontBoundingBoxAscent - Web APIs
The read-only fontBoundingBoxAscent property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline attribute to the top of the highest bounding rectangle of all the fonts used to render the text, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.fontBoundingBoxAscent; // 10; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.fontBoundingBoxAscent' in that specification. ...
TextMetrics.fontBoundingBoxDescent - Web APIs
The read-only fontBoundingBoxDescent property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline attribute to the bottom of the bounding rectangle of all the fonts used to render the text, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.fontBoundingBoxDescent; // 3; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.fontBoundingBoxDescent' in that specification. ...
TextMetrics.hangingBaseline - Web APIs
The read-only hangingBaseline property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline property to the hanging baseline of the line box, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.hangingBaseline; // 6.078125; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.hangingBaseline' in that specification. ...
TextMetrics.ideographicBaseline - Web APIs
The read-only ideographicBaseline property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline property to the ideographic baseline of the line box, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.ideographicBaseline; // -1.201171875; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.ideographicBaseline' in that specification. ...
TextMetrics.width - Web APIs
Web › API › TextMetrics › width
The read-only width property of the TextMetrics interface contains the text's advance width (the width of that inline box) in CSS pixels. Examples Given this <canvas> element: <canvas id="canvas"></canvas> ... you can get a TextMetrics object using the following code: const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let text = ctx.measureText('foo'); // TextMetrics object text.width; // 16; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.width' in that specification. ...
TextTrack.mode - Web APIs
Web › API › TextTrack › mode
ion and ends at the cue's end position. Example In this example, we configure the text track's cues so that every time a cue is finished, the video automatically pauses playback. This is done by setting the pauseOnExit property on each cue to true. However, to ensure that the track's cues are available, we first set mode to showing. window.addEventListener("load", event => { let trackElem = document.querySelector("track"); let track = trackElem.track; track.mode = "showing"; for (let index=0; index < track.cues.length; index++) { let cue = track.cues[index]; cue.pauseOnExit = true; }; }); Specifications Specification Status Comment HTML Living StandardThe definition of 'mode' in that specification. Living Standard ...
TextTrack - Web APIs
Web › API › TextTrack
s an empty string (""), in which case a custom label may need to be generated by your code using other attributes of the track, if the track's label needs to be exposed to the user. TextTrack.language Read only A DOMString which specifies the text language in which the text track's contents is written. The value must adhere to the format specified in the Tags for Identifying Languages (BCP 47) document from the IETF, just like the HTML lang attribute. For example, this can be "en-US" for United States English or "pt-BR" for Brazilian Portuguese. TextTrack.mode A DOMString specifying the track's current mode. Changing this property's value changes the track's current mode to match. Permitted values are listed under Text track mode constants. The default is disabled, unless the <track> element'...
TextTrackList: addtrack event - Web APIs
The addtrack event is fired when a track is added to a TextTrackList. Bubbles No Cancelable No Interface TrackEvent Event handler property onaddtrack Examples Using addEventListener(): const mediaElement = document.querySelector('video, audio'); mediaElement.textTracks.addEventListener('addtrack', (event) => { console.log(`Text track: ${event.track.label} added`); }); Using the onaddtrack event handler property: const mediaElement = document.querySelector('video, audio'); mediaElement.textTracks.onaddtrack = (event) => { console.log(`Text track: ${event.track.label} added`); }; Specifications Specification Status HTML Living StandardThe definition of 'addtrack' in that specification. Living Standard ...
TextTrackList: change event - Web APIs
The change event is fired when a text track is made active or inactive, or a textTrackList is otherwise changed. Bubbles No Cancelable No Interface Event Event handler property onchange Examples Using addEventListener(): const mediaElement = document.querySelectorAll('video, audio')[0]; mediaElement.textTracks.addEventListener('change', (event) => { console.log(`'${event.type}' event fired`); }); Using the onchange event handler property: const mediaElement = document.querySelector('video, audio'); mediaElement.textTracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; Specifications Specification Status HTML Living StandardThe definition of 'change' in that specification. Living...
TextTrackList.length - Web APIs
are no text tracks in the media. Syntax var trackCount = TextTrackList.length; Value A number indicating how many text tracks are included in the TextTrackList. Each track can be accessed by treating the TextTrackList as an array of objects of type TextTrack. Example This snippet gets the number of text tracks in the first media element found in the DOM by querySelector(). var mediaElem = document.querySelector("video, audio"); var numTextTracks = 0; if (mediaElem.textTracks) { numTextTracks = mediaElem.textTracks.length; } Note that this sample checks to be sure HTMLMediaElement.textTracks is defined, to avoid failing on browsers without support for TextTrack. Specifications Specification Status Comment HTML Living StandardThe definition of 'TextTrackLis...
TextTrackList.onaddtrack - Web APIs
first attached to the element; one addtrack event will occur for each video track in the media resource. Example This snippet establishes a handler for the addtrack event that calls a function, addToTrackList(), passing in the VideoTrack object representing the newly-added track. In this scenario, that function's role is to add the new track to a list of video tracks available to choose from. document.querySelector("video").textTracks.onaddtrack = function(event) { addToTrackList(event.track); }; Specifications Specification Status Comment HTML Living StandardThe definition of 'TextTrackList: onaddtrack' in that specification. Living Standard ...
TextTrackList.onchange - Web APIs
ck in the VideoTrackList. Note: You can also add a handler for the change event using addEventListener(). Syntax TextTrackList.onchange = eventHandler; Example This snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track. var trackList = document.querySelector("video, audio").textTracks; trackList.onchange = function(event) { .... /* do something */ }; Specifications Specification Status Comment HTML Living StandardThe definition of 'TextTrackList: onchange' in that specification. Living Standard ...
TextTrackList.onremovetrack - Web APIs
istener(). Syntax TextTrackList.onremovetrack = eventHandler; Value Set onremovetrack to a function that accepts as input a TrackEvent object which indicates in its track property which text track has been removed from the media element. Example This simple example just fetches the current number of text tracks in the first media element whenever a track is removed from the media element. document.querySelectorAll("video, audio")[0].textTracks.onremovetrack = function(event) { myTrackCount = document.querySelectorAll("video, audio")[0].textTracks.length; }; The current number of text tracks remaining in the media element is obtained from TextTrackList property length. Specifications Specification Status Comment HTML Living StandardThe definition of 'TextTr...
TextTrackList - Web APIs
esent on a media element, TextTrackList lets you set event handlers on the addtrack and removetrack events, so that you can detect when tracks are added to or removed from the media element's stream. See onaddtrack and onremovetrack for details and examples. Examples Getting a video element's text track list To get a media element's TextTrackList, use its textTracks property. var textTracks = document.querySelector("video").textTracks; Monitoring track count changes In this example, we have an app that displays information about the number of channels available. To keep it up to date, handlers for the addtrack and removetrack events are set up. textTracks.onaddtrack = updateTrackCount; textTracks.onremovetrack = updateTrackCount; function updateTrackCount(event) { trackCount = textTracks...
TimeEvent - Web APIs
Web › API › TimeEvent
he Event, depending on the type of the event. For this event type, indicates the repeat number for the animation. TimeEvent.view Read only Is a WindowProxy that identifies the Window from which the event was generated. Methods initTimeEvent(DOMString typeArg, AbstractView viewArg, long detailArg) The initTimeEvent method is used to initialize the value of a TimeEvent created through the DocumentEvent interface. This method may only be called before the TimeEvent has been dispatched via the dispatchEvent method, though it may be called multiple times during that phase if necessary. ...
TimeRanges.end() - Web APIs
Web › API › TimeRanges › end
Returns the time offset at which a specified time range ends. Syntax endTime = TimeRanges.end(index) Parameters index is the range number to return the ending time for. Exceptions INDEX_SIZE_ERR A DOMException thrown if the specified index doesn't correspond to an existing range. Example Given a video element with the ID "myVideo": var v = document.getElementById("myVideo"); var buf = v.buffered; var numRanges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // The one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } This example looks at the time ranges and looks to see if the entire video has been loaded. Specifications Specification Sta...
TimeRanges.length - Web APIs
Web › API › TimeRanges › length
The TimeRanges.length read-only property returns the number of ranges in the object. Syntax length = TimeRanges.length; Example Given a video element with the ID "myVideo": var v = document.GetElementById("myVideo"); var buf = v.buffered; var numRanges = buf.length; if (buf.length == 1) { // Only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // The one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } This example looks at the time ranges and looks to see if the entire video has been loaded. Specifications Specification Status Comment HTML Living StandardThe definition of 'TimeRanges.length()' in that specification. Living Standard Initial definition ...
TimeRanges.start() - Web APIs
Web › API › TimeRanges › start
Returns the time offset at which a specified time range begins. Syntax startTime = TimeRanges.start(index) Parameters index is the range number to return the starting time for. Exceptions INDEX_SIZE_ERR A DOMException thrown if the specified index doesn't correspond to an existing range. Example Given a video element with the ID "myVideo": var v = document.getElementById("myVideo"); var buf = v.buffered; var numRanges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // The one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } This example looks at the time ranges and looks to see if the entire video has been loaded. Specifications Specificatio...
Touch.clientX - Web APIs
Web › API › Touch › clientX
iates a touch on an element with an id of source, moves within the element or out of the element and then releases contact with the surface. When the touchend event handler is invoked, the changes in the Touch.clientX and Touch.clientY coordinates, from the starting touch point to the ending touch point, are calculated. // Register touchstart and touchend listeners for element 'source' var src = document.getElementById("source"); var clientX, clientY; src.addEventListener('touchstart', function(e) { // Cache the client X/Y coordinates clientX = e.touches[0].clientX; clientY = e.touches[0].clientY; }, false); src.addEventListener('touchend', function(e) { var deltaX, deltaY; // Compute the change in X and Y coordinates. // The first touch point in the changedTouches // list is the...
Touch.clientY - Web APIs
Web › API › Touch › clientY
iates a touch on an element with an id of source, moves within the element or out of the element and then releases contact with the surface. When the touchend event handler is invoked, the changes in the Touch.clientX and Touch.clientY coordinates, from the starting touch point to the ending touch point, are calculated. // Register touchstart and touchend listeners for element 'source' var src = document.getElementById("source"); var clientX, clientY; src.addEventListener('touchstart', function(e) { // Cache the client X/Y coordinates clientX = e.touches[0].clientX; clientY = e.touches[0].clientY; }, false); src.addEventListener('touchend', function(e) { var deltaX, deltaY; // Compute the change in X and Y coordinates. // The first touch point in the changedTouches // list is the...
Touch.pageX - Web APIs
Web › API › Touch › pageX
code snippet, we assume the user initiates one or more touch contacts on the source element, moves the touch points and then releases all contacts with the surface. When the touchmove event handler is invoked, each touch point's Touch.pageX and Touch.pageY coordinates are accessed via the event's TouchEvent.changedTouches list. // Register a touchmove listeners for the 'source' element var src = document.getElementById("source"); src.addEventListener('touchmove', function(e) { // Iterate through the touch points that have moved and log each // of the pageX/Y coordinates. The unit of each coordinate is CSS pixels. var i; for (i=0; i < e.changedTouches.length; i++) { console.log("touchpoint[" + i + "].pageX = " + e.changedTouches[i].pageX); console.log("touchpoint[" + i + "].pageY ...
Touch.pageY - Web APIs
Web › API › Touch › pageY
code snippet, we assume the user initiates one or more touch contacts on the source element, moves the touch points and then releases all contacts with the surface. When the touchmove event handler is invoked, each touch point's Touch.pageX and Touch.pageY coordinates are accessed via the event's TouchEvent.changedTouches list. // Register a touchmove listeners for the 'source' element var src = document.getElementById("source"); src.addEventListener('touchmove', function(e) { // Iterate through the touch points that have moved and log each // of the pageX/Y coordinates. The unit of each coordinate is CSS pixels. var i; for (i=0; i < e.changedTouches.length; i++) { console.log("touchpoint[" + i + "].pageX = " + e.changedTouches[i].pageX); console.log("touchpoint[" + i + "].pageY ...
Touch.radiusX - Web APIs
Web › API › Touch › radiusX
otated clockwise about its center. The following simple code snippet, registers a single handler for the touchstart, touchmove and touchend events. When the src element is touched, the element's width and height will be calculate based on the touch point's radiusX and radiusY values and the element will then be rotated using the touch point's rotationAngle. <div id="src"> ... </div> var src = document.getElementById("src"); src.addEventListener('touchstart', rotate); src.addEventListener('touchmove', rotate); src.addEventListener('touchend', rotate); function rotate (e) { var touch = e.changedTouches.item(0); // Turn off default event handling e.preventDefault(); // Rotate element 'src'. src.style.width = touch.radiusX * 2 + 'px'; src.style.height = touch.radiusY * 2 + 'px'; ...
Touch.screenX - Web APIs
Web › API › Touch › screenX
relative to the screen in CSS pixels. In following simple code snippet, we assume the user initiates multiple touch contacts on an element with an id of source and then releases contacts with the surface. When the touchstart event handler is invoked, each touch point's Touch.screenX and Touch.screenY coordinates are accessed. // Register a touchstart listeners for the 'source' element var src = document.getElementById("source"); src.addEventListener('touchstart', function(e) { // Iterate through the touch points and log each screenX/Y coordinate. // The unit of each coordinate is CSS pixels. var i; for (i=0; i < e.touches.length; i++) { console.log("touchpoint[" + i + "].screenX = " + e.touches[i].screenX); console.log("touchpoint[" + i + "].screenY = " + e.touches[i].screenY); ...
TouchEvent - Web APIs
granularity of these events. touchcancel Sent when a touch point has been disrupted in some way. There are several possible reasons why this might happen (and the exact reasons will vary from device to device, as well as browser to browser): An event of some kind occurred that canceled the touch; this might happen if a modal alert pops up during the interaction. The touch point has left the document window and moved into the browser's UI area, a plug-in, or other external content. The user has placed more touch points on the screen than can be supported, in which case the earliest Touch in the TouchList gets canceled. Using with addEventListener() and preventDefault() It's important to note that in many cases, both touch and mouse events get sent (in order to let non-touch-specific code ...
TouchList.item() - Web APIs
Web › API › TouchList › item
The index of the Touch object to retrieve. The index is a number in the range of 0 to one less than the length of the TouchList. Return value touchPoint The requested Touch object from the TouchList. Returns null if the index is not less than the length of the list. Example This code example illustrates the use of the TouchList interface's item method and the length property. ...
TouchList.length - Web APIs
Web › API › TouchList › length
The length read-only property indicates the number of items (touch points) in a given TouchList. Syntax var numTouches = touchList.length; Return value numTouches The number of touch points in touchList. Example This code example illustrates the use of the TouchList interface's item method and the length property. ...
TransitionEvent.initTransitionEvent() - Web APIs
TransitionEvent created that way are untrusted. Note: this method has been dropped during the standard process. It has been deprecated and is in the progress of been removed from most implementation. ...
TransitionEvent - Web APIs
playing. transitionrun An Event fired when a CSS transition is created, when it is added to a set of running transitions, though not nessarilty started transitionstart An Event fired when a CSS transition has started transitioning. Methods Also inherits properties from its parent Event. TransitionEvent.initTransitionEvent() Initializes a TransitionEvent created using the deprecated Document.createEvent("TransitionEvent") method. Specifications Specification Status Comment CSS TransitionsThe definition of 'TransitionEvent' in that specification. Working Draft Initial definition. ...
TreeWalker.currentNode - Web APIs
The TreeWalker.currentNode property represents the Node on which the TreeWalker is currently pointing at. Syntax node = treeWalker.currentNode; treeWalker.currentNode = node; Example var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); root = treeWalker.currentNode; // the root element as it is the first element! Specifications Specification Status Comment DOMThe definition of 'TreeWalker.currrentNode' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Specification Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'TreeWalker.curren...
TreeWalker.expandEntityReferences - Web APIs
flag indicating whether or not the children of entity reference nodes are visible to the TreeWalker. If this value is false, the children of entity reference nodes (as well as all of their descendants) are rejected. This takes precedence over the value of the TreeWalker.whatToShow method and the associated filter. Syntax expand = treeWalker.expandEntityReferences; Example var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); expand = treeWalker.expandEntityReferences; Specifications Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'TreeWalker.expandEntityReferences' in that specification. Obsolete Initial definiti...
TreeWalker.previousSibling() - Web APIs
The TreeWalker.previousSibling() method moves the current Node to its previous sibling, if any, and returns the found sibling. If there is no such node, return null and the current node is not changed. Syntax node = treeWalker.previousSibling(); Example var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); var node = treeWalker.previousSibling(); // returns null as there is no previous sibiling Specifications Specification Status Comment DOMThe definition of 'TreeWalker.previousSibling' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Specification Document Object Mod...
TreeWalker.root - Web APIs
Web › API › TreeWalker › root
The TreeWalker.root read-only property returns the node that is the root of what the TreeWalker traverses. Syntax root = TreeWalker.root; Example var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); root = treeWalker.root; // document.body in this case Specifications Specification Status Comment DOMThe definition of 'TreeWalker.root' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Specification Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'TreeWalker.root' in that specification. Obsolete Initial definition. ...
UIEvent() - Web APIs
Web › API › UIEvent › UIEvent
Obsolete Initial definition. ...
UIEvent.detail - Web APIs
Web › API › UIEvent › detail
etail read-only property, when non-zero, provides the current (or next, depending on the event) click count. For click or dblclick events, UIEvent.detail is the current click count. For mousedown or mouseup events, UIEvent.detail is 1 plus the current click count. For all other UIEvent objects, UIEvent.detail is always zero. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'UIEvent.detail' in that specification. Obsolete Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'UIEvent.detail' in that specification. Obsolete Initial definition. ...
UIEvent.view - Web APIs
Web › API › UIEvent › view
The UIEvent.view read-only property returns the WindowProxy object from which the event was generated. In browsers, this is the Window object the event happened in. Syntax var view = event.view; view is a reference to an AbstractView object. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'UIEvent' in that specification. Obsolete From Document Object Model (DOM) Level 2 Events Specification, changed the type of view from AbstractView to WindowProxy. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'UIEvent' in that specification. Obsolete Initial definition. ...
URL.searchParams - Web APIs
Web › API › URL › searchParams
ns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL. Note: This feature is available in Web Workers. Syntax const urlSearchParams = url.searchParams Value A URLSearchParams object. Examples If the URL of your page is https://example.com/?name=Jonathan%20Smith&age=18 you could parse out the name and age parameters using: let params = (new URL(document.location)).searchParams; let name = params.get('name'); // is the string "Jonathan Smith". let age = parseInt(params.get('age')); // is the number 18 Specifications Specification Status Comment URLThe definition of 'searchParams' in that specification. Living Standard Initial definition. ...
URLSearchParams.get() - Web APIs
Note: This feature is available in Web Workers. Syntax URLSearchParams.get(name) Parameters name The name of the parameter to return. Return value A USVString if the given search parameter is found; otherwise, null. ...
Using the User Timing API - Web APIs
at are part of the browser's performance timeline. There are two types of user defined timing entry types: the "mark" entry type and the "measure" entry type. mark events are named by the application and can be set at any location in an application. measure events are also named by the application but they are placed between two marks thus they are effectively a midpoint between two marks. This document shows how to create mark and measure performance entry types and how to use User Timing methods (which are extensions of the Performance interface) to retrieve and remove entries from the browser's performance timeline. A live version of the examples is available on Github, as is the source code. Pull requests, enhancement requests and bug reports are welcome. Performance marks A performance m...
User Timing API - Web APIs
at are part of the browser's performance timeline. There are two types of user defined timing event types: the "mark" event type and the "measure" event type. mark events are named by the application and can be set at any location in an application. measure events are also named by the application but they are placed between two marks thus they are effectively a midpoint between two marks. This document provides an overview of the mark and measure performance event types including the four User Timing methods that extend the Performance interface. For more details and example code regarding these two performance event types and the methods, see Using the User Timing API. Performance marks A performance mark is a named performance entry that is created by the application. The mark is a timestam...
VRStageParameters - Web APIs
tageParameters property. Properties VRStageParameters.sittingToStandingTransform Read only Contains a matrix that transforms the sitting-space view matrices of VRFrameData to standing-space. VRStageParameters.sizeX Read only Returns the width of the play-area bounds in meters. VRStageParameters.sizeY Read only Returns the depth of the play-area bounds in meters. ...
VTTCue - Web APIs
Web › API › VTTCue
o determine what the VTTCue.position is anchored to. The default is auto. VTTCue.size Returns a double representing the size of the cue, as a percentage of the video size. 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. Example HTML <video controls src="https://udn.realityripple.com/samples/c6/f8a3489533.webm"></video> CSS video { width: 320px; height: 180px; } JavaScript let video = document.querySelector('video'); video.addEventListener('loadedmetadata', () => { const track = video.addTextTrack("captions", "????Subtitles", "zh_CN"); track.mode = "showing"; const cueCn = new VTTCue(0...
validityState.badInput - Web APIs
he read-only badInput property of a ValidityState object indicates if the user has provided input that the browser is unable to convert. For example, if you have a number input element whose content is a string. Note: While this is unsupported in Internet Explorer, any non-numeric value will be dismissed from the field if it is a number input. Example <input type="number" id="age"> var input = document.getElementById("age"); if (input.validity.badInput) { console.log("Bad input detected..."); } else { console.log("Content of input ok."); } Specifications Specification Status Comment HTML Living StandardThe definition of 'ValidityState.badInput' in that specification. Living Standard Live Standard HTML 5.1The definition of 'ValidityState.badInput' in...
VideoPlaybackQuality.corruptedVideoFrames - Web APIs
a corrupted video frame. If a corrupted frame is dropped, then both corruptedVideoFrames and droppedVideoFrames are incremented. Example This example determines the percentage of frames which have been corrupted, and if the value is greater than 5%, calls a funciton called downgradeVideo() that would be implemented to switch to a different video that might tax the network less. var videoElem = document.getElementById("my_vid"); var quality = videoElem.getVideoPlaybackQuality(); if (quality.corruptedVideoFrames/quality.totalVideoFrames > 0.05) { downgradeVideo(videoElem); } Specifications Specification Status Comment Media Playback QualityThe definition of 'VideoPlaybackQuality: corruptedVideoFrames' in that specification. Editor's Draft ...
VideoPlaybackQuality.creationTime - Web APIs
rmined, see Performance.now(). Example This example calls getVideoPlaybackQuality() to obtain a VideoPlaybackQuality object, then determines what percentage of frames have been lost by either corruption or being dropped. If that exceeds 10% (0.1), a function called lostFramesThresholdExceeded() is called to, perhaps, update a quality indicator to show an increase in frame loss. var videoElem = document.getElementById("my_vid"); var quality = videoElem.getVideoPlaybackQuality(); if ((quality.corruptedVideoFrames + quality.droppedVideoFrames)/quality.totalVideoFrames > 0.1) { lostFramesThresholdExceeded(); } Specifications Specification Status Comment Media Playback QualityThe definition of 'VideoPlaybackQuality.corruptedVideoFrames' in that specification. Editor'...
VideoPlaybackQuality.totalFrameDelay - Web APIs
t any time. Try to avoid using it. ...
VideoPlaybackQuality.totalVideoFrames - Web APIs
media is reloaded or replaced. Example This example calls getVideoPlaybackQuality() to obtain a VideoPlaybackQuality object, then determines what percentage of frames have been lost by either corruption or being dropped. If that exceeds 10% (0.1), a function called lostFramesThresholdExceeded() is called to, perhaps, update a quality indicator to show an increase in frame loss. var videoElem = document.getElementById("my_vid"); var quality = videoElem.getVideoPlaybackQuality(); if ((quality.corruptedVideoFrames + quality.droppedVideoFrames)/quality.totalVideoFrames > 0.1) { lostFramesThresholdExceeded(); } A similar algorithm might be used to attempt to switch to a lower-resolution video that requires less bandwidth, in order to avoid dropping frames. Specifications Specification...
VideoTrack - Web APIs
the track. Returns null if the track was not created by a SourceBuffer or the SourceBuffer has been removed from the MediaSource.sourceBuffers attribute of its parent media source. Usage notes To get a VideoTrack for a given media element, use the element's videoTracks property, which returns a VideoTrackList object from which you can get the individual tracks contained in the media: var el = document.querySelector("video"); var tracks = el.videoTracks; You can then access the media's individual tracks using either array syntax or functions such as forEach(). This first example gets the first video track on the media: var firstTrack = tracks[0]; The next example scans through all of the media's video tracks, activating the first video track that is in the user's preferred language (taken ...
VideoTrackList: addtrack event - Web APIs
The addtrack event is fired when a track is added to a VideoTrackList. Bubbles No Cancelable No Interface TrackEvent Event handler property onaddtrack Examples Using addEventListener(): const videoElement = document.querySelector('video'); videoElement.videoTracks.addEventListener('addtrack', (event) => { console.log(`Video track: ${event.track.label} added`); }); Using the onaddtrack event handler property: const videoElement = document.querySelector('video'); videoElement.videoTracks.onaddtrack = (event) => { console.log(`Video track: ${event.track.label} added`); }; Specifications Specification Status HTML Living StandardThe definition of 'addtrack' in that specification. Living Standard ...
VideoTrackList.length - Web APIs
ideo tracks in the media. Syntax var trackCount = VideoTrackList.length; Value A number indicating how many video tracks are included in the VideoTrackList. Each track can be accessed by treating the VideoTrackList as an array of objects of type VideoTrack. Example This snippet gets the number of video tracks in the first <video> element found in the DOM by querySelector(). var videoElem = document.querySelector("video"); var numVideoTracks = 0; if (videoElem.videoTracks) { numVideoTracks = videoElem.videoTracks.length; } Note that this sample checks to be sure HTMLMediaElement.videoTracks is defined, to avoid failing on browsers without support for VideoTrack. Specifications Specification Status Comment HTML Living StandardThe definition of 'VideoTrackLis...
VideoTrackList.onaddtrack - Web APIs
first attached to the element; one addtrack event will occur for each video track in the media resource. Example This snippet establishes a handler for the addtrack event that calls a function, addToTrackList(), passing in the VideoTrack object representing the newly-added track. In this scenario, that function's role is to add the new track to a list of video tracks available to choose from. document.querySelector("video").videoTracks.onaddtrack = function(event) { addToTrackList(event.track); }; Specifications Specification Status Comment HTML Living StandardThe definition of 'VideoTrackList: onaddtrack' in that specification. Living Standard ...
VideoTrackList.onchange - Web APIs
EventListener(). Syntax VideoTrackList.onchange = eventHandler; Value Set onchange to a function that should be called whenever a track is made active. Example This snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track. ...
VideoTrackList.onremovetrack - Web APIs
ntListener(). Syntax VideoTrackList.onremovetrack = eventHandler; Value Set onremovetrack to a function that accepts as input a TrackEvent object which indicates in its track property which video track has been removed from the media element. Example This simple example just fetches the current number of video tracks in the media element whenever a track is removed from the media element. document.querySelector("my-video").videoTracks.onremovetrack = function(event) { myTrackCount = document.querySelector("my-video").videoTracks.length; }; The current number of video tracks remaining in the media element is obtained from VideoTrackList property length. Specifications Specification Status Comment HTML Living StandardThe definition of 'VideoTrackList: onremo...
VideoTrackList: removetrack event - Web APIs
The removetrack event is fired when a track is removed from a VideoTrackList. Bubbles No Cancelable No Interface TrackEvent Event handler property onremovetrack Examples Using addEventListener(): const videoElement = document.querySelector('video'); videoElement.videoTracks.addEventListener('removetrack', (event) => { console.log(`Video track: ${event.track.label} removed`); }); Using the onremovetrack event handler property: const videoElement = document.querySelector('video'); videoElement.videoTracks.onremovetrack = (event) => { console.log(`Video track: ${event.track.label} removed`); }; Specifications Specification Status HTML Living StandardThe definition of 'removetrack' in that specification. Livin...
VideoTrackList - Web APIs
on a media element, VideoTrackList lets you set event handlers on the addtrack and removetrack events, so that you can detect when tracks are added to or removed from the media element's stream. See onaddtrack and onremovetrack for details and examples. Examples Getting a media element's video track list To get a media element's VideoTrackList, use its videoTracks property. var videoTracks = document.querySelector("video").videoTracks; Monitoring track count changes In this example, we have an app that displays information about the number of channels available. To keep it up to date, handlers for the addtrack and removetrack events are set up. videoTracks.onaddtrack = updateTrackCount; videoTracks.onremovetrack = updateTrackCount; function updateTrackCount(event) { trackCount = videoTr...
Visual Viewport API - Web APIs
prevent multiple invocations of the transfrom that can occur when onresize and onscroll fire at the same time. Using requestAnimationFrame() ensures that the transform ocurrs before the next render. let pendingUpdate = false; function viewportHandler(event) { if (pendingUpdate) return; pendingUpdate = true; requestAnimationFrame(() => { pendingUpdate = false; var layoutViewport = document.getElementById('layoutViewport'); // Since the bar is position: fixed we need to offset it by the // visual viewport's offset from the layout viewport origin. var viewport = event.target; var offsetLeft = viewport.offsetLeft; var offsetTop = viewport.height - layoutViewport.getBoundingClientRect().height + viewport.offsetTop; // You could ...
WEBGL_debug_renderer_info - Web APIs
xtensions is disabled. This extension is available to both, WebGL1 and WebGL2 contexts. Constants ext.UNMASKED_VENDOR_WEBGL Vendor string of the graphics driver. ext.UNMASKED_RENDERER_WEBGL Renderer string of the graphics driver. ...
WEBGL_debug_shaders.getTranslatedShaderSource() - Web APIs
sion('WEBGL_debug_shaders').getTranslatedShaderSource(shader); Parameters shader A WebGLShader to get the translated source from. Return value A String containing the translated shader source. An empty string is returned, if: no source has been defined or, WebGLRenderingContext.compileShader() has not yet been called or, the translation for the shader failed. ...
WEBGL_lose_context.loseContext() - Web APIs
nd allows you to simulate losing the context of a WebGLRenderingContext context. It triggers the steps described in the WebGL specification for handling context lost. The context will remain lost until WEBGL_lose_context.restoreContext() is called. Syntax gl.getExtension('WEBGL_lose_context').loseContext(); Examples With this method, you can simulate the webglcontextlost event: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', function(e) { console.log(e); }, false); gl.getExtension('WEBGL_lose_context').loseContext(); // WebGLContextEvent event with type "webglcontextlost" is logged. Specifications Specification Status Comment WEBGL_lose_contextThe definition of 'WEBGL_lose_context...
WEBGL_lose_context.restoreContext() - Web APIs
The WEBGL_lose_context.restoreContext() method is part of the WebGL API and allows you to simulate restoring the context of a WebGLRenderingContext object. Syntax gl.getExtension('WEBGL_lose_context').restoreContext(); Errors thrown INVALID_OPERATION if the context was not lost. Examples With this method, you can simulate the webglcontextrestored event: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getExtension('WEBGL_lose_context').restoreContext(); Specifications Specification Status Comment WEBGL_lose_contextThe definition of 'WEBGL_lose_context.loseContext' in that specification. Recommendation Initial definition. ...
WEBGL_lose_context - Web APIs
, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. Methods WEBGL_lose_context.loseContext() Simulates losing the context. WEBGL_lose_context.restoreContext() Simulates restoring the context. Examples With this extension, you can simulate the webglcontextlost and webglcontextrestored events: const canvas = document.getElementById('canvas'); const gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', (event) => { console.log(event); }); gl.getExtension('WEBGL_lose_context').loseContext(); // WebGLContextEvent event with type "webglcontextlost" is logged. Specifications Specification Status Comment WEBGL_lose_contextThe definition of 'WEBGL_lose_context' ...
WakeLock.request() - Web APIs
Web › API › WakeLock › request
n dimming and locking. Syntax var wakeLock = navigator.wakeLock.request(type); Parameters type Options are as follows: 'screen': Requests a screen wake lock. Prevents devices from dimming or locking the screen. Return value A Promise that resolves with a WakeLockSentinel object. Exceptions NotAllowedError Thrown when wake lock is not available, which can happen because: Document is not allowed to use screen wake lock due to screen-wake-lock policy. Document is not fully active. Document is hidden. User Agent could not acquire platform's wake lock. Examples The following asynchronous function requests a WakeLockSentinel object. The request() method is wrapped in a try...catch statement to account for if the browser refuses the request for any reason. const r...
WakeLockSentinel - Web APIs
e WakeLockSentinel interface of the Screen Wake Lock API provides a handle to the underlying platform wake lock and can be manually released and reacquired. An Object representing the wake lock is returned via the navigator.wakelock.request() method. An acquired WakeLockSentinel can be released manually via the release() method, or automatically via the platform wake lock. This can happen if the document becomes inactive or looses visibility, if the device is low on power or the user turns on a power save mode. Releasing all WakeLockSentinel instances of a given wake lock type will cause the underlying platform wake lock to be released. Properties This interface provides the following properties. type Read only Returns a String representation of the currently acquired WakeLockSentinel type...
WebGL2RenderingContext - Web APIs
The WebGL2RenderingContext interface implements all members of the WebGLRenderingContext interface. ...
WebGLBuffer - Web APIs
r object does not define any methods or properties of its own and its content is not directly accessible. When working with WebGLBuffer objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindBuffer() WebGLRenderingContext.createBuffer() WebGLRenderingContext.deleteBuffer() WebGLRenderingContext.isBuffer() Examples Creating a buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLBuffer' in that specification. Recommendation Initial definition. ...
WebGLContextEvent.statusMessage - Web APIs
The read-only WebGLContextEvent.statusMessage property contains additional event status information, or is an empty string if no additional information is available. Examples The statusMessage property can contain a platform dependent string with details of an event. This can occur, for example, if the webglcontextcreationerror event is fired. var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextcreationerror', function(e) { console.log('WebGL context creation failed:' + e.statusMessage || 'Unknown error'); }, false); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLContextEvent.statusMessage' in that specification. Recommendation Initial definition...
WebGLContextEvent - Web APIs
om its parent interface, Event. WebGLContextEvent.statusMessage A read-only property containing additional information about the event. Methods This interface doesn't define any own methods, but inherits methods from its parent interface, Event. Examples With the help of the WEBGL_lose_context extension, you can simulate the webglcontextlost and webglcontextrestored events: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', function(e) { console.log(e); }, false); gl.getExtension('WEBGL_lose_context').loseContext(); // WebGLContextEvent event with type "webglcontextlost" is logged. Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLContextEvent' in that ...
WebGLFramebuffer - Web APIs
thods or properties of its own and its content is not directly accessible. When working with WebGLFramebuffer objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindFramebuffer() WebGLRenderingContext.createFramebuffer() WebGLRenderingContext.deleteFramebuffer() WebGLRenderingContext.isFramebuffer() Examples Creating a frame buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createFramebuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLFramebuffer' in that specification. Recommendation Initial definition. ...
WebGLRenderbuffer - Web APIs
or properties of its own and its content is not directly accessible. When working with WebGLRenderbuffer objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindRenderbuffer() WebGLRenderingContext.createRenderbuffer() WebGLRenderingContext.deleteRenderbuffer() WebGLRenderingContext.isRenderbuffer() Examples Creating a render buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createRenderbuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderbuffer' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.bindBuffer() - Web APIs
Buffer. An attempt to bind the buffer to another target will throw an INVALID_OPERATION error and the current buffer binding will remain the same. A WebGLBuffer which has been marked for deletion with deleteBuffer cannot be (re-)bound. An attempt to do so will generate an INVALID_OPERATION error, and the current binding will remain untouched. Examples Binding a buffer to a target var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); Getting current bindings To check the current buffer bindings, query the ARRAY_BUFFER_BINDING and ELEMENT_ARRAY_BUFFER_BINDING constants. gl.getParameter(gl.ARRAY_BUFFER_BINDING); gl.getParameter(gl.ELEMENT_ARRAY_BUFFER_BINDING); Specifications Sp...
WebGLRenderingContext.bindFramebuffer() - Web APIs
sed as a destination for drawing, rendering, clearing, and writing operations. gl.READ_FRAMEBUFFER: Used as a source for reading operations. framebuffer A WebGLFramebuffer object to bind. Return value None. Exceptions A gl.INVALID_ENUM error is thrown if target is not gl.FRAMEBUFFER, gl.DRAW_FRAMEBUFFER, or gl.READ_FRAMEBUFFER. Examples Binding a frame buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); Getting current bindings To check the current frame buffer binding, query the FRAMEBUFFER_BINDING constant. gl.getParameter(gl.FRAMEBUFFER_BINDING); Specifications Specification Status Comment WebGL 1.0The definit...
WebGLRenderingContext.bindRenderbuffer() - Web APIs
nderbuffer); Parameters target A GLenum specifying the binding point (target). Possible values: gl.RENDERBUFFER: Buffer data storage for single images in a renderable internal format. renderbuffer A WebGLRenderbuffer object to bind. Return value None. Exceptions A gl.INVALID_ENUM error is thrown if target is not gl.RENDERBUFFER. Examples Binding a renderbuffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderbuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer); Getting current bindings To check the current renderbuffer binding, query the RENDERBUFFER_BINDING constant. gl.getParameter(gl.RENDERBUFFER_BINDING); Specifications Specification Status Comment WebGL 1.0The ...
WebGLRenderingContext.bindTexture() - Web APIs
alues are available additionally: gl.TEXTURE_3D: A three-dimensional texture. gl.TEXTURE_2D_ARRAY: A two-dimensional array texture. texture A WebGLTexture object to bind. Return value None. Exceptions A gl.INVALID_ENUM error is thrown if target is not gl.TEXTURE_2D, gl.TEXTURE_CUBE_MAP, gl.TEXTURE_3D, or gl.TEXTURE_2D_ARRAY. Examples Binding a texture var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); Getting current bindings To check the current texture binding, query the gl.TEXTURE_BINDING_2D or gl.TEXTURE_BINDING_CUBE_MAP constants. gl.getParameter(gl.TEXTURE_BINDING_2D); Specifications Specification Status Comment WebGL 1.0...
WebGLRenderingContext.bufferData() - Web APIs
start reading the buffer. length Optional A GLuint defaulting to 0. Return value None. Exceptions A gl.OUT_OF_MEMORY error is thrown if the context is unable to create a data store with the given size. A gl.INVALID_VALUE error is thrown if size is negative. A gl.INVALID_ENUM error is thrown if target or usage are not one of the allowed enums. Examples Using bufferData var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, 1024, gl.STATIC_DRAW); Getting buffer information To check the current buffer usage and buffer size, use the WebGLRenderingContext.getBufferParameter() method. gl.getBufferParameter(gl.ARRAY_BUFFER, gl.BUFFER_SIZE); gl.getBufferP...
WebGLRenderingContext.bufferSubData() - Web APIs
et A GLuint specifying the element index offset where to start reading the buffer. length Optional A GLuint defaulting to 0. Return value None. Exceptions A gl.INVALID_VALUE error is thrown if the data would be written past the end of the buffer or if data is null. A gl.INVALID_ENUM error is thrown if target is not one of the allowed enums. Examples Using bufferSubData var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, 1024, gl.STATIC_DRAW); gl.bufferSubData(gl.ARRAY_BUFFER, 512, data); Specifications Specification Status Comment WebGL 1.0The definition of 'bufferSubData' in that specification. Recommendation Initia...
WebGLRenderingContext.canvas - Web APIs
he context. It might be null if it is not associated with a <canvas> element or an OffscreenCanvas object. Syntax gl.canvas; Return value Either a HTMLCanvasElement or OffscreenCanvas object or null. Examples Canvas element Given this <canvas> element: <canvas id="canvas"></canvas> You can get back a reference to it from the WebGLRenderingContext using the canvas property: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.canvas; // HTMLCanvasElement Offscreen canvas Example using the experimental OffscreenCanvas object. var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext('webgl'); gl.canvas; // OffscreenCanvas Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderin...
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
are a mix of renderbuffers and textures. When using the OVR_multiview2 extension, the following value can be returned additionally: ext.FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR: If baseViewIndex is not the same for all framebuffer attachment points where the value of FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is not NONE, the framebuffer is considered incomplete. Examples var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); // ... gl.checkFramebufferStatus(gl.FRAMEBUFFER); Specifications Specification Status Comment WebGL 1.0The definition of 'checkFramebufferStatus' in that specification. Recommendation Initial definition for WebGL. OpenGL ES 2.0The definition of 'glCh...
WebGLRenderingContext.commit() - Web APIs
some drawing using the gl context ... ...
WebGLRenderingContext.createBuffer() - Web APIs
The WebGLRenderingContext.createBuffer() method of the WebGL API creates and initializes a WebGLBuffer storing data such as vertices or colors. Syntax WebGLBuffer gl.createBuffer(); Parameters None. Return value A WebGLBuffer storing data such as vertices or colors. Examples Creating a buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'createBuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenBuffers' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.createFramebuffer() - Web APIs
The WebGLRenderingContext.createFramebuffer() method of the WebGL API creates and initializes a WebGLFramebuffer object. Syntax WebGLFramebuffer gl.createFramebuffer(); Parameters None. Return value A WebGLFramebuffer object. Examples Creating a frame buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'createFramebuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenFramebuffers' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.createRenderbuffer() - Web APIs
The WebGLRenderingContext.createRenderbuffer() method of the WebGL API creates and initializes a WebGLRenderbuffer object. Syntax WebGLRenderbuffer gl.createRenderbuffer(); Parameters None. Return value A WebGLRenderbuffer object that stores data such an image, or can be source or target of an rendering operation. Examples Creating a render buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderBuffer = gl.createRenderBuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'createRenderbuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenRenderbuffers' in that specification. Standard Man page of the (similar) OpenGL API...
WebGLRenderingContext.createTexture() - Web APIs
The WebGLRenderingContext.createTexture() method of the WebGL API creates and initializes a WebGLTexture object. Syntax WebGLTexture gl.createTexture(); Parameters None. Return value A WebGLTexture object to which images can be bound to. Examples See also the WebGL tutorial on Using textures in WebGL. Creating a texture var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); Specifications Specification Status Comment WebGL 1.0The definition of 'createTexture' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenTextures' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.deleteBuffer() - Web APIs
The WebGLRenderingContext.deleteBuffer() method of the WebGL API deletes a given WebGLBuffer. This method has no effect if the buffer has already been deleted. Syntax void gl.deleteBuffer(buffer); Parameters buffer A WebGLBuffer object to delete. Return value None. Examples Deleting a buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); // ... gl.deleteBuffer(buffer); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteBuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteBuffers' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.deleteFramebuffer() - Web APIs
The WebGLRenderingContext.deleteFramebuffer() method of the WebGL API deletes a given WebGLFramebuffer object. This method has no effect if the frame buffer has already been deleted. Syntax void gl.deleteFramebuffer(framebuffer); Parameters framebuffer A WebGLFramebuffer object to delete. Return value None. Examples Deleting a frame buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); // ... gl.deleteFramebuffer(framebuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteFramebuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteFramebuffers' in that specification. Standard ...
WebGLRenderingContext.deleteProgram() - Web APIs
The WebGLRenderingContext.deleteProgram() method of the WebGL API deletes a given WebGLProgram object. This method has no effect if the program has already been deleted. Syntax void gl.deleteProgram(program); Parameters program A WebGLProgram object to delete. Return value None. Examples Deleting a program var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var program = gl.createProgram(); // ... gl.deleteProgram(program); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteProgram' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteProgram' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.deleteRenderbuffer() - Web APIs
The WebGLRenderingContext.deleteRenderbuffer() method of the WebGL API deletes a given WebGLRenderbuffer object. This method has no effect if the render buffer has already been deleted. Syntax void gl.deleteRenderbuffer(renderbuffer); Parameters renderbuffer A WebGLRenderbuffer object to delete. Return value None. Examples Deleting a renderbuffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderbuffer = gl.createRenderbuffer(); // ... gl.deleteRenderbuffer(renderbuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteRenderbuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteRenderbuffers' in that specification. ...
WebGLRenderingContext.deleteTexture() - Web APIs
The WebGLRenderingContext.deleteTexture() method of the WebGL API deletes a given WebGLTexture object. This method has no effect if the texture has already been deleted. Syntax void gl.deleteTexture(texture); Parameters texture A WebGLTexture object to delete. Return value None. Examples Deleting a texture var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); // ... gl.deleteTexture(texture); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteTexture' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteTextures' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.drawingBufferHeight - Web APIs
ht of the current drawing buffer. It should match the height attribute of the <canvas> element associated with this context, but might differ if the implementation is not able to provide the requested height. Syntax gl.drawingBufferHeight; Examples Given this <canvas> element: <canvas id="canvas"></canvas> You can get the height of the drawing buffer with the following lines: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.drawingBufferHeight; // 150 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderingContext.drawingBufferHeight' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.drawingBufferWidth - Web APIs
width of the current drawing buffer. It should match the width attribute of the <canvas> element associated with this context, but might differ if the implementation is not able to provide the requested width. Syntax gl.drawingBufferWidth; Examples Given this <canvas> element: <canvas id="canvas"></canvas> You can get the width of the drawing buffer with the following lines: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.drawingBufferWidth; // 300 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderingContext.drawingBufferWidth' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.getContextAttributes() - Web APIs
urns a WebGLContextAttributes object that contains the actual context parameters. Might return null, if the context is lost. Syntax gl.getContextAttributes(); Return value A WebGLContextAttributes object that contains the actual context parameters, or null if the context is lost. ...
WebGLRenderingContext.getExtension() - Web APIs
ame); Parameters name A String for the name of the WebGL extension to enable. Return value A WebGL extension object, or null if name does not match (case-insensitive) to one of the strings in WebGLRenderingContext.getSupportedExtensions. Examples Once a WebGL extension is enabled, you are able to use the methods, properties or constants that this extension object provides. var canvas = document.getElementById('canvas'); gl = canvas.getContext('webgl'); gl.getExtension('WEBGL_lose_context').loseContext(); WebGL extensions Extensions for the WebGL API are registered in the WebGL Extension Registry. The current extensions are: ANGLE_instanced_arrays EXT_blend_minmax EXT_color_buffer_float EXT_color_buffer_half_float EXT_disjoint_timer_query EXT_float_blend EXT_frag_depth E...
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
l.LOW_INT, gl.MEDIUM_INT, or gl.HIGH_INT. Return value A WebGLShaderPrecisionFormat object or null, if an error occurs. Exceptions gl.INVALID_ENUM if the shader or precision types aren't recognized. gl.INVALID_OPERATION if the shader compiler isn't supported. Examples The following code gets the precision format of a gl.VERTEX_SHADER with a gl.MEDIUM_FLOAT precision type. var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT); // WebGLShaderPrecisionFormat { rangeMin: 127, rangeMax: 127, precision: 23 } Specifications Specification Status Comment WebGL 1.0The definition of 'getShaderPrecisionFormat' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.getSupportedExtensions() - Web APIs
] See also the WebGLRenderingContext.getExtension() method to get a specific extension object. ...
WebGLRenderingContext.isBuffer() - Web APIs
The WebGLRenderingContext.isBuffer() method of the WebGL API returns true if the passed WebGLBuffer is valid and false otherwise. Syntax GLboolean gl.isBuffer(buffer); Parameters buffer A WebGLBuffer to check. Return value A GLboolean indicating whether or not the buffer is valid. Examples Creating a buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.isBuffer(buffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isBuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsBuffer' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.isFramebuffer() - Web APIs
The WebGLRenderingContext.isFramebuffer() method of the WebGL API returns true if the passed WebGLFramebuffer is valid and false otherwise. Syntax GLboolean gl.isFramebuffer(framebuffer); Parameters framebuffer A WebGLFramebuffer to check. Return value A GLboolean indicating whether or not the frame buffer is valid. Examples Checking a frame buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); gl.isFramebuffer(framebuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isFramebuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsFramebuffer' in that specification. Standard Man page ...
WebGLRenderingContext.isProgram() - Web APIs
The WebGLRenderingContext.isProgram() method of the WebGL API returns true if the passed WebGLProgram is valid, false otherwise. Syntax GLboolean gl.isProgram(program); Parameters program A WebGLProgram to check. Return value A GLboolean indicating whether or not the program is valid. Examples Checking a program var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var program = gl.createProgram(); // ... gl.isProgram(program); Specifications Specification Status Comment WebGL 1.0The definition of 'isProgram' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsProgram' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.isRenderbuffer() - Web APIs
The WebGLRenderingContext.isRenderbuffer() method of the WebGL API returns true if the passed WebGLRenderbuffer is valid and false otherwise. Syntax GLboolean gl.isRenderbuffer(renderbuffer); Parameters renderbuffer A WebGLRenderbuffer to check. Return value A GLboolean indicating whether or not the renderbuffer is valid. Examples Checking a renderbuffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderbuffer = gl.createRenderbuffer(); gl.isRenderbuffer(renderbuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isRenderbuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsRenderbuffer' in that specification. Standard ...
WebGLRenderingContext.isShader() - Web APIs
The WebGLRenderingContext.isShader() method of the WebGL API returns true if the passed WebGLShader is valid, false otherwise. Syntax GLboolean gl.isShader(shader); Parameters shader A WebGLShader to check. Return value A GLboolean indicating whether or not the shader is valid. Examples Checking a shader var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var shader = gl.createShader(gl.VERTEX_SHADER); // ... gl.isShader(shader); Specifications Specification Status Comment WebGL 1.0The definition of 'isShader' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsShader' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.isTexture() - Web APIs
The WebGLRenderingContext.isTexture() method of the WebGL API returns true if the passed WebGLTexture is valid and false otherwise. Syntax GLboolean gl.isTexture(texture); Parameters texture A WebGLTexture to check. Return value A GLboolean indicating whether or not the texture is valid. Examples Checking a texture var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); gl.isTexture(texture); Specifications Specification Status Comment WebGL 1.0The definition of 'isTexture' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsTexture' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.makeXRCompatible() - Web APIs
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.readPixels() - Web APIs
e is not an accepted value. A gl.INVALID_OPERATION error is thrown if type is gl.UNSIGNED_SHORT_5_6_5 and format is not gl.RGB. type is gl.UNSIGNED_SHORT_4_4_4_4 and format is not gl.RGBA. type does not match the typed array type of pixels. A gl.INVALID_FRAMEBUFFER_OPERATION error is thrown if the currently bound framebuffer is not framebuffer complete. ...
WebGLShaderPrecisionFormat.precision - Web APIs
The read-only WebGLShaderPrecisionFormat.precision property returns the number of bits of precision that can be represented. For integer formats this value is always 0. Examples var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision; // 23 gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).precision; // 0 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLShaderPrecisionFormat.precision' in that specification. Recommendation Initial definition. ...
WebGLShaderPrecisionFormat.rangeMax - Web APIs
The read-only WebGLShaderPrecisionFormat.rangeMax property returns the base 2 log of the absolute value of the maximum value that can be represented. Examples var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).rangeMax; // 127 gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).rangeMax; // 24 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLShaderPrecisionFormat.rangeMax' in that specification. Recommendation Initial definition. ...
WebGLShaderPrecisionFormat.rangeMin - Web APIs
The read-only WebGLShaderPrecisionFormat.rangeMin property returns the base 2 log of the absolute value of the minimum value that can be represented. Examples var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).rangeMin; // 127 gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).rangeMin; // 24 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLShaderPrecisionFormat.rangeMin' in that specification. Recommendation Initial definition. ...
WebGLShaderPrecisionFormat - Web APIs
Format.rangeMax Read only The base 2 log of the absolute value of the maximum value that can be represented. WebGLShaderPrecisionFormat.precision Read only The number of bits of precision that can be represented. For integer formats this value is always 0. Examples A WebGLShaderPrecisionFormat object is returned by the WebGLRenderingContext.getShaderPrecisionFormat() method. var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT); // WebGLShaderPrecisionFormat { rangeMin: 127, rangeMax: 127, precision: 23 } Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLShaderPrecisionFormat' in that specification. Recommendation Initial definition. ...
WebGLTexture - Web APIs
ct does not define any methods or properties of its own and its content is not directly accessible. When working with WebGLTexture objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindTexture() WebGLRenderingContext.createTexture() WebGLRenderingContext.deleteTexture() WebGLRenderingContext.isTexture() Examples Creating a texture var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLTexture' in that specification. Recommendation Initial definition. ...
WebGLUniformLocation - Web APIs
der program. Description The WebGLUniformLocation object does not define any methods or properties of its own and its content is not directly accessible. When working with WebGLUniformLocation objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.getUniformLocation() WebGLRenderingContext.uniform() Examples Getting an uniform location var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var location = gl.getUniformLocation(WebGLProgram, 'uniformName'); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLUniformLocation' in that specification. Recommendation Initial definition. ...
Boilerplate 1 - Web APIs
as>Your browser does not seem to support HTML5 canvas.</canvas> CSS body { text-align : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } JavaScript function getRenderingContext() { var canvas = document.querySelector("canvas"); canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { var paragraph = document.querySelector("p"); paragraph.innerHTML = "Failed to get WebGL context." + "Your browser or device may not support WebGL."; return null; } gl.viewport(0...
Canvas size and WebGL - Web APIs
ur browser does not seem to support HTML5 canvas.</canvas> <canvas>Your browser does not seem to support HTML5 canvas.</canvas> body { text-align : center; } canvas { display : inline-block; width : 120px; height : 80px; margin : auto; padding : 0; border : none; background-color : black; } window.addEventListener("load", function() { "use strict" var firstCanvas = document.getElementsByTagName("canvas")[0], secondCanvas = document.getElementsByTagName("canvas")[1]; firstCanvas.width = firstCanvas.clientWidth; firstCanvas.height = firstCanvas.clientHeight; [firstCanvas, secondCanvas].forEach(function(canvas) { var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { document.querySelector("p").innerHTML...
Clearing by clicking - Web APIs
-block; font-size : inherit; margin : auto; padding : 0.6em; } window.addEventListener("load", function setupWebGL (evt) { "use strict" // Cleaning after ourselves. The event handler removes // itself, because it only needs to run once. window.removeEventListener(evt.type, setupWebGL, false); // Adding the same click event handler to both canvas and // button. var canvas = document.querySelector("#canvas-view"); var button = document.querySelector("#color-switcher"); canvas.addEventListener("click", switchColor, false); button.addEventListener("click", switchColor, false); // A variable to hold the WebGLRenderingContext. var gl; // The click event handler. function switchColor () { // Referring to the externally defined gl variable. // If undefined, ...
Clearing with colors - Web APIs
cope. We are giving the event // handler a name (setupWebGL) so that we can refer to the // function object within the function itself. window.addEventListener("load", function setupWebGL (evt) { "use strict" // Cleaning after ourselves. The event handler removes // itself, because it only needs to run once. window.removeEventListener(evt.type, setupWebGL, false); // References to the document elements. var paragraph = document.querySelector("p"), canvas = document.querySelector("canvas"); // Getting the WebGL rendering context. var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); // If failed, inform user of failure. Otherwise, initialize // the drawing buffer (the viewport) and clear the context // with a solid color. if (!gl) { ...
WebGL constants - Web APIs
A list is provided below. ...
Data in WebGL - Web APIs
Web › API › WebGL API › Data
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 o...
Matrix math for the web - Web APIs
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 moveMe.style.transform = matrix3dRule; View on JSFiddle Scale matrix A scale matrix makes something larger or smaller in one or more of the three dimensions: width, height, and depth. In typic...
Animating textures in WebGL - Web APIs
and vertex math. You'll need to include it if you create your own project based on this code. Our sample loads a copy from a CDN in our HTML's <head>. ...
Getting started with WebGL - Web APIs
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 browser or machine may not support it."); return; } // Set clear color to black, fully opaque gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear the color buffer with specifi...
WebGL best practices - Web APIs
General Topics Address and eliminate WebGL errors Your application should run without generating any WebGL errors (as returned by getError). ...
WebGL model view projection - Web APIs
This example will create a custom WebGLBox object that will draw a 2D box on the screen. Note: The code for each WebGLBox example is available in this github repo and is organized by section. In addition there is a JSFiddle link at the bottom of each section. ...
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
and peer connections First, the signaling channel needs to be opened and the RTCPeerConnection needs to be created. The STUN server listed here is obviously not a real one; you'll need to replace stun.myserver.tld with the address of a real STUN server. const constraints = { audio: true, video: true }; const config = { iceServers: [{ urls: "stun:stun.mystunserver.tld" }] }; const selfVideo = document.querySelector("video.selfview"); const remoteVideo = document.querySelector("video.remoteview"); const signaler = new SignalingChannel(); const pc = new RTCPeerConnection(config); This code also gets the <video> elements using the classes "selfview" and "remoteview"; these will contain, respectively, the local user's self-view and the view of the incoming stream from the remote peer. Connecti...
Introduction to WebRTC protocols - Web APIs
ribing the multimedia content of the connection such as resolution, formats, codecs, encryption, etc. so that both peers can understand each other once the data is transferring. This is, in essence, the metadata describing the content and not the media content itself. Technically, then, SDP is not truly a protocol, but a data format used to describe connection that shares media between devices. Documenting SDP is well outside the scope of this documentation; however, there are a few things worth noting here. Structure SDP consists of one or more lines of UTF-8 text, each beginning with a one-character type, followed by an equals sign ("="), followed by structured text comprising a value or description, whose format depends on the type. The lines of text that begin with a given letter are gener...
WebRTC API - Web APIs
media, as well as to exchange arbitrary data between browsers without requiring an intermediary. The set of standards that comprise WebRTC makes it possible to share data and perform teleconferencing peer-to-peer, without requiring that the user installs plug-ins or any other third-party software. WebRTC consists of several interrelated APIs and protocols which work together to achieve this. The documentation you'll find here will help you understand the fundamentals of WebRTC, how to set up and use both data and media connections, and more. Interoperability Because implementations of WebRTC are still evolving, and because each browser has different levels of support for codecs and WebRTC features, you should strongly consider making use of the Adapter.js library provided by Google before you b...
WebRTC Statistics API - Web APIs
This object contains a Map of named dictionaries based on RTCStats and its affiliated types. This example specifically looks for the report whose type is inbound-rtp and whose k...
Writing a WebSocket server in C# - Web APIs
<!doctype html> <style> textarea { vertical-align: bottom; } #output { overflow: auto; } #output > p { overflow-wrap: break-word; } #output span { color: blue; } #output span.error { color: red; } </style> <h2>WebSocket Test</h2> <textarea cols=60 rows=6></textarea> <button>send</button> <div id=output></div> <script> // http://www.websocket.org/echo.html var button = document.querySelector("button"), output = document.querySelector("#output"), textarea = document.querySelector("textarea"), // wsUri = "ws://echo.websocket.org/", wsUri = "ws://127.0.0.1/", websocket = new WebSocket(wsUri); button.addEventListener("click", onClickButton); websocket.onopen = function (e) { writeToScreen("CONNECTED"); doSend...
Lighting a WebXR setting - Web APIs
nd orientation of the objects in the scene, along with information about the materials they're made of, then returns data you can use to create virtual light source objects that approximately match the real world's lighting. The specifics of how lighting estimation works, especially in the context of the proposed API, is out of scope for the moment. Once the API has stabilized, we'll update this documentation with the details. Security and privacy concerns There are a number of potential security issues involved with collecting all of this data in order to generate and apply lighting to your virtual objects using real-world data. Of course, many AR applications make it pretty clear where the user is located. If the user is running an app called Touring the Louvre, there's a very good chance th...
WebXR Device API - Web APIs
o define the boundaries of where the viewer can safely move about without leaving the area tracked by their XR hardware or colliding with a physical obstacle. On devices which support it, bounded-floor can be a useful tool in your repertoire. Making it interactive Movement, orientation, and motion: A WebXR example In this example and tutorial, we use information learned throughout the WebXR documentation to create a scene containing a rotating cube which the user can move around using both VR headset and keyboard and mouse. Inputs and input sources A guide to input sources and how to efficiently manage the input devices being used to control the WebXR session, and how to receive and process user inputs from those devices. Targeting and hit detection How to use an input source's targetin...
Web Budget API - Web APIs
Concepts and Usage TBD Interfaces BudgetService Provides a programmatic interface to the user agent's budget service. It is available in both document and worker environments. BudgetState Provides the amount of the user agent's processing budget at a specific point in time. Specifications Specification Status Comment Web Budget API Draft Initial definition. ...
Web Storage API - Web APIs
ype (session or local.) Window The Web Storage API extends the Window object with two new properties -- Window.sessionStorage and Window.localStorage -- which provide access to the current domain's session and local Storage objects respectively, and a Window.onstorage event handler that fires when a storage area changes (e.g. a new item is stored.) StorageEvent The storage event is fired on a document's Window object when a storage area changes. Examples To illustrate some typical web storage usage, we have created a simple example, imaginatively called Web Storage Demo. The landing page provides controls that can be used to customize the colour, font and decorative image. When you choose different options, the page is instantly updated; in addition your choices are stored in localStorage, ...
Functions and classes available to Web Workers - Web APIs
r iframes) with the same origin (usually pages from the same site). 38 (38) No support No support No support Cache Cache API provides the ability to programmatically control cache storage associated with current origin. (Yes) No support 43 ? Channel Messaging API Allows two separate scripts running in different browsing contexts attached to the same document (e.g., two IFrames, or the main document and an IFrame, two documents via a SharedWorker, or two workers) to communicate directly via two ports. 41 (41) (Yes) (Yes) (Yes) Console API Provides access to the browser's debugging console (e.g., the Web Console in Firefox). The specifics of how it works vary from browser to browser, but there is a de facto set of features that ...
WheelEvent() - Web APIs
ls. DOM_DELTA_LINE 0x01 The delta values are specified in lines. DOM_DELTA_PAGE 0x02 The delta values are specified in pages. The WheelEventInit dictionary also accepts fields from the MouseEventInit, UIEventInit and EventInit dictionaries. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'WheelEvent()' in that specification. Obsolete Initial definition ...
WheelEvent.deltaMode - Web APIs
DOM_DELTA_LINE 0x01 The delta values are specified in lines. DOM_DELTA_PAGE 0x02 The delta values are specified in pages. Syntax var unit = event.deltaMode; Example var syntheticEvent = new WheelEvent("syntheticWheel", {"deltaX": 4, "deltaMode": 0}); console.log(syntheticEvent.deltaMode); Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'WheelEvent.deltaMode' in that specification. Obsolete Initial definition. ...
WheelEvent.deltaX - Web APIs
Web › API › WheelEvent › deltaX
The WheelEvent.deltaX read-only property is a double representing the horizontal scroll amount in the WheelEvent.deltaMode unit. Syntax var dX = event.deltaX; Example var syntheticEvent = new WheelEvent("syntheticWheel", {"deltaX": 4, "deltaMode": 0}); console.log(syntheticEvent.deltaX); Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'WheelEvent.deltaX' in that specification. Obsolete Initial definition. ...
WheelEvent.deltaY - Web APIs
Web › API › WheelEvent › deltaY
The WheelEvent.deltaY read-only property is a double representing the vertical scroll amount in the WheelEvent.deltaMode unit. Syntax var dY = event.deltaY; Example var syntheticEvent = new WheelEvent("syntheticWheel", {"deltaY": 4, "deltaMode": 0}); console.log(syntheticEvent.deltaY); Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'WheelEvent.deltaY' in that specification. Obsolete Initial definition. ...
WheelEvent.deltaZ - Web APIs
Web › API › WheelEvent › deltaZ
The WheelEvent.deltaZ read-only property is a double representing the scroll amount along the z-axis, in the WheelEvent.deltaMode unit. Syntax var dZ = event.deltaZ; Example var syntheticEvent = new WheelEvent("syntheticWheel", {"deltaZ": 4, "deltaMode": 0}); console.log(syntheticEvent.deltaZ); Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'WheelEvent.deltaZ' in that specification. Obsolete Initial definition. ...
WheelEvent - Web APIs
t.DOM_DELTA_PAGE 0x02 The delta* values are specified in pages. Methods This interface doesn't define any specific methods, but inherits methods from its ancestors, MouseEvent, UIEvent, and Event. Specifications Specification Status Comment UI EventsThe definition of 'The WheelEvent interface' in that specification. Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'WheelEvent' in that specification. Obsolete Initial definition. ...
Window: afterprint event - Web APIs
The afterprint event is fired after the associated document has started printing or the print preview has been closed. Bubbles No Cancelable No Interface Event Event handler property onafterprint Examples Using addEventListener(): window.addEventListener('afterprint', (event) => { console.log('After print'); }); Using the onafterprint event handler property: window.onafterprint = (event) => { console.log('After print'); }; Specifications Specification Status HTML Living Standard Living Standard ...
Window: beforeprint event - Web APIs
The beforeprint event is fired when the associated document is about to be printed or previewed for printing. Bubbles No Cancelable No Interface Event Event handler property onbeforeprint Examples Using addEventListener(): window.addEventListener('beforeprint', (event) => { console.log('Before print'); }); Using the onbeforeprint event handler property: window.onbeforeprint = (event) => { console.log('Before print'); }; Specifications Specification Status HTML Living Standard Living Standard ...
Window.captureEvents() - Web APIs
="en"> <head> <!-- ... --> <script> function reg() { window.captureEvents(Event.CLICK); window.onclick = page_click; } function page_click() { alert('page click event detected!'); } </script> </head> <body onload="reg();"> <p>click anywhere on this page.</p> </body> </html> Notes Events raised in the DOM by user activity (such as clicking buttons or shifting focus away from the current document) generally pass through the high-level window and document objects first before arriving at the object that initiated the event. When you call the captureEvents() method on the window, events of the type you specify (for example, Event.CLICK) no longer pass through to "lower" objects in the hierarchy. In order for events to "bubble up" in the way that they normally do, you must call window.relea...
Window.clearImmediate() - Web APIs
w.setImmediate. This method is not expected to become standard, and is only implemented by recent builds of Internet Explorer and Node.js 0.10+. It meets resistance both from Gecko (Firefox) and Webkit (Google/Apple). Syntax window.clearImmediate( immediateID ) where immediateID is a ID returned by window.setImmediate. Examples let immediateID = setImmediate(() => { // Run some code } document.getElementById("button") .addEventListener(() => { clearImmediate(immediateID); }); Specifications Specification Status Comment Efficient Script Yielding The definition of 'setImmediate' in that specification. Editor's Draft Initial definition. ...
Window.crypto - Web APIs
Web › API › Window › crypto
to; // 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.customElements - Web APIs
Specification Specification Status Comment HTML Living StandardThe definition of 'window.customElements' in that specifi...
Window: error event - Web APIs
tarea> </div> CSS body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } button { height: 2rem; margin: .5rem; } img { width: 0; height: 0; } JS const log = document.querySelector('.event-log-contents'); window.addEventListener('error', (event) => { log.textContent = log.textContent + `${event.type}: ${event.message}\n`; console.log(event) }); const scriptError = document.querySelector('#script-error'); scriptError.addEventListener('click', () => { const badCode = 'const s;'; eval(badCode); }); Result Specifications Specificat...
Window.forward() - Web APIs
Web › API › Window › forward
This was a Firefox-specific method and was removed in Firefox 31. Note: Use the standard window.history.forward() method instead. Syntax window.forward(); Parameters None Return value undefined. ...
Window.frameElement - Web APIs
The Window.frameElement property returns the element (such as <iframe> or <object>) in which the window is embedded. Note: Despite this property's name, it works for documents embedded within any embedding point, including <object>, <iframe>, or <embed>. Syntax const frameEl = window.frameElement Value The element which the window is embedded into. If the window isn't embedded into another document, or if the document into which it's embedded has a different origin, the value is null instead. Example const frameEl = window.frameElement; // If we're embedded, change the containing element's URL to 'http://mozilla.org/' if (frameEl) { frameEl.src = 'http://mozilla.org/'; } Specifications Specification Status Comment HTML Living StandardThe definition of 'W...
Window.length - Web APIs
Web › API › Window › length
Returns the number of frames (either <frame> or <iframe> elements) in the window. Syntax framesCount = window.length; framesCount is the number of frames. Example if (window.length) { // this is a document with subframes } Specifications Specification Status Comment HTML Living StandardThe definition of 'Window.length' in that specification. Living Standard HTML5The definition of 'Window.length' in that specification. Recommendation ...
Window.localStorage - Web APIs
localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends -- that is, when the page is closed. (Data in a localStorage object created in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.) Data stored in either localStorage is specific to the protocol of the page. ...
Window: message event - Web APIs
other browsing context. ...
Window.mozPaintCount - Web APIs
Obsolete since Gecko 72 (Firefox 72 / Thunderbird 72 / SeaMonkey 2.69)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. Returns the number of times the current document has been painted to the screen in this window. Syntax var paintCount = window.mozPaintCount; paintCount stores the window.mozPaintCount property value. The window.mozPaintCount value is a long long, and starts at zero when the document is first created, incrementing by one each time the document is painted. Specification Not part of any W3C technical specification or recommendation. ...
Privileged features - Web APIs
MSIE 6, the nearest equivalent to this 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 th...
Window: pageshow event - Web APIs
This includes: Initially loading the page Navigating to the page from another page in the same window or tab Restoring a frozen page on mobile OSes Returning to the page using the browser's forward or back buttons During the initial page load, the pageshow event fires after the load 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. ...
Window.performance - Web APIs
It serves as the point of exposure for the Performance Timeline API, the High Resolution Time API, the Navigation Timing API, the User Timing API, and the Resource Timing API. Syntax performanceData = window.performance; Value A Performance object offering access to the performance and timing-related information offered by the APIs it exposes. ...
Window.print() - Web APIs
Web › API › Window › print
In most browsers, this method will block while the print dialog is open. However in more recent versions of Safari, it may return immediately. Syntax window.print() Specification Specification Status Comment HTML Living StandardThe definition of 'print()' in that specification. Living Standard Browser Compatibility The compatibility table in 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. ...
Window.requestAnimationFrame() - Web APIs
In this example, an element is animated for 2 seconds (2000 milliseconds). The element moves at a speed of 0.1px/ms to the right, so its relative position (in CSS pixels) can be calculated in function of the time elapsed since the start of the animation (in milliseconds) with 0.1 * elapsed. The element's final position is 200px (0.1 * 2000) to the right of its initial position. const element = document.getElementById('some-element-you-want-to-animate'); let start; function step(timestamp) { if (start === undefined) start = timestamp; const elapsed = timestamp - start; // `Math.min()` is used here to make sure that the element stops at exactly 200px. element.style.transform = 'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)'; if (elapsed < 2000) { // Stop the animation after ...
Window.scroll() - Web APIs
Web › API › Window › scroll
- or - options is a ScrollToOptions dictionary. Examples <!-- put the 100th vertical pixel at the top of the window --> <button onclick="scroll(0, 100);">click to scroll down 100 pixels</button> Using options: window.scroll({ top: 100, left: 100, behavior: 'smooth' }); Notes Window.scrollTo() is effectively the same as this method. ...
Window.scrollByLines() - Web APIs
The Window.scrollByLines() method scrolls the document by the specified number of lines. Syntax window.scrollByLines(lines) Parameters lines is the number of lines to scroll the document by. It may be a positive or negative integer. Example <!-- Scroll up the document by 5 lines --> <button id="scroll-up" onclick="scrollByLines(-5);">Up 5 lines</button> <!-- Scroll down the document by 5 lines --> <button id="scroll-down" onclick="scrollByLines(5);">Down 5 lines</button> Specification This is not part of any specification. ...
Window.scrollByPages() - Web APIs
The Window.scrollByPages() method scrolls the current document by the specified number of pages. Syntax window.scrollByPages(pages) Parameters pages is the number of pages to scroll. It may be a positive or negative integer. Example // scroll down the document by 1 page window.scrollByPages(1); // scroll up the document by 1 page window.scrollByPages(-1); Specification DOM Level 0. Not part of specification. ...
Window.scrollMaxX - Web APIs
Web › API › Window › scrollMaxX
The Window.scrollMaxX read-only property returns the maximum number of pixels that the document can be scrolled horizontally. Syntax xMax = window.scrollMaxX xMax is the number of pixels. Example // Scroll to right edge of the page let maxX = window.scrollMaxX; window.scrollTo(maxX, 0); Notes Do not use this property to get the total document width, which is not equivalent to window.innerWidth + window.scrollMaxX, because window.innerWidth includes the width of any visible vertical scrollbar, thus the result would exceed the total document width by the width of any visible vertical scrollbar. Instead use document.body.scrollWidth. See also window.scrollMaxY. Specification This is not part of any specification. ...
Window.scrollMaxY - Web APIs
Web › API › Window › scrollMaxY
The Window.scrollMaxY read-only property returns the maximum number of pixels that the document can be scrolled vertically. Syntax yMax = window.scrollMaxY yMax is the number of pixels. Example // Scroll to the bottom of the page let maxY = window.scrollMaxY; window.scrollTo(0, maxY); Notes Do not use this property to get the total document height, which is not equivalent to window.innerHeight + window.scrollMaxY, because window.innerHeight includes the width of any visible horizontal scrollbar, thus the result would exceed the total document height by the width of any visible horizontal scrollbar. Instead use document.body.scrollHeight. See also window.scrollMaxX and window.scrollTo. Specification This is not part of any specification. ...
Window.scrollTo() - Web APIs
Web › API › Window › scrollTo
- or - options is a ScrollToOptions dictionary. Examples window.scrollTo(0, 1000); Using options: window.scrollTo({ top: 100, left: 100, behavior: 'smooth' }); Notes Window.scroll() is effectively the same as this method. For relative scrolling, see Window.scrollBy(), Window.scrollByLines(), and Window.scrollByPages(). ...
Window.self - Web APIs
Web › API › Window › self
y that will work not only in a window context (self will resolve to window.self) but also in a worker context (self will then resolve to WorkerGlobalScope.self). Example Uses of window.self like the following could just as well be replaced by window. ...
Window.sessionStorage - Web APIs
ied origin. Example The following snippet accesses the current origin's session Storage object and adds data to it with Storage.setItem(). sessionStorage.setItem('myCat', 'Tom'); The following example autosaves the contents of a text field, and if the browser is refreshed, restores the text field content so that no writing is lost. ...
Window.showModalDialog() - Web APIs
This feature has been removed. Please fix your Web sites and applications. This method was removed in Chrome 43 and Firefox 56. The Window.showModalDialog() created and displayed a modal dialog box containing a specified HTML document. Syntax returnVal = window.showModalDialog(uri[, arguments][, options]); returnVal holds the returnValue property as set by the document specified by uri. uri is the URL of the document to display in the dialog. arguments is an optional variant containing values passed to the dialog; these are made available in the window object's window.dialogArguments property. options is an optional string specifying window ornamentation for the dialog, using one or more semicolon delimited values: Syntax Description center: {on | off...
Window.stop() - Web APIs
Web › API › Window › stop
Syntax window.stop() Example window.stop(); Specification Specification Status Comment HTML Living StandardThe definition of 'Window.stop()' in that specification. ...
Window: storage event - Web APIs
Bubbles No Cancelable No Interface StorageEvent Event handler property onstorage Examples Log the sampleList item to the console when the storage event fires: window.addEventListener('storage', () => { // When local storage changes, dump the list to // the console. ...
Window: unload event - Web APIs
The unload event is fired when the document or a child resource is being unloaded. Bubbles No Cancelable No Interface Event Event handler property onunload It is fired after: beforeunload (cancelable event) pagehide The document is in the following state: All the resources still exist (img, iframe etc.) Nothing is visible anymore to the end user UI interactions are ineffective (window.open, alert, confirm, etc.) An error won't stop the unloading workflow Please note that the unload event also follows the document tree: parent frame unload will happen before child frame unload (see example below). Examples <!DOCTYPE html> <html> <head> <title>Parent Frame</title> <script> window.addEventListener('beforeunload',...
Window.window - Web APIs
Web › API › Window › window
e 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-namespaced version, "this.window" would refer back to "window", and also be able to readily get the document location. Another advantage, is that the objects of such a class (even if the class were defined outside of a module) could change their reference to the window at will, they would not be able to do this if they had hard-coded a reference to "window". The default in the class could still be set as the current window object. Specifications Specification Status Comment HTM...
WindowClient.visibilityState - Web APIs
The visibilityState read-only property of the WindowClient interface indicates the visibility of the current client. This value can be one of "hidden", "visible", or "prerender". Syntax var myVisState = windowClient.visibilityState; Value A DOMString (See Document.visibilityState for values). Example event.waitUntil(clients.matchAll({ type: "window" }).then(function(clientList) { for (let i = 0; i < clientList.length; i++) { let client = clientList[i]; if (client.url == '/' && 'focus' in client) { if (client.visibilityState === 'hidden') return client.focus(); } } } if (clients.openWindow) { return clients.openWindow('/'); } })); }); Specifications Specification Status Comment Service Worker...
WindowClient - Web APIs
The service worker client independently selects and uses a service worker for its own loading and sub-resources. Methods WindowClient inherits methods from its parent interface, Client. WindowClient.focus() Gives user input focus to the current client. WindowClient.navigate() Loads a specified URL into a controlled client page. Properties WindowClient inherits properties from its parent interface, Client. WindowClient.focused Read only A boolean that indicates whether the current client has focus. ...
WindowEventHandlers.onbeforeunload - Web APIs
Note: To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with. Moreover, some don't display them at all. Syntax window.addEventListener("beforeunload", function(event) { ... }); window.onbeforeunload = function(event) { ... ...
WindowEventHandlers.onstorage - Web APIs
The onstorage property of the WindowEventHandlers mixin is an EventHandler for processing storage events. The storage event fires when a storage area has been changed in the context of another document. Syntax window.onstorage = functionRef; Value functionRef is a function name or a function expression. This function receives a StorageEvent as its sole argument. Example This example logs the value for a storage key whenever it changes in another document. window.onstorage = function(e) { console.log('The ' + e.key + ' key has been changed from ' + e.oldValue + ' to ' + e.newValue + '.'); }; Specifications Specification Status Comment HTML Living StandardThe definition of 'onstorage' in that specification. Living Standard ...
self.createImageBitmap() - Web APIs
turn value A Promise which resolves to an ImageBitmap object containing bitmap data from the given rectangle. Example Creating sprites from a sprite sheet This example loads a sprite sheet, extracts individual sprites, and then renders each sprite to the canvas. A sprite sheet is an image containing multiple smaller images, each of which you want to be able to render separately. ...
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
out scripts Since Firefox 55, tracking scripts (e.g. Google Analytics, any script URL that Firefox recognises as a tracking script through its TP lists) have been subject to further throttling. When running in the foreground, the throttling minimum delay is still 4ms. In background tabs, however, the throttling minimum delay is 10,000 ms, or 10 seconds, which comes into effect 30 seconds after a document has first loaded. The prefs that control this behaviour are: dom.min_tracking_timeout_value: 4 dom.min_tracking_background_timeout_value: 10000 dom.timeout.tracking_throttling_delay: 30000 Late timeouts In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks. One important case to note is that the function or code snipp...
Worker() - Web APIs
Web › API › Worker › Worker
credentials to use for the worker. The value can be omit, same-origin, or include. If not specified, or if type is classic, the default used is omit (no credentials required). name: A DOMString specifying an identifying name 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 u...
WorkerGlobalScope.importScripts() - Web APIs
Return value None. ...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
RUPT, network(71) errName = 'NetworkInterruptError'; break; default: errName = 'NetworkError'; break; } } // XXX we have no TCPError implementation right now because it's really hard to // do on b2g18. On mozilla-central we want a proper TCPError that ideally // sub-classes DOMError. Bug 867872 has been filed to implement this and // contains a documented TCPError.webidl that maps all the error codes we use in // this file to slightly more readable explanations. let error = Cc["@mozilla.org/dom-error;1"].createInstance(Ci.nsIDOMDOMError); error.wrappedJSObject.init(errName); return error; // XXX: errType goes unused } function dumpSecurityInfo(xhr, error) { let channel = xhr.channel; try { dump("Connection status:\n"); ...
Synchronous and asynchronous requests - Web APIs
quest.open('GET', '/bar/foo.txt', false); // `false` makes the request synchronous request.send(null); if (request.status === 200) { console.log(request.responseText); } Line 3 sends the request. The null parameter indicates that no body content is needed for the GET request. Line 5 checks the status code after the transaction is completed. If the result is 200 -- HTTP's "OK" result -- the document'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. example.html (the main page): <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>MDN Example</title> <script type="text...
init() - Web APIs
sILoadGroup 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. Prior to Firefox 23, this was always a Window. baseURI The base URI to use when resolving relative URIs when handling the request. This may be null. loadGroup Optional An optional load group used when performing the request. If this is specified, it is used even if the global has a window with a load group already established. ...
XMLHttpRequest: abort event - Web APIs
="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> CSS .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } JS const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.addEventListener('loadstart', handleEvent);...
XMLHttpRequest: error event - Web APIs
="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> CSS .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } JS const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.addEventListener('loadstart', handleEvent);...
XMLHttpRequest: load event - Web APIs
="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> CSS .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } JS const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.addEventListener('loadstart', handleEvent);...
XMLHttpRequest: loadend event - Web APIs
="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> CSS .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } JS const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.addEventListener('loadstart', handleEvent);...
XMLHttpRequest: loadstart event - Web APIs
="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> CSS .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } JS const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.addEventListener('loadstart', handleEvent);...
XMLHttpRequest: progress event - Web APIs
="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> CSS .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } JS const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.addEventListener('loadstart', handleEvent);...
XMLHttpRequest.timeout - Web APIs
When a timeout happens, a timeout event is fired. Note: You may not use a timeout for synchronous requests with an owning window. ...
XMLHttpRequest.withCredentials - Web APIs
to indicate when cookies are to be ignored in the response. The default is false. XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request. The third-party cookies obtained by setting withCredentials to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers. Note: This never affects same-site requests. Note: XMLHttpRequest responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request, regardless of Access-Control- header values. Example var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/', true); xhr.withCredent...
XMLHttpRequestResponseType - Web APIs
e 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 in a DOMString object. ms-stream The response is part of a streaming d...
XMLSerializer.serializeToString() - Web APIs
of HTML was requested but could not succeed due to the content not being well-formed. Usage notes Compatible node types The specified root node--and all of its descendants--must be compatible with the XML serialization algorithm. The root node itself must be either a Node or Attr object. The following types are also permitted as descendants of the root node, in addition to Node and Attr: DocumentType Document DocumentFragment Element Comment Text ProcessingInstruction Attr If any other type is encountered, a TypeError exception is thrown. Notes on the resulting XML There are some things worth noting about the XML output by serializeToString(): For XML serializations, Element and Attr nodes are always serialized with their namespaceURI intact. This may mean that a previously-...
XPathEvaluator.createExpression() - Web APIs
y the specified XPathNSResolver, a DOMException of type NAMESPACE_ERROR is raised. Example The following example shows the use of the evaluate() method. HTML <div>XPath example</div> <div>Number of &lt;div&gt;s: <output></output></div> JavaScript var xpath = "//div"; var evaluator = new XPathEvaluator(); var expression = evaluator.createExpression("//div"); var result = expression.evaluate(document, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE); document.querySelector("output").textContent = result.snapshotLength; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathEvaluator.createExpression()' in that specification. Recommendation Initial definition ...
XPathException.code - Web APIs
The code read-only property of the XPathException interface returns a short that contains one of the error code constants. Syntax var exceptionCode = exception.code; Value A short number representing the error code. Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathException' in that specification. Recommendation Initial definition ...
XPathException - Web APIs
Recommendation Initial definition ...
XPathNSResolver.lookupNamespaceURI() - Web APIs
the given namespace prefix within an XPath expression evaluated by the XPathEvaluator interface. Syntax DOMString XPathNSResolver.lookupNamespaceURI(prefix); Parameters prefix A DOMString representing the prefix to look for. Return value A DOMString representing the associated namespace URI or null if none is found. Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathNSResolver.lookupNamespaceURI()' in that specification. Recommendation Initial definition ...
XPathNSResolver - Web APIs
h expression to be properly bound to namespace URI strings. The XPathEvaluator interface can construct an implementation of XPathNSResolver from a node, or the interface may be implemented by any application. Methods XPathNSResolver.lookupNamespaceURI() Looks up the namespace URI associated to the given namespace prefix. Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathNSResolver' in that specification. Recommendation Initial definition ...
XPathResult.snapshotLength - Web APIs
the result snapshot. Exceptions TYPE_ERR In case XPathResult.resultType is not UNORDERED_NODE_SNAPSHOT_TYPE or ORDERED_NODE_SNAPSHOT_TYPE, an XPathException of type TYPE_ERR is thrown. Example The following example shows the use of the snapshotLength property. HTML <div>XPath example</div> <div>Number of matched nodes: <output></output></div> JavaScript var xpath = "//div"; var result = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); document.querySelector("output").textContent = result.snapshotLength; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathResult.snapshotLength' in that specification. Recommendation Initial definition ...
XRPermissionDescriptor.mode - Web APIs
immersive-vr Indicates that the rendered session will be displayed using an immersive XR device in VR mode; it is not intended to be overlaid or integrated into the surrounding environment. The environmentBlendMode is expected to be opaque if possible, but might be additive if the hardware requires it. inline The output is presented inline within the context of an element in a standard HTML document, rather than occupying the full visual space. Inline sessions can be presented in either mono or stereo mode, and may or may not have viewer tracking available. Inline sessions don't require special hardware and should be avalable on any user agent offering WebXR API support. Usage notes Examples The example below checks to ensure that permission has been granted to allow the user to use WebX...
XRReferenceSpace.onreset - Web APIs
R device has experienced a discontinuity large enough to require that the position and/or orientation of the origin be significantly altered to compensate. Syntax xrReferenceSpace.onreset = eventHandler; eventHandler = xrReferenceSpace.onreset; Value An event handler function which will be called whenever the reset event is received by the XRReferenceSpace. Usage notes See the reset event documentation for further details. Specifications Specification Status Comment WebXR Device APIThe definition of 'onreset' in that specification. Working Draft Initial definition. ...
XRReferenceSpaceEvent.transform - Web APIs
Usage notes Upon receiving a reset event, you can apply the transform to cached position or orientation information to shift them into the updated coordinate system. Alternatively, you can just discard any cached positional information and recompute from scratch. The approach you take will depend on your needs. For details on what causes a reset event and how to respond, see the reset event's documentation. Examples This example handles the reset event by walking through all the objects in a scene, updating each object's position by multiplying it with the event's given transform. The scene is represented by a scene object, with all the objects in an array called objects within it. xrReferenceSpace.addEventListener("reset", event => { for (let obj of scene.objects) { mat4.multiply(obj...
XRRenderState.baseLayer - Web APIs
WebGLLayer = xrRenderState.baseLayer; Value A XRWebGLLayer object which is used as the source of the world's contents when rendering each frame of the scene. See the examples below to see how to use updateRenderState() to set the current XRWebGLLayer used for rendering the scene. Examples You can set the XRWebGLLayer used for rendering by calling updateRenderState(), like this: let canvas = document.querySelector("canvas"); gl = canvas.getContext("webgl", { xrCompatible: true }); setNewWebGLLayer(); function setNewWebGLLayer(gl) { if (!gl) { /* WebGL not available */ return; } xrSession.updateRenderState({ baseLayer: new XRWebGLLayer(xrSession, gl); }); }; Here, the canvas obtained in the first line is the canvas into which WebGL is going to draw. That context is pass...
XRSession.updateRenderState() - Web APIs
nlineVerticalFieldOfView property was set, but the session is immersive and therefore does not allow this property to be used. Examples This example creates a WebGL context that is compatible with an immersive XR device and then uses it to create an XRWebGLLayer. updateRenderState() is then called to associate the new XRWebGLLayer. function onXRSessionStarted(xrSession) { let glCanvas = document.createElement("canvas"); let gl = glCanvas.getContext("webgl", { xrCompatible: true }); loadWebGLResources(); xrSession.updateRenderState({ baseLayer: new XRWebGLLayer(xrSession, gl) }); } Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSession.updateRenderState()' in that specification. Working Draft Initial definition...
XRSessionMode - Web APIs
immersive-vr Indicates that the rendered session will be displayed using an immersive XR device in VR mode; it is not intended to be overlaid or integrated into the surrounding environment. The environmentBlendMode is expected to be opaque if possible, but might be additive if the hardware requires it. inline The output is presented inline within the context of an element in a standard HTML document, rather than occupying the full visual space. Inline sessions can be presented in either mono or stereo mode, and may or may not have viewer tracking available. Inline sessions don't require special hardware and should be avalable on any user agent offering WebXR API support. Usage notes The XRSessionMode type indicates the values that can be specified when calling XR.isSessionSupported() to d...
XRSystem: devicechange event - Web APIs
has changed; for example, a VR headset or AR goggles have been connected or disconnected. It's a generic Event with no added properties. Note: Not to be confused with the MediaDevices devicechange event. Bubbles No Cancelable No Interface Event Event handler XRSystem.ondevicechange Usage notes devicechange events are not delivered if the document which owns the XRSystem object has been granted permission to do so through the xr-spatial-tracking feature policy. You can use this event to, for example, monitor for the availability of a WebXR-compatible device so that you can enable a UI element which the user can use to activate immersive mode. This is shown in the example below. Example The example shown here handles the devicechange eve...
XRSystem: requestSession() - Web APIs
immersive-vr Indicates that the rendered session will be displayed using an immersive XR device in VR mode; it is not intended to be overlaid or integrated into the surrounding environment. The environmentBlendMode is expected to be opaque if possible, but might be additive if the hardware requires it. inline The output is presented inline within the context of an element in a standard HTML document, rather than occupying the full visual space. Inline sessions can be presented in either mono or stereo mode, and may or may not have viewer tracking available. Inline sessions don't require special hardware and should be avalable on any user agent offering WebXR API support. sessionInit Optional A XRSessionInit object providing options to configure the new XRSession. See Specifying session op...
XRSystem - Web APIs
Web › API › XRSystem
upported. requestSession() Returns a promise that resolves to a new XRSession with the specified XRSessionMode. Events devicechange Sent when the set of available XR devices has changed. Also available using the ondevicechange event handler. Usage notes Thsi interface was previously known as simply XR in earlier versions of the specification; if you see references to XR in code or documentation, simply replace that with XRSystem. Examples The following example shows how to use both isSessionSupported() and requestSession(). if (navigator.xr) { immersiveButton.addEventListener("click", onButtonClicked); navigator.xr.isSessionSupported('immersive-vr') .then((isSupported) => { if (isSupported) { immersiveButton.disabled = false; } else { immersiveButton.di...
msGetRegionContent - Web APIs
nt returns an array of Range instances corresponding to the content from the region flow that is positioned in the region. This proprietary method is specific to Internet Explorer browser. Syntax var retVal = Element.msGetRegionContent(); Parameters retVal [out, reval] Type: MSRangeCollection The name of the property to enable. Return value Type: Boolean Returned ranges are sorted by document position and do not overlap. If an element is not a region, this method throws a DOMException with the InvalidAccessError error code. This is only available to regions that are document elements and not to regions that are pseudo-elements. See also Microsoft API extensions ...
msRegionOverflow - Web APIs
to accommodate any content). empty: The region element has no content and is empty. All content from the named flow was fitted in regions with a lower content-order value. undefined: The element is not a region. When the region is an actual element, msRegionOverflow provides the ability to find out if content fully fits into the region or not. However, it is only available to regions that are document elements and not to regions that are pseudo-elements. See also Microsoft API extensions ...
Using the alertdialog role - Accessibility
ffer on how assistive technology should handle this technique. The information provided above is one of those opinions and therefore not normative. Examples Example 1: A basic alert dialog The code snippet below shows how to mark up an alert dialog that only provides a message and an OK button. ...
Using the aria-labelledby attribute - Accessibility
elationships between objects and their label(s), and its value should be one or more element IDs, which refer to elements that have the text needed for labeling. List multiple element IDs in a space delimited fashion. This idea is similar to how the "for" attribute is used to link a LABEL to an INPUT. Assistive technology, such as screen readers, use this attribute to catalog the objects in a document so that users can navigate between them. Without an element ID, the assistive technology cannot catalog the object. aria-labelledby is very similar to aria-describedby: A label provides essential information about an object, while a description provides extended information that the user might need. In addition to form elements, you can use the aria-labelledby attribute to associate static text...
Using the link role - Accessibility
e.target : e.srcElement; if (ref) { window.open(ref.getAttribute('data-href'), '_blank'); } } } spanElem.addEventListener('click', navigateLink); spanElem.addEventListener('keydown', navi...
x-ms-aria-flowfrom - Accessibility
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 x-ms-aria-flowfrom property specifies the id of the previous element in an alternative reading order, allowing assistive technology to override the general default of reading in document source order. The property serves to define element relationships utilizing ARIA relationship attributes and the aria-flowto property. This proprietary property is specific to Internet Explorer and Microsoft Edge. Syntax x-ms-aria-flowfrom="elementID"; Value The x-ms-aria-flowfrom property value uses an ID selector to define which previous element the reading order will flow from. Example ...
ARIA: timer role - Accessibility
ic, 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. <div id="clock" role="timer" aria-live="off">20</div> <button onclick="startTimer('clock')">start</button> /* basic JavaScript to update a timer */ function startTimer(timerName) { // get the number of seconds let timer = document.getElementById(timerName), seconds = parseInt(timer.innerText); // remove a second // updated the content of timer timer.innerText = --seconds // if timer != 0, setTimeout if (seconds) { setTimeout( function() { startTimer(timerName); }, 1000); } } The first time the function executes, the entirety of the string that is added will be announced. On subsequent c...
ARIA: alert role - Accessibility
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> function triggerAlert() { var alertEl = document.querySelector('.alert'); alertEl.addAttribute("role", "alert"); } Accessibility concerns The alert role should read out content that has changed, or bring the user's attention to it immediately, so it should not be used for static content or used regularly. Alerts, by definition, are disruptive. Lots of alerts at once or unnecessary alerts willl create a bad user experience. Specification...
ARIA: banner role - Accessibility
a banner landmark to assistive technologies. Assistive technologies can identify the main header element of a page as the banner if is a descendant of the body element, and not nested within an article, aside, main, nav or section subsection. Each page may have a banner landmark, but 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 sub...
ARIA: switch role - Accessibility
ng 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. ...
ARIA: checkbox role - Accessibility
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-checked="true"]::before { content: "[x]"; } [aria-checked="false"]::before { content: "[ ]"; } JavaScript function changeCheckbox(event) { let item = document.getElementById('chkPref'); switch(item.getAttribute('aria-checked')) { case "true": item.setAttribute('aria-checked', "false"); break; case "false": item.setAttribute('aria-checked', "true"); break; } } Accessibility concerns When the checkbox role is added to an element, the user agent should do the following: Expose ...
ARIA: listbox role - Accessibility
the correct spelling based on the accessibility API conventions.) aria-roledescription A human-readable string value which more clearly identifies the role of the listbox. Screen readers will often read this value to the user after reading the label (if there is one), in place of saying "listbox". (For further details and a full list of ARIA states and properties see the ARIA listbox (role) documentation.) Keyboard interactions When a single-select listbox receives focus: If none of the options are selected before the listbox receives focus, the first option receives focus. Optionally, the first option may be automatically selected. If an option is selected before the listbox receives focus, focus is set on the selected option. When a multi-select listbox receives focus: I...
Multipart labels: Using ARIA for labels with embedded fields inside them - Accessibility
With JAWS 8, I have not found a way to make it to accept the label from the example above. But NVDA and Window-Eyes do it just fine, and Orca on Linux also has no problems. TBD: add more compatibility info Can this be done without ARIA? Community member Ben Millard has pointed out in a blog post that controls can be embedded in labels as shown in the above example using HTML 4, simply by...
Community - Accessibility
If you know of other useful resources, please link to them here. ...
Accessibility FAQ - Accessibility
For interface design with XUL, follow the Accessibile XUL Authoring Guidelines (archive.org). I'm interested in helping promote the fine accessibility features that Firefox provides, what can I do? Join t...
Operable - Accessibility
t labels. Also note that you should minimize instances where multiple copies of the same text are linked to different places. This can cause problems for screenreader users, who will often bring up a list of the links out of context -- several links all labelled "click here", "click here", "click here" would be confusing. 2.4.10 Section headings (AAA) As well as creating a useful document structure, headings should also accurately describe and break up content areas into logical sections. Note that this criterion refers to headings and titles in general web content (e.g. headings within text content). Headings and titles for user interfaces are a special case covered in criterion 4.1.2. See The basics of headings and paragraphs. Note: Also see the WCAG...
-webkit-text-fill-color - CSS: Cascading Style Sheets
CSS p { margin: 0; font-size: 3em; -webkit-text-fill-color: green; } HTML <p>This text is green.</p> Results Specifications Specification Status Comment Compatibility StandardThe definition of '-webkit-text-fill-color' in that specification. Living Standard Initial standardization Safari CSS Reference '-webkit-text-fill-color' in that document. Non-standard unofficial documentation Initial definition ...
-webkit-text-stroke-width - CSS: Cascading Style Sheets
mm; } HTML <p id="thin">Thin stroke</p> <p id="medium">Medium stroke</p> <p id="thick">Thick stroke</p> Results Specifications Specification Status Comment Compatibility StandardThe definition of '-webkit-text-stroke-width' in that specification. Living Standard Initial standardization Safari CSS Reference '-webkit-text-stroke-width' in that document. Non-standard unofficial documentation Initial documentation ...
-webkit-text-stroke - CSS: Cascading Style Sheets
le">The stroke of this text is red.</p> CSS #example { font-size: 3em; margin: 0; -webkit-text-stroke: 2px red; } Result Specifications Specification Status Comment Compatibility StandardThe definition of '-webkit-text-stroke' in that specification. Living Standard Initial standardization Safari CSS Reference '-webkit-text-stroke' in that document. Non-standard unofficial documentation Initial definition ...
:-moz-window-inactive - CSS: Cascading Style Sheets
Note: Prior to the addition of this pseudo-class, giving different styles to background windows was achieved by setting an attribute (active="true") on the top-level XUL chrome window. This attribute is no longer used. Syntax :-moz-window-inactive Examples This example alters the appearance of a box's background depending on whether its window is active or not. ...
::before (:before) - CSS: Cascading Style Sheets
Web › CSS › ::before
Note that there are no icons used, and the check-mark is actually the ::before that has been styled in CSS. Go ahead and get some stuff done. Result Special characters As this is CSS; not ...
::first-line (:first-line) - CSS: Cascading Style Sheets
/* Selects the first line of a <p> */ p::first-line { color: red; } CSS3 introduced the ::first-line notation (with two colons) to distinguish pseudo-classes from pseudo-elements. Browsers also accept :first-line, introduced in CSS2. ...
::grammar-error - CSS: Cascading Style Sheets
ts a text segment which the user agent has flagged as grammatically incorrect. Allowable properties Only a small subset of CSS properties can be used in a rule with ::grammar-error in its selector: color background-color cursor caret-color outline and its longhands text-decoration and its associated properties text-emphasis-color text-shadow Syntax ::grammar-error Examples Simple document grammar check In this example, eventual supporting browsers should highlight any flagged grammatical errors with the styles shown. HTML <p>My friends is coming to the party tonight.</p> CSS ::grammar-error { text-decoration: underline red; color: red; } Result Specifications Specification Status Comment CSS Pseudo-Elements Level 4The definition of '::gra...
::part() - CSS: Cascading Style Sheets
Web › CSS › ::part
Wor...
::selection - CSS: Cascading Style Sheets
::selection { background-color: cyan; } Allowable properties Only certain CSS properties can be used with ::selection: color background-color cursor caret-color outline and its longhands text-decoration and its associated properties text-emphasis-color text-shadow In particular, background-image is ignored. Syntax /* Legacy Firefox syntax (version 61 and below) */ ::-moz-selection ::selection Examples HTML This text has special styles when you highlight it. ...
::slotted() - CSS: Cascading Style Sheets
Web › CSS › ::slotted
ot name="person-name">NAME MISSING</slot> <ul> <li><slot name="person-age">AGE MISSING</slot></li> <li><slot name="person-occupation">OCCUPATION MISSING</slot></li> </ul> </div> </template> A custom element -- <person-details> -- is defined like so: customElements.define('person-details', class extends HTMLElement { constructor() { super(); let template = document.getElementById('person-template'); let templateContent = template.content; const shadowRoot = this.attachShadow({mode: 'open'}); let style = document.createElement('style'); style.textContent = 'div { padding: 10px; border: 1px solid gray; width: 200px; margin: 10px; }' + 'h2 { margin: 0 0 10px; }' + 'ul { margin: 0; ...
::spelling-error - CSS: Cascading Style Sheets
ents a text segment which the user agent has flagged as incorrectly spelled. Allowable properties Only a small subset of CSS properties can be used in a rule with ::spelling-error in its selector: color background-color cursor caret-color outline and its longhands text-decoration and its associated properties text-emphasis-color text-shadow Syntax ::spelling-error Examples Simple document spell check In this example, eventual supporting browsers should highlight any flagged spelling errors with the styles shown. HTML <p contenteditable spellcheck="true">My friends are coegdfgfddffbgning to the party tonight.</p> CSS ::spelling-error { text-decoration: wavy red; } Result Specifications Specification Status Comment CSS Pseudo-Elements Level 4...
:disabled - CSS: Cascading Style Sheets
Web › CSS › :disabled
">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 text fields for (var i = 0; i < billingItems.le...
:indeterminate - CSS: Cascading Style Sheets
is example applies special styles to the labels associated with indeterminate form fields. ...
:is() (:matches(), :any()) - CSS: Cascading Style Sheets
Web › CSS › :is
<p>This is my footer paragraph</p> </footer> :-webkit-any(header, main, footer) p:hover { color: red; cursor: pointer; } :-moz-any(header, main, footer) p:hover { color: red; cursor: pointer; } :matches(header, main, footer) p:hover { color: red; cursor: pointer; } :is(header, main, footer) p:hover { color: red; cursor: pointer; } let matchedItems; try { matchedItems = document.querySelectorAll(':is(header, main, footer) p'); } catch(e) { try { matchedItems = document.querySelectorAll(':matches(header, main, footer) p'); } catch(e) { try { matchedItems = document.querySelectorAll(':-webkit-any(header, main, footer) p'); } catch(e) { try { matchedItems = document.querySelectorAll(':-moz-any(header, main, footer) p'); } catch(e) {...
:left - CSS: Cascading Style Sheets
Web › CSS › :left
The :left CSS pseudo-class, used with the @page at-rule, represents all left-hand pages of a printed document. /* Selects any left-hand pages when printing */ @page :left { margin: 2in 3in; } Whether a given page is "left" or "right" is determined by the major writing direction of the document. For example, if the first page has a major writing direction of left-to-right then it will be a :right page; if it has a major writing direction of right-to-left then it will be a :left page. Note: This pseudo-class can be used to change only the margin, padding, border, and background properties of the page box. All other properties will be ignored, and only the page box, not the document content on the page, will be affected. Syntax :left Examples Setting a margin for left-hand pages @page :l...
:right - CSS: Cascading Style Sheets
Web › CSS › :right
The :right CSS pseudo-class, used with the @page at-rule, represents all right-hand pages of a printed document. /* Selects any right-hand pages when printing */ @page :right { margin: 2in 3in; } Whether a given page is "left" or "right" is determined by the major writing direction of the document. For example, if the first page has a major writing direction of left-to-right then it will be a :right page; if it has a major writing direction of right-to-left then it will be a :left page. Note: This pseudo-class can be used to change only the margin, padding, border, and background properties of the page box. All other properties will be ignored, and only the page box, not the document content on the page, will be affected. Syntax :right Examples Setting margins for right-hand pages @pa...
@charset - CSS: Cascading Style Sheets
Web › CSS › @charset
try the following methods in the following order (and stop as soon as one yields a result) : The value of the Unicode byte-order character placed at the beginning of the file. The value given by the charset attribute of the Content-Type: HTTP header or the equivalent in the protocol used to serve the style sheet. The @charset CSS at-rule. Use the character encoding defined by the referring document: the charset attribute of the <link> element. This method is obsoleted in HTML5 and must not be used. Assume that the document is UTF-8 Syntax @charset "UTF-8"; @charset "iso-8859-15"; where: charset Is a <string> denoting the character encoding to be used. It must be the name of a web-safe character encoding defined in the IANA-registry, and must be double-quoted, following exactly one...
speak-as - CSS: Cascading Style Sheets
system is extends, the value of speak-as will be the same as if speak-as: auto is specified on the extended style. For all other cases, specifying auto has the same effect as specifying speak-as: numbers. bullets A phrase or an audio cue defined by the user agent for representing an unordered list item will be read out. numbers The numerical value of the counter will be read out in the document language. words The user agent will generate a counter value as normal and read it out as a word in the document language. spell-out The user agent will generate a counter representation as normal and would read it out letter by letter. If the user agent doesn't know how to read out a partiular counter symbol, the user agent might read it out as if the value of speak-as was numbers. <counter...
src - CSS: Cascading Style Sheets
Web › CSS › @font-face › src
the first one it can successfully activate. Fonts containing invalid data or local font faces that are not found are ignored and the user agent loads the next font in the list. As with other URLs in CSS, the URL may be relative, in which case it is resolved relative to the location of the style sheet containing the @font-face rule. In the case of SVG fonts, the URL points to an element within a document containing SVG font definitions. If the element reference is omitted, a reference to the first defined font is implied. Similarly, font container formats that can contain more than one font load only one of the fonts for a given @font-face rule. Fragment identifiers are used to indicate which font to load. If a container format lacks a defined fragment identifier scheme, a simple 1-based indexing...
@font-face - CSS: Cascading Style Sheets
</body> </h...
@import - CSS: Cascading Style Sheets
Web › CSS › @import
ueriesThe definition of '@import' in that specification. Recommendation Extended the syntax to support any media query and not only simple media types. CSS Level 2 (Revision 1)The definition of '@import' in that specification. Recommendation Added support for <string> to denote the url of a stylesheet, and requirement to insert the @import rule at the beginning of the CSS document. CSS Level 1The definition of '@import' in that specification. Recommendation Initial definition ...
-webkit-device-pixel-ratio - CSS: Cascading Style Sheets
} } /* Maximum resolution */ @media (-webkit-max-device-pixel-ratio: 3) { p { background: yellow; } } Result Specifications Specification Status Comment Compatibility StandardThe definition of '-webkit-device-pixel-ratio' in that specification. Living Standard Initial standardization Safari CSS Reference 'media query extensions' in that document. Non-standard unofficial documentation Initial documentation ...
-webkit-transform-3d - CSS: Cascading Style Sheets
{ transform-style: preserve-3d; } } @media (-webkit-transform-3d: 1) { .foo { transform-style: preserve-3d; } } Specifications Specification Status Comment Compatibility StandardThe definition of '-webkit-transform-3d' in that specification. Living Standard Initial standardization Safari CSS Reference 'media query extensions' in that document. Non-standard unofficial documentation Initial documentation ...
update - CSS: Cascading Style Sheets
The update CSS media feature can be used to test how frequently (if at all) the output device is able to modify the appearance of content. Syntax The update feature is specified as a single keyword value chosen from the list below. none Once it has been rendered, the layout can no longer be updated. Example: documents printed on paper. slow The layout may change dynamically according to the usual rules of CSS, but the output device is not able to render or display changes quickly enough for them to be perceived as a smooth animation. Examples: e-book readers or severely underpowered devices. fast The layout may change dynamically according to the usual rules of CSS, and the output device is not unusually constrained in speed, so regularly-updating things like CSS Animations can be used.
marks - CSS: Cascading Style Sheets
Web › CSS › @page › marks
Crop marks indicate where the page should be cut. Cross marks are used to align sheets. Crop marks and cross marks are printed outside the page box. To have room to show crop and cross marks, the final pages will have to be somewhat bigger than the page box. Syntax /* Keyword values */ marks: none; marks: crop; marks: cross; marks: crop cross; Values crop Crop marks will be displayed. cross Cross marks will be displayed. none No marks will be displayed. ...
@page - CSS: Cascading Style Sheets
Web › CSS › @page
The @page CSS at-rule is used to modify some CSS properties when printing a document. Syntax @page { margin: 1cm; } @page :first { margin: 2cm; } Descriptors size Specifies the target size and orientation of the page box's containing block. In the general case, where one page box is rendered onto one page sheet, it also indicates the size of the destination page sheet. marks Adds crop and/or registration marks to the document. bleed Specifies the extent beyond the page box at which the page rendering is clipped. Description You can't change all CSS properties with @page. You can only change the margins, orphans, widows, and page breaks of the document. Attempts to change any other CSS properties will be ignored. The @page at-rule can be accessed via the CSS object model ...
max-height - CSS: Cascading Style Sheets
The height will initially be set as close as possible to the initial viewport height considering the maximum height constraint. Syntax /* Keyword value */ max-height: auto; /* <length> values */ max-height: 400px; max-height: 50em; max-height: 20cm; /* <percentage> value */ max-height: 75%; Values auto The used value is calculated from the other CSS descriptors' values. <length> A non-negative absolute or relative length. <percentage> A percentage value relative to the height of the initial viewport at zoom factor 1.0 for vertical lengths. Must be non-negative. ...
max-width - CSS: Cascading Style Sheets
By default, the width is set as close as possible to the initial viewport considering the maximum width constraint. Syntax /* Keyword value */ max-width: auto; /* <length> values */ max-width: 600px; max-width: 80em; max-width: 15cm; /* <percentage> value */ max-width: 75%; Values auto The used value is calculated from the other CSS descriptors' values. <length> A non-negative absolute or relative length. <percentage> A percentage value relative to the width of the initial viewport at zoom factor 1.0 for horizontal lengths. Must be non-negative. ...
min-height - CSS: Cascading Style Sheets
The height will initially be set as close as possible to the initial viewport height considering the minimum height constraint. Syntax /* Keyword value */ min-height: auto; /* <length> values */ min-height: 120px; min-height: 20em; min-height: 10cm; /* <percentage> value */ min-height: 25%; Values auto The used value is calculated from the other CSS descriptors' values. <length> A non-negative absolute or relative length. <percentage> A percentage value relative to the height of the initial viewport at zoom factor 1.0 for vertical lengths. Must be non-negative. ...
min-width - CSS: Cascading Style Sheets
By default, min-width is set as close as possible to the initial viewport considering the minimum width constraint. Syntax /* Keyword value */ min-width: auto; /* <length> values */ min-width: 320px; min-width: 40em; min-width: 5cm; /* <percentage> value */ min-width: 25%; Values auto The used value is calculated from the other CSS descriptors' values. <length> A non-negative absolute or relative length. <percentage> A percentage value relative to the width or height of the initial viewport at zoom factor 1.0, for horizontal and vertical lengths respectively. Must be non-negative. ...
orientation - CSS: Cascading Style Sheets
The orientation CSS descriptor controls the orientation of a document defined by @viewport. /* Keyword values */ orientation: auto; orientation: portrait; orientation: landscape; For a UA/device where the orientation is changed upon tilting the device, an author can use this descriptor to inhibit the orientation change. Syntax Values auto The user agent will set the document's orientation automatically, typically based on the device's orientation as determined by an accelerometer (if the device has such a hardware sensor), although there is often a user-controlled, OS-level "Lock orientation" setting that will trump the accelerometer reading. portrait The document should be locked into portrait orientation. landscape The document should be locked into landscape orientation. Formal ...
user-zoom - CSS: Cascading Style Sheets
/* Keyword values */ user-zoom: zoom; user-zoom: fixed; Syntax Values zoom The user can zoom in or out. fixed The user cannot zoom in or out. Accessibility concerns Disabling zooming capabilities prevents people experiencing low vision conditions from being able to read and understand page content. ...
viewport-fit - CSS: Cascading Style Sheets
Syntax /* Keyword values */ viewport-fit: auto; viewport-fit: contain; viewport-fit: cover; Values auto This value doesn't affect the initial layout viewport, and the whole web page is viewable. contain The viewport is scaled to fit the largest rectangle inscribed within the display. cover The viewport is scaled to fill the device display. It is highly recommended to make use of the safe area inset variables to ensure that important content doesn't end up outside the display. This descriptor hasn't been added to https://github.com/mdn/data/blob/master/css/at-rules.json yet. ...
Alternative style sheets - CSS: Cascading Style Sheets
e", "Fancy", and "Basic" will be listed in the Page Style submenu, with "Default Style" pre-selected. When the user selects a different style, the page will immediately be re-rendered using that style sheet. No matter what style is selected, the rules from the reset.css stylesheet will always be applied. Try it out Click here for a working example you can try out. Details Any stylesheet in a document falls into one of the following categories: Persistent (no rel="alternate", no title=""): always applies to the document. Preferred (no rel="alternate", with title="..." specified): applied by default, but disabled if an alternate stylesheet is selected. There can only be one preferred stylesheet, so providing stylesheets with different title attributes will cause some of them to be ignored. ...
CSSOM View - CSS: Cascading Style Sheets
Reference Properties scroll-behavior Guides Coordinate systems A guide to the coordinate systems used to specify the position of a location in a display context, whether that context is a window on a monitor, a viewport on a mobile device, or a position on a sheet of paper when printing. ...
Box alignment for block, absolutely positioned and table layout - CSS: Cascading Style Sheets
uding floated, positioned, and table elements. As this page aims to detail things which are specific to block layout and box alignment, it should be read in conjunction with the main Box Alignment page, which details the common features of box alignment across layout methods. Note: At the time of writing (May 2018), there is no real support for the box alignment properties in block layout. This document details how the specification expects these properties to be implemented for completeness, and is likely to change as the specification and browser implementations develop. align-content and justify-content The justify-content property does not apply to block containers or table cells. The align-content property applies to the block axis in order to align the contents of the box within its co...
Box alignment in Flexbox - CSS: Cascading Style Sheets
ignment page which details the common features of box alignment across layout methods. Basic example In this example, three flex items are aligned on the main axis using justify-content and on the cross axis using align-items. The first item overrides the align-items values set on the group by setting align-self to center. The axes and flex-direction Flexbox respects the writing mode of the document, therefore if you are working in English and set justify-content to flex-end this will align the items to the end of the flex container. If you are working with flex-direction set to row, this alignment will be in the inline direction. However, in Flexbox you can change the main axis by setting flex-direction to column. In this case, justify-content will align items in the block direction. There...
Introduction to the CSS basic box model - CSS: Cascading Style Sheets
CSS determines the size, position, and properties (color, background, border size, etc.) of these boxes. Every box is composed of four parts (or areas), defined by their respective edges: the content edge, padding edge, border edge, and margin edge. The content area, bounded by the content edge, contains the "real" content of the element, such as text, an image, or a video player. Its dimensions are the content width (or content-box width) and the content height (or content-box height). It often has a background color or background image. ...
CSS Multi-column Layout - CSS: Cascading Style Sheets
ample In the following example the column-count property has been applied to the element with a class of container. As the value of column-count is 3, the content is arranged into 3 columns of equal size. Relationship to Fragmentation Multiple-column Layout is closely related to Paged Media, in that each column box becomes a fragment, much like a printed page becomes a fragment of an overall document. Therefore the properties now defined in the CSS Fragmentation specification are required in order to control how content breaks between columns. Reference Multiple-column Layout Properties column-count column-fill column-gap column-rule column-rule-color column-rule-style column-rule-width column-span column-width columns Related CSS Fragmentation Properties break-after b...
CSS Display - CSS: Cascading Style Sheets
CSS Display is a module of CSS that defines how the CSS formatting box tree is generated from the document element tree and defines properties controlling it. Reference CSS properties display CSS data types <display-outside> <display-inside> <display-listitem> <display-box> <display-internal> <display-legacy> Guides CSS Flow Layout (display: block, display: inline) Block and Inline Layout in Normal Flow Flow Layout and Overflow Flow Layout and Writing Modes Formatting Contexts Explained In Flow and Out of Flow display: flex Basic concepts of flexbox Aligning Items in a Flex Container Controlling Ratios of Flex Items Along the Main Axis Cross-browser Flexbox mixins Mastering Wrapping of Flex Items Ordering Flex Items Relationship of flexbox to other layout m...
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
d to a second wrapper in order that the negative margin can pull the items up to that wrapper element. It is this requirement that the gap properties, once implemented, will solve for us. Proper gaps only happen on the inside edges of items. Collapsed items The flexbox specification details what should happen if a flex item is collapsed by setting visibility: collapse on an item. See the MDN documentation for the visibility property. The specification describes the behaviour as follows: "Specifying visibility:collapse on a flex item causes it to become a collapsed flex item, producing an effect similar to visibility:collapse on a table-row or table-column: the collapsed flex item is removed from rendering entirely, but leaves behind a "strut" that keeps the flex line's cross-size stable. Th...
Flow Layout and Overflow - CSS: Cascading Style Sheets
ed at the newer properties of block-size and inline-size which make more sense when working with different writing modes than tying our layout to the physical dimensions of the screen. The Level 3 Overflow Module also includes flow relative properties for overflow - overflow-block and overflow-inline. These correspond to overflow-x and overflow-y but the mapping depends on the writing mode of the document. These properties currently do not have implementations in browsers, so you will need to use the physical properties at the present time and adjust for your writing mode. Indicating Overflow In the Level 3 Overflow specification we have some properties which can help improve the way content looks in an overflow situation. Inline-Axis Overflow The text-overflow property deals with text overfl...
CSS Flow Layout - CSS: Cascading Style Sheets
displayed on a page before any changes are made to their layout. The flow is essentially a set of things that are all working together and know about each other in your layout. Once something is taken out of flow it works independently. In normal flow, inline elements display in the inline direction, that is in the direction words are displayed in a sentence according to the Writing Mode of the document. Block elements display one after the other, as paragraphs do in the Writing Mode of that document. In English therefore, inline elements display one after the other, starting on the left, and block elements start at the top and move down the page. Basic Example The following example demonstrates Block and Inline Level boxes. The two paragraph elements with a green border are Block Level, displ...
OpenType font features guide - CSS: Cascading Style Sheets
s but this can become cumbersome. The issue with simply using font-feature-settings for everything is that every time you want to change one of the individual features, you have to redefine the entire string (similar to manipulating variable fonts with font-variation-settings). Discovering availability of features in fonts This is sometimes the trickiest thing to work out if you don't have any documentation that came with the fonts (many type designers and foundries will provide sample pages and CSS just for this very reason). But there are some sites that make it easier to figure out. You can visit wakamaifondue.com, drop your font file on the circle where instructed and in a few moments you'll have a full report on all the capabilities and features of your font. Axis-praxis.org also offers a ...
Line-based placement with CSS Grid - CSS: Cascading Style Sheets
d using line numbers. In this article we will fully explore how this fundamental feature of the specification works. Starting your exploration of grid with numbered lines is the most logical place to begin, as when you use grid layout you always have numbered lines. The lines are numbered for columns and rows, and are indexed from 1. Note that grid is indexed according to the writing mode of the document. In a left to right language such as English line 1 is on the left-hand side of the grid. If you are working in a right-to-left language then line 1 will be the far right of the grid. We will learn more about the interaction between writing modes and grids in a later guide. A basic example As a very simple example we can take a grid with 3 column tracks and 3 row tracks. This gives us 4 lines i...
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
play: contents. The contents value of the display property is a new value that is described in the Display specification as follows: "The element itself does not generate any boxes, but its children and pseudo-elements still generate boxes as normal. For the purposes of box generation and layout, the element must be treated as if it had been replaced with its children and pseudo-elements in the document tree." If you set an item to display: contents the box it would normally create disappears, and the boxes of the child elements appear as if they have risen up a level. This means that children of a grid item can become grid items. Sound odd? Here is a simple example. In the following markup, I have a grid and the first item on the grid is set to span all three column tracks. It contains three ...
CSS Images - CSS: Cascading Style Sheets
ting-linear-gradient() repeating-radial-gradient() conic-gradient() repeating-conic-gradient() url() element() image() cross-fade() Data types <gradient> <image> Guides Using CSS gradients Presents a specific type of CSS images, gradients, and how to create and use these. Implementing image sprites in CSS Describes the common technique grouping several images in one single document to save download requests and speed up the availability of a page. Specifications Specification Status Comment CSS Images Module Level 4 Working Draft Added image-resolution, conic-gradient(), and image() CSS Images Module Level 3 Candidate Recommendation Added image-orientation, image-rendering, object-fit and object-position Compatibi...
Using CSS counters - CSS: Cascading Style Sheets
For example, you can use counters to automatically number the headings in a webpage. Counters are, in essence, variables maintained by CSS whose values may be incremented by CSS rules to track how many times they're used. Using counters Manipulating a counter's value To use a CSS counter, it must first be initialized to a value with the counter-reset property (0 by default). The same property can also be used to change its value to any specific number. Once initialized, a counter's value can be increased or decreased with counter-increment. ...
Basic concepts of Logical Properties and Values - CSS: Cascading Style Sheets
oncept of working with flow relative properties and values is the two dimensions of block and inline. As we saw above, newer CSS layout methods such as Flexbox and Grid Layout use the concepts of block and inline rather than right and left/top and bottom when aligning items. The inline dimension is the dimension along which a line of text runs in the writing mode in use. Therefore, in an English document with the text running horizontally left to right, or an Arabic document with the text running horizontally right to left, the inline dimension is horizontal. Switch to a vertical writing mode (e.g. a Japanese document) and the inline dimension is now vertical, as lines in that writing mode run vertically. The block dimension is the other dimension, and the direction in which blocks -- such as pa...
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
...
The stacking context - CSS: Cascading Style Sheets
or the webpage. HTML elements occupy this space in priority order based on element attributes. The stacking context In the previous part of this article, Using z-index, the rendering order of certain elements is influenced by their z-index value. This occurs because these elements have special properties which cause them to form a stacking context. A stacking context is formed, anywhere in the document, by any element in the following scenarios: Root element of the document (<html>). Element with a position value absolute or relative and z-index value other than auto. Element with a position value fixed or sticky (sticky for all mobile browsers, but not older desktop). Element that is a child of a flex (flexbox) container, with z-index value other than auto. Element that is a child of a ...
Understanding CSS z-index - CSS: Cascading Style Sheets
elements are handled with stacking. Using z-index: How to use z-index to change default stacking. The stacking context: Notes on the stacking context. Stacking context example 1: 2-level HTML hierarchy, z-index on the last level Stacking context example 2: 2-level HTML hierarchy, z-index on all levels Stacking context example 3: 3-level HTML hierarchy, z-index on the second level Original Document Information Author(s): Paolo Lombardi This article is the English translation of an article I wrote in Italian for YappY. I grant the right to share all the content under the Creative Commons: Attribution-Sharealike license. Last Updated Date: July 9, 2005 Author's note: Thanks to Wladimir Palant and Rod Whiteley for the review. ...
CSS Ruby Layout - CSS: Cascading Style Sheets
Web › CSS › CSS Ruby
CSS Ruby Layout is a module of CSS that provides the rendering model and formatting controls related to the display of ruby annotation. Ruby annotation is a form of interlinear annotation, consisting of short runs of text alongside the base text. They are typically used in East Asian documents to indicate pronunciation or to provide a short annotation. Reference Properties ruby-align ruby-position Specifications Specification Status Comment CSS Ruby Layout Module Level 1 Working Draft Initial definition ...
Basic concepts of CSS Scroll Snap - CSS: Cascading Style Sheets
This can be helpful in creating a more app-like experience on mobile or even on the desktop for some types of applications. Basics of Scroll Snap The key properties of the Scroll Snap specification are scroll-snap-type and scroll-snap-align. The scroll-snap-type property is used on the scroll container to state the type and direction of scrolling. The scroll-snap-align property must be used on child elements in order to set the position that scrolling will snap to. ...
Overview of CSS Shapes - CSS: Cascading Style Sheets
ted item In the examples above we have used images or a visible element to define the shape, meaning that you can see the shape on the page. Instead, you might simply want to cause some text to flow along a non-rectangular invisible line. You can do this with Shapes, however you will still need a floated item, which you can then make invisible. That could be a redundant element inserted into the document, an empty <div> or <span> perhaps, but our preference is to use generated content. This means we can keep things used for styling inside the CSS. In this next example, we use generated content to insert an element with height and width of 150px. We can then use Basic Shapes, Box Values or even the Alpha Channel of an image to create a shape for the text to wrap around. Relationship to clip-pa...
Using CSS transforms - CSS: Cascading Style Sheets
This guide provides an introduction to using transforms. CSS transforms are implemented using a set of CSS properties that let you apply affine linear transformations to HTML elements. These transformations include rotation, skewing, scaling, and translation both in the plane and in the 3D space. Only elements positioned by the box model can be transformed. As a rule of thumb, an element is positioned by the box model if it has display: block. ...
Comments - CSS: Cascading Style Sheets
Web › CSS › Comments
Syntax Comments can be placed wherever white space is allowed within a style sheet. They can be used on a single line, or traverse multiple lines. ...
Layout and the containing block - CSS: Cascading Style Sheets
The size and position of an element are often impacted by its containing block. Most often, the containing block is the content area of an element's nearest block-level ancestor, but this is not always the case. In this article, we examine the factors that determine an element's containing block. When a user agent (such as your browser) lays out a document, it generates a box for every element. Each box is divided into four areas: Content area Padding area Border area Margin area Many developers believe that the containing block of an element is always the content area of its parent, but that isn't necessarily true. Let's investigate the factors that determine what an element's containing block is. Effects of the containing block Before learning what determines the containing block o...
Questions about CSS - CSS: Cascading Style Sheets
Web › CSS › FAQ
Cascading Style Sheets (CSS) is a rule-based language allowing developers to define styles to apply to HTML elements (or other markup structures). CSS gives more control over the appearance of a Web page to the page creator than to the browser designer or the viewer. With CSS, the sources of style definition for a given document element are in this order of precedence: The STYLE attribute on an individual element tag The STYLE element that defines a specific style sheet containing style declarations or a LINK element that links to a separate document containing the STYLE element. In a Web page, the STYLE element is placed between the TITLE statement and the BODY statement. An imported style sheet, using the CSS @import notation to automatically import and merge an external style s...
Filter Effects - CSS: Cascading Style Sheets
Filter Effects is a module of CSS that defines a way of processing an element's rendering before it is displayed in the document. Reference Properties backdrop-filter filter Data types <filter-function> Specifications Specification Status Comment Filter Effects Module Level 1The definition of 'filter' in that specification. Working Draft Initial definition. ...
Pagination - CSS: Cascading Style Sheets
...
Pseudo-classes - CSS: Cascading Style Sheets
A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s). For example, :hover can be used to change a button's color when the user's pointer hovers over it. /* Any button over which the user's pointer is hovering */ button:hover { color: blue; } Pseudo-classes let you apply a style to an element not only in relation to the content of the document tree, but also in relation to external factors like the history of the navigator (:visited, for example), the status of its content (like :checked on certain form elements), or the position of the mouse (like :hover, which lets you know if the mouse is over an element or not). Note: In contrast to pseudo-classes, pseudo-elements can be used to style a specific part of an element. Syntax select...
CSS reference - CSS: Cascading Style Sheets
Web › CSS › Reference
Inheritance Shorthand properties Specificity Value definition syntax CSS unit and value types Values Actual value Computed value Initial value Resolved value Specified value Used value Layout Block formatting context Box model Containing block Layout mode Margin collapsing Replaced elements Stacking context Visual formatting model DOM-CSS / CSSOM Major object types DocumentOrShadowRoot.styleSheets styleSheets[i].cssRules cssRules[i].cssText (selector & style) cssRules[i].selectorText HTMLElement.style HTMLElement.style.cssText (just style) Element.className Element.classList Important methods CSSStyleSheet.insertRule() CSSStyleSheet.deleteRule() ...
Replaced elements - CSS: Cascading Style Sheets
In CSS, a replaced element is an element whose representation is outside the scope of CSS; they're external objects whose representation is independent of the CSS formatting model. Put in simpler terms, they're elements whose contents are not affected by the current document's styles. The position of the replaced element can be affected using CSS, but not the contents of the replaced element itself. Some replaced elements, such as <iframe> elements, may have stylesheets of their own, but they don't inherit the styles of the parent document. The only other impact CSS can have on a replaced element is that there are properties which support controlling the positioning of the element's content within its box. See Controlling object position within the content box for further information. Replaced...
Shorthand properties - CSS: Cascading Style Sheets
the left and right. When three values are specified, the first margin applies to the top, the second to the left and right, the third to the bottom. When four values are specified, the margins apply to the top, right, bottom, and left in that order (clockwise). The universal shorthand property CSS provides a universal shorthand property, all, which applies its value to every property in the document. Its purpose is to change the properties' inheritance model to one of: CSS provides four special universal property values for controlling inheritance. Every CSS property accepts these values. inherit Sets the property value applied to a selected element to be the same as that of its parent element. Effectively, this "turns on inheritance". initial Sets the property value applied to a sele...
Specificity - CSS: Cascading Style Sheets
r type in the matching selector. When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element. Specificity only applies when the same element is targeted by multiple declarations. As per CSS rules, directly targeted elements will always take precedence over rules which an element inherits from its ancestor. Note: Proximity of elements in the document tree has no effect on the specificity. Selector Types The following list of selector types increases by specificity: Type selectors (e.g., h1) and pseudo-elements (e.g., ::before). Class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover). ID selectors (e.g., #example). Universal selector (*), combinators (+, >, ~, ' ', ||) and negat...
Type selectors - CSS: Cascading Style Sheets
/* All <a> elements. */ a { color: red; } Syntax element { style properties } Examples CSS span { background-color: skyblue; } HTML <span>Here's a span with some text.</span> <p>Here's a p with some text.</p> <span>Here's a span with more text.</span> Result Specifications Specification Status Comment Selectors Level 4The definition of 'Type (tag name) selector' in that specification. Working Draft No changes Selectors Level 3The definition of 'type selectors' in that specification. ...
WebKit CSS extensions - CSS: Cascading Style Sheets
background-origin-y (unprefixed!) * Still supported in the Safari Technology Preview, but not in a generally released browser. Pseudo-classes :-webkit-animating-full-screen-transition :-webkit-any() :-webkit-any-link* :-webkit-autofill :-webkit-autofill-strong-password :-webkit-drag :-webkit-full-page-media :-webkit-full-screen* :-webkit-full-screen-ancestor :-webkit-full-screen-document :-webkit-full-screen-controls-hidden * Now standard. Note: If there is an invalid pseudo-class within in a chain or group of selectors, the whole selector list is invalid. Pseudo-elements For web-compatibility reasons, Blink, WebKit, and Gecko browsers treat all pseudo-elements starting with ::-webkit- as valid. ::-webkit-file-upload-button ::-webkit-inner-spin-button ::-webkit-inp...
align-content - CSS: Cascading Style Sheets
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 Specification Status ...
align-items - CSS: Cascading Style Sheets
afe 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 Specification Status ...
<angle-percentage> - CSS: Cascading Style Sheets
Use in calc() Where an <angle-percentage> is specified as an allowable type, this means that the percentage resolves to an angle and therefore can be used in a calc() expression. Specifications Specification Status Comment CSS Values and Units Module Level 4The definition of '<angle-percentage>' in that specification. ...
animation - CSS: Cascading Style Sheets
Web › CSS › animation
n { from { transform: scaleX(0); } to { transform: scaleX(1); } } .a1 { animation: 3s ease-in 1s 2 reverse both paused slidein; } .a2 { animation: 3s linear 1s slidein; } .a3 { animation: 3s slidein; } .animation { background: #3F87A6; width: 100%; height: calc(100% - 1.5em); transform-origin: left center; } window.addEventListener('load', function () { var ANIMATION = Array.from(document.querySelectorAll('.animation')); var BUTTON = Array.from(document.querySelectorAll('button')); function toggleButton (btn, type) { btn.classList.remove('play', 'pause', 'restart'); btn.classList.add(type); btn.title = type.toUpperCase(type); } function playPause (i) { var btn = BUTTON[i]; var anim = ANIMATION[i]; if (btn.classList.contains('play')) { a...
attr() - CSS: Cascading Style Sheets
Web › CSS › attr
pty string. color <color> The attribute value is parsed as a hash (3- or 6-value hash) or a keyword. It must be a valid CSS <string> value. Leading and trailing spaces are stripped. currentcolor url <url> The attribute value is parsed as a string that is used inside a CSS url() function. Relative URL are resolved relatively to the original document, not relatively to the style sheet. Leading and trailing spaces are stripped. The url about:invalid that points to a non-existent document with a generic error condition. integer <integer> The attribute value is parsed as a CSS <integer>. If it is not valid, that is not an integer or out of the range accepted by the CSS property, the default value is used. Lead...
background-blend-mode - CSS: Cascading Style Sheets
n> <option>difference</option> <option>exclusion</option> <option>hue</option> <option>saturation</option> <option>color</option> <option>luminosity</option> </select> #div { width: 300px; height: 300px; background: url('https://mdn.mozillademos.org/files/8543/br.png'),url('https://mdn.mozillademos.org/files/8545/tr.png'); background-blend-mode: screen; } document.getElementById("select").onchange = function(event) { document.getElementById("div").style.backgroundBlendMode = document.getElementById("select").selectedOptions[0].innerHTML; } console.log(document.getElementById('div')); Specifications Specification Status Comment Compositing and Blending Level 1The definition of 'background-blend-mode' in that specification...
background-image - CSS: Cascading Style Sheets
d. Accessibility concerns Browsers do not provide any special information on background images to assistive technology. This is important primarily for screen readers, as a screen reader will not announce its presence and therefore convey nothing to its users. If the image contains information critical to understanding the page's overall purpose, it is better to describe it semantically in the document. MDN Understanding WCAG, Guideline 1.1 explanations Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 Formal definition Initial valuenoneApplies toall elements. It also applies to ::first-letter and ::first-line.InheritednoComputed valueas specified, but with <url> values made absoluteAnimation typediscrete Formal syntax <bg-image>#where <bg-image> = none | <image>where ...
background - CSS: Cascading Style Sheets
e. Accessibility concerns Browsers do not provide any special information on background images to assistive technology. This is important primarily for screen readers, as a screen reader will not announce its presence and therefore convey nothing to its users. If the image contains information critical to understanding the page's overall purpose, it is better to describe it semantically in the document. MDN Understanding WCAG, Guideline 1.1 explanations Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 Formal definition Initial valueas each of the properties of the shorthand:background-image: nonebackground-position: 0% 0%background-size: auto autobackground-repeat: repeatbackground-origin: padding-boxbackground-clip: border-boxbackground-attachment: scrollbackground-col...
border-bottom-width - CSS: Cascading Style Sheets
er medium A medium border thick A thick border Note: Because the specification doesn't define the exact thickness denoted by each keyword, the precise result when using one of them is implementation-specific. Nevertheless, they always follow the pattern thin <= medium <= thick, and the values are constant within a single document. Formal definition Initial valuemediumApplies toall elements. It also applies to ::first-letter.InheritednoComputed valuethe absolute length or 0 if border-bottom-style is none or hiddenAnimation typea length Formal syntax <line-width>where <line-width> = <length> | thin | medium | thick Examples Comparing bottom border widths HTML <div>Element 1</div> <div>Element 2</div> CSS div ...
border-image-slice - CSS: Cascading Style Sheets
ice-output">30</output> </li> </ul> CSS .wrapper { width: 400px; height: 300px; } div > div { width: 300px; height: 200px; border-width: 30px; border-style: solid; border-image: url(https://udn.realityripple.com/samples/56/bb98f533ef.png); border-image-slice: 30; border-image-repeat: round; } li { display: flex; place-content: center; } JavaScript const widthSlider = document.getElementById('width'); const sliceSlider = document.getElementById('slice'); const widthOutput = document.getElementById('width-output'); const sliceOutput = document.getElementById('slice-output'); const divElem = document.querySelector('div > div'); widthSlider.addEventListener('input', () => { const newValue = widthSlider.value + 'px'; divElem.style.borderWidth = newValue; widthOutput...
border-image - CSS: Cascading Style Sheets
'border-image-repeat'> Defines how the edge regions of the source image are adjusted to fit the dimensions of the border image. Up to two values may be specified. See border-image-repeat. Accessibility concerns Assistive technology cannot parse border images. If the image contains information critical to understanding the page's overall purpose, it is better to describe it semantically in the document. MDN Understanding WCAG, Guideline 1.1 explanations Understanding Success Criterion 1.1.1 | Understanding WCAG 2.0 Formal definition Initial valueas each of the properties of the shorthand:border-image-source: noneborder-image-slice: 100%border-image-width: 1border-image-outset: 0border-image-repeat: stretchApplies toall elements, except internal table elements when border-collapse is col...
border-left-width - CSS: Cascading Style Sheets
er medium A medium border thick A thick border Note: Because the specification doesn't define the exact thickness denoted by each keyword, the precise result when using one of them is implementation-specific. Nevertheless, they always follow the pattern thin <= medium <= thick, and the values are constant within a single document. Formal definition Initial valuemediumApplies toall elements. It also applies to ::first-letter.InheritednoComputed valuethe absolute length or 0 if border-left-style is none or hiddenAnimation typea length Formal syntax <line-width>where <line-width> = <length> | thin | medium | thick Examples Comparing border widths HTML <div>Element 1</div> <div>Element 2</div> CSS div { borde...
border-right-width - CSS: Cascading Style Sheets
er medium A medium border thick A thick border Note: Because the specification doesn't define the exact thickness denoted by each keyword, the precise result when using one of them is implementation-specific. Nevertheless, they always follow the pattern thin <= medium <= thick, and the values are constant within a single document. Formal definition Initial valuemediumApplies toall elements. It also applies to ::first-letter.InheritednoComputed valuethe absolute length or 0 if border-right-style is none or hiddenAnimation typea length Formal syntax <line-width>where <line-width> = <length> | thin | medium | thick Examples Comparing border widths HTML <div>Element 1</div> <div>Element 2</div> CSS div { bord...
border-top-width - CSS: Cascading Style Sheets
er medium A medium border thick A thick border Note: Because the specification doesn't define the exact thickness denoted by each keyword, the precise result when using one of them is implementation-specific. Nevertheless, they always follow the pattern thin <= medium <= thick, and the values are constant within a single document. Formal definition Initial valuemediumApplies toall elements. It also applies to ::first-letter.InheritednoComputed valuethe absolute length or 0 if border-top-style is none or hiddenAnimation typea length Formal syntax <line-width>where <line-width> = <length> | thin | medium | thick Examples HTML <div>Element 1</div> <div>Element 2</div> CSS div { border: 1px solid red; margin...
box-ordinal-group - CSS: Cascading Style Sheets
control the order in which the direct children of a box appear. When the computed box-direction is normal, a box will display its elements starting from the lowest numbered ordinal group and ensure that those elements appear to the left (for horizontal boxes) or at the top (for vertical boxes) of the container. Elements with the same ordinal group are flowed in the order they appear in the source document tree. In the reverse direction, the ordinal groups are examined in the same order, except the elements appear reversed. Syntax The box-ordinal-group property is specified as any positive <integer>. Formal definition Initial value1Applies tochildren of box elementsInheritednoComputed valueas specifiedAnimation typediscrete Formal syntax <integer> Examples Basic usage example In an older v...
conic-gradient() - CSS: Cascading Style Sheets
While it is possible to create pie charts, checkerboards, and other effects with conic gradients, CSS images provide no native way to assign alternative text, and therefore the image represented by the conic gradient will not be accessible to screen reader users. If the image contains information critical to understanding the page's overall purpose, it is better to describe it semantically in the document. MDN Understanding WCAG, Guideline 1.1 explanations Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 Examples Gradient at 40-degrees div { width: 100px; height: 100px; } <div></div> div { background-image: conic-gradient(from 40deg, #fff, #000); } Off-centered gradient div { width: 100px; height: 100px; } <div></div> div { background: coni...
contain - CSS: Cascading Style Sheets
Web › CSS › contain
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, leading to obvious performance benefits. This property is useful on pages that contain a lot of widgets that are all independent, as it can be used to prevent each widget's internals from having side effects outside of the widget's bounding-box. ...
cross-fade() - CSS: Cascading Style Sheets
on. Accessibility concerns Browsers do not provide any special information on background images to assistive technology. This is important primarily for screen readers, as a screen reader will not announce its presence and therefore convey nothing to its users. If the image contains information critical to understanding the page's overall purpose, it is better to describe it semantically in the document. When using background images, make sure the contrast in color is great enough that any text is legible over the image as well as if the images is missing. MDN Understanding WCAG, Guideline 1.1 explanations Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 Formal syntax cross-fade( <cf-mixing-image> , <cf-final-image>? )where <cf-mixing-image> = <percentage>? && <image><cf...
<display-box> - CSS: Cascading Style Sheets
uch as replaced elements. See Appendix B: Effects of display: contents on Unusual Elements for more details. Due to a bug in browsers this will currently remove the element from the accessibility tree -- screen readers will not look at what's inside. See the Accessibility concerns section below for more details. none Turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist). All descendant elements also have their display turned off. To have an element take up the space that it would normally take, but without actually rendering anything, use the visibility property instead. Accessibility concerns Current implementations in most browsers will remove from the accessibility tree any element with a display value of c...
<easing-function> - CSS: Cascading Style Sheets
olor: blue; background-image: radial-gradient(circle at 10px 10px, rgba(25,255,255,0.8),rgba(25,255,255,0.4)); border-radius: 50%; top: 25px; animation: 1.5s infinite alternate; } @keyframes move-right { from { left: 10%; } to { left: 90%; } } li { display: flex; align-items: center; justify-content: center; margin-bottom: 20px; } JavaScript const selectElem = document.querySelector('select'); const startBtn = document.querySelector('button'); const divElem = document.querySelector('div > div'); startBtn.addEventListener('click', () => { if(startBtn.textContent === 'Start animation') { divElem.style.animationName = 'move-right'; startBtn.textContent = 'Stop animation'; divElem.style.animationTimingFunction = selectElem.value; } else { divEl...
env() - CSS: Cascading Style Sheets
Web › CSS › env
The env() CSS function can be used to insert the value of a user agent-defined environment variable into your CSS, in a similar fashion to the var() function and custom properties. The difference is that, as well as being user-agent defined rather than user-defined, environment variables are globally scoped to a document, whereas custom properties are scoped to the element(s) on which they are declared. To tell the browser to use the whole available space on the screen, and so enabling us to use the env() variables, we need to add a new viewport meta value: <meta name="viewport" content="viewport-fit=cover" /> body { padding: env(safe-area-inset-top, 20px) env(safe-area-inset-right, 20px) env(safe-area-inset-bottom, 20px) env(safe-area-inset-left, 20px); } In addition, unli...
<filter-function> - CSS: Cascading Style Sheets
0px; background: url(https://media.prod.mdn.mozit.cloud/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/firefox.png) no-repeat center; } li { display: flex; align-items: center; justify-content: center; margin-bottom: 20px; } input { width: 60% } output { width: 5%; text-align: center; } select { width: 40%; margin-left: 2px; } JavaScript const selectElem = document.querySelector('select'); const divElem = document.querySelector('div'); const slider = document.querySelector('input'); const output = document.querySelector('output'); const curValue = document.querySelector('p code'); selectElem.addEventListener('change', () => { setSlider(selectElem.value); setDiv(selectElem.value); }); slider.addEventListener('input', () => { setDiv(selectElem.value);...
flex - CSS: Cascading Style Sheets
Web › CSS › flex
-shrink'>? | <'flex-basis'> ] Examples Setting flex: auto HTML <div id="flex-container"> <div class="flex-item" id="flex">Flex box (click to toggle raw box)</div> <div class="raw-item" id="raw">Raw box</div> </div> CSS #flex-container { display: flex; flex-direction: row; } #flex-container > .flex-item { flex: auto; } #flex-container > .raw-item { width: 5rem; } var flex = document.getElementById("flex"); var raw = document.getElementById("raw"); flex.addEventListener("click", function() { raw.style.display = raw.style.display == "none" ? "block" : "none"; }); #flex-container { width: 100%; font-family: Consolas, Arial, sans-serif; } #flex-container > div { border: 1px solid #f00; padding: 1rem; } #flex-container > .raw-item { border: 1px solid #000; } Re...
float - CSS: Cascading Style Sheets
Web › CSS › float
eft side with rtl scripts. Formal definition Initial valuenoneApplies toall elements, but has no effect if the value of display is none.InheritednoComputed valueas specifiedAnimation typediscrete Formal syntax left | right | none | inline-start | inline-end Examples How floated elements are positioned As mentioned above, when an element is floated, it is taken out of the normal flow of the document (though still remaining part of it). It is shifted to the left, or right, until it touches the edge of its containing box, or another floated element. In this example, there are three colored squares. Two are floated left, and one is floated right. Note that the second "left" square is placed to the right of the first. Additional squares would continue to stack to the right, until they filled th...
font-family - CSS: Cascading Style Sheets
cross several lines, nesting expressions, and double struck glyphs with distinct meanings. This is some example math text: ax2 + bx + c = 0. emoji Fonts that are specifically designed to render emoji. This is some example emoji text: ??. fangsong A particular style of Chinese characters that are between serif-style Song and cursive-style Kai forms. This style is often used for government documents. This is some example fangsong text with the Chinese characters for "fangsong" in traditional and simple forms, respectively: ??? ???. Valid family names Font family names must either be given quoted as strings, or unquoted as a sequence of one or more identifiers. This means that punctuation characters and digits at the start of each token must be escaped in unquoted font family names. ...
font-style - CSS: Cascading Style Sheets
ntainer { max-height: 150px; overflow: scroll; } .sample { font: 2rem 'AmstelvarAlpha', sans-serif; } html, body { max-height: 100vh; max-width: 100vw; overflow: hidden; } body { display: flex; flex-direction: column; } header { margin-bottom: 1.5rem; } .container { flex-grow: 1; } .container > p { margin-top: 0; margin-bottom: 0; } JavaScript let slantLabel = document.querySelector('label[for="slant"]'); let slantInput = document.querySelector('#slant'); let sampleText = document.querySelector('.sample'); function update() { let slant = `oblique ${slantInput.value}deg`; slantLabel.textContent = `font-style: ${slant};`; sampleText.style.fontStyle = slant; } slantInput.addEventListener('input', update); update(); Accessibility concerns Large section...
font-weight - CSS: Cascading Style Sheets
x; overflow-y: auto; } .sample { text-transform: uppercase; font: 1.5rem 'MutatorSans', sans-serif; } html, body { max-height: 100vh; max-width: 100vw; overflow: hidden; } body { display: flex; flex-direction: column; } header { margin-bottom: 1.5rem; } .container { flex-grow: 1; } .container > p { margin-top: 0; margin-bottom: 0; } JavaScript let weightLabel = document.querySelector('label[for="weight"]'); let weightInput = document.querySelector('#weight'); let sampleText = document.querySelector('.sample'); function update() { weightLabel.textContent = `font-weight: ${weightInput.value};`; sampleText.style.fontWeight = weightInput.value; } weightInput.addEventListener('input', update); update(); Accessibility concerns People experiencing low vision...
image-set() - CSS: Cascading Style Sheets
Web › CSS › image-set
on. Accessibility concerns Browsers do not provide any special information on background images to assistive technology. This is important primarily for screen readers, as a screen reader will not announce its presence and therefore convey nothing to its users. If the image contains information critical to understanding the page's overall purpose, it is better to describe it semantically in the document. MDN Understanding WCAG, Guideline 1.1 explanations Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 Specifications Specification Status Comment CSS Images Module Level 4The definition of 'The image-set() notation' in that specification. Working Draft Browser compatibility The compatibility table on this page is generated from st...
<image> - CSS: Cascading Style Sheets
Web › CSS › image
ls. Accessibility concerns Browsers do not provide any special information on background images to assistive technology. This is important primarily for screen readers, as a screen reader will not announce its presence and therefore convey nothing to its users. If the image contains information critical to understanding the page's overall purpose, it is better to describe it semantically in the document. MDN Understanding WCAG, Guideline 1.1 explanations Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 Examples Valid images url(test.jpg) /* A <url>, as long as test.jpg is an actual image */ linear-gradient(blue, red) /* A <gradient> */ element(#realid) /* A part of the webpage, referenced with the element() function, ...
inherit - CSS: Cascading Style Sheets
Web › CSS › inherit
pplied to any CSS property, including the CSS shorthand all. For inherited properties, this reinforces the default behavior, and is only needed to override another rule. For non-inherited properties, this specifies a behavior that typically makes relatively little sense and you may consider using initial instead, or unset on the all property. Inheritance is always from the parent element in the document tree, even when the parent element is not the containing block. Examples Exclude selected elements from a rule /* Make second-level headers green */ h2 { color: green; } /* ...but leave those in the sidebar alone so they use their parent's color */ #sidebar h2 { color: inherit; } In this example the h2 elements inside the sidebar might be different colors. For example, if one of them were t...
Inheritance - CSS: Cascading Style Sheets
which by default are set to initial value of the property Refer to any CSS property definition to see whether a specific property inherits by default ("Inherited: yes") or not ("Inherited: no"). Inherited properties When no value for an inherited property has been specified on an element, the element gets the computed value of that property on its parent element. Only the root element of the document gets the initial value given in the property's summary. A typical example of an inherited property is the color property. Given the style rules: p { color: green; } ... and the markup: <p>This paragraph has <em>emphasized text</em> in it.</p> ... the words "emphasized text" will appear green, since the em element has inherited the value of the color property from the p element. It does not g...
<length-percentage> - CSS: Cascading Style Sheets
Examples length-percentage examples The following simple example demonstrates several properties that use <length-percentage> values. ...
list-style-type - CSS: Cascading Style Sheets
n, in... gujarati -moz-gujarati Example gurmukhi -moz-gurmukhi Example hebrew Traditional Hebrew numbering hiragana E.g. ?, ?, ?, ?, ?, ?, ?... (Japanese) hiragana-iroha E.g. ?, ?, ?, ?, ?, ?, ?... Iroha is the old japanese ordering of syllabs. japanese-formal Japanese formal numbering to be used in legal or financial document. E.g., ????????? The kanjis are designed so that they can't be modified to look like another correct one japanese-informal Japanese informal numbering kannada -moz-kannada Example katakana E.g. ?, ?, ?, ?, ?, ?, ?... (Japanese) katakana-iroha E.g. ?, ?, ?, ?, ?, ?, ?... Iroha is the old japanese ordering of syllabs. khmer -moz-khmer...
mask-repeat - CSS: Cascading Style Sheets
in-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-repeat: repeat-x, repeat-y; } Each...
overflow-block - CSS: Cascading Style Sheets
The overflow-block CSS property sets what shows when content overflows the block start and block end edges of a box. This may be nothing, a scroll bar, or the overflow content. The overflow-block property maps to overflow-y or overflow-x depending on the writing mode of the document. Syntax /* Keyword values */ overflow-block: visible; overflow-block: hidden; overflow-block: scroll; overflow-block: auto; /* Global values */ overflow-block: inherit; overflow-block: initial; overflow-block: unset; The overflow-block property is specified as a single keyword chosen from the list of values below. Values visible Content is not clipped and may be rendered outside the padding box's block start and block end edges. hidden Content is clipped if necessary to fit the block dimension in the pa...
overflow-inline - CSS: Cascading Style Sheets
The overflow-inline CSS property sets what shows when content overflows the inline start and end edges of a box. This may be nothing, a scroll bar, or the overflow content. The overflow-inline property maps to overflow-y or overflow-x depending on the writing mode of the document. Syntax /* Keyword values */ overflow-inline: visible; overflow-inline: hidden; overflow-inline: scroll; overflow-inline: auto; /* Global values */ overflow-inline: inherit; overflow-inline: initial; overflow-inline: unset; The overflow-inline property is specified as a single keyword chosen from the list of values below. Values visible Content is not clipped and may be rendered outside the padding box's inline start and end edges. hidden Content is clipped if necessary to fit the inline dimension in the p...
place-items - CSS: Cascading Style Sheets
ption 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; width: 240px; place-item...
repeating-conic-gradient() - CSS: Cascading Style Sheets
While it is possible to create pie charts, checkerboards, and other effects with conic gradients, CSS images provide no native way to assign alternative text, and therefore the image represented by the conic gradient will not be accessible to screen reader users. If the image contains information critical to understanding the page's overall purpose, it is better to describe it semantically in the document. MDN Understanding WCAG, Guideline 1.1 explanations Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 Examples Black and white starburst div { width: 200px; height: 200px; } <div></div> div { background-image: repeating-conic-gradient(#fff 0 9deg, #000 9deg 18deg); } Off-centered gradient This gradient repeats 18 times, but since we only see the rig...
<resolution> - CSS: Cascading Style Sheets
ed to CSS inches, centimeters, or pixels, not physical values. Syntax The <resolution> data type consists of a strictly positive <number> followed by one of the units listed below. As with all CSS dimensions, there is no space between the unit literal and the number. Units dpi Represents the number of dots per inch. Screens typically contains 72 or 96 dots per inch, but the dpi for printed documents is usually much greater. As 1 inch is 2.54 cm, 1dpi ? 0.39dpcm. dpcm Represents the number of dots per centimeter. As 1 inch is 2.54 cm, 1dpcm ? 2.54dpi. dppx Represents the number of dots per px unit. Due to the 1:96 fixed ratio of CSS in to CSS px, 1dppx is equivalent to 96dpi, which corresponds to the default resolution of images displayed in CSS as defined by image-resolution. x Alias ...
shape-outside - CSS: Cascading Style Sheets
and computed based on the alpha channel of the specified <image> as defined by shape-image-threshold. Note: User agents must use the potentially CORS-enabled fetch method defined by the HTML5 specification for all URLs in a shape-outside value. When fetching, user agents must use "Anonymous" mode, set the referrer source to the stylesheet's URL, and set the origin to the URL of the containing document. If this results in network errors such that there is no valid fallback image, the effect is as if the value none had been specified. Interpolation When animating between one <basic-shape> and a second, the rules below are applied. The values in the shape functions interpolate as a simple list. The list values interpolate as <length>, <percentage>, or calc() where possible. If list values ar...
text-underline-position - CSS: Cascading Style Sheets
s of left or right to make the underline appear on the left or right of the text as required. The live example looks like this: Setting text-underline-position globally Because the text-underline-position property inherits and is not reset by the text-decoration shorthand property, it may be appropriate to set its value at a global level. For example, the under value may be appropriate for a document with lots of chemical and mathematical formulas, which make a large use of subscripts. :root { text-underline-position: under; } Specifications Specification Status Comment CSS Text Decoration Module Level 3The definition of 'text-underline-position' in that specification. Candidate Recommendation Initial definition ...
<time-percentage> - CSS: Cascading Style Sheets
Examples Use in calc() Where a <time-percentage> is specified as an allowable type, this means that the percentage resolves to a time and therefore can be used in a calc() expression. ...
<transform-function> - CSS: Cascading Style Sheets
,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)'; }, 2000) } }) Result ...
transform-style - CSS: Cascading Style Sheets
(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 definition of 'transform-...
url() - CSS: Cascading Style Sheets
Web › CSS › url()
} @import url("https://www.example.com/style.css"); @namespace url(http://www.w3.org/1999/xhtml); Relative URLs, if used, are relative to the URL of the stylesheet (not to the URL of the web page). The url() function can be included as a value for background, background-image, list-style, list-style-image, content, cursor, border, border-image, border-im...
Used value - CSS: Cascading Style Sheets
how-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.addEventListener('resize', updateAllUsedWidths); Result D...
visibility - CSS: Cascading Style Sheets
The visibility CSS property shows or hides an element without changing the layout of a document. The property can also hide rows or columns in a <table>. 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. To both hide an element and remove it from the document layout, set the display property to none instead of using visibility. Syntax /* Keyword values */ visibility: visible; visibility: hidden; visibility: collapse; /* Global values */ visibility: inherit; visibility: initial; visibility: unset; The visibility property is specified as one of the keyword values listed below. Values visible The element box is vis...
will-change - CSS: Cascading Style Sheets
ition Initial valueautoApplies toall elementsInheritednoComputed valueas specifiedAnimation typediscrete Formal syntax auto | <animateable-feature>#where <animateable-feature> = scroll-position | contents | <custom-ident> Examples Via script This is an example showing how to apply the will-change property through scripting, which is probably what you should be doing in most cases. ...
zoom - CSS: Cascading Style Sheets
Web › CSS › zoom
om: normal; zoom: reset; /* <percentage> values */ zoom: 50%; zoom: 200%; /* <number> values */ zoom: 1.1; zoom: 0.7; /* Global values */ zoom: inherit; zoom: initial; zoom: unset; Syntax Values normal Render this element at its normal size. reset Do not (de)magnify this element if the user applies non-pinch-based zooming (e.g. by pressing Ctrl-- or Ctrl++ keyboard shortcuts) to the document. Only supported by WebKit (and possibly Blink). <percentage> Zoom factor. 100% is equivalent to normal. Values larger than 100% zoom in. Values smaller than 100% zoom out. <number> Zoom factor. Equivalent to the corresponding percentage (1.0 = 100% = normal). Values larger than 1.0 zoom in. Values smaller than 1.0 zoom out. Formal definition Initial valuenormalApplies toall elementsInherit...
CSS: Cascading Style Sheets
Web › CSS
CSS describes how elements should be rendered on screen, on paper, in speech, or on other media. CSS among the core languages of the open Web and is standardized across Web browsers according to the W3C specification. Previously development of various parts of CSS specification was done synchronously, which allowed versioning of the latest recommendation. You might have heard about CSS1, CSS2.1, CSS3. However, CSS4 has never become an official version. ...
touchstart - Event reference
The touchstart event is fired when one or more touch points are placed on the touch surface. Two types of object can be the target of this event. ...
Setting up adaptive streaming media sources - Developer guides
the various streams and the bandwidths they are associated with. In your video source (src) attribute you point to the MPD instead of to the media file as you would with non-adaptive media. The MPD file tells the browser where the various pieces of media are located, it also includes meta data such as mimeType and codecs and there are other details such as byte-ranges in there too - it is an XML document and in many cases will be generated for you. There are a few profiles we can use. We're going to take a look at Ondemand profile for Video On Demand (VOD) and the LIVE profile. For live services streaming, the LIVE profile is a requirement. The stream switching capabilities are identical between the profiles. Other reasons to use LIVE profile over Ondemand for VOD content may be: Your clien...
Video player styling basics - Developer guides
Play/Pause and Mute Now that the buttons actually look like buttons and have images that indicate what they do, some changes need to be made so that the "dual functionalit...
Block formatting context - Developer guides
Floats (elements where float isn't none). Absolutely positioned elements (elements where position is absolute or fixed). Inline-blocks (elements with display: inline-block). ...
HTML5 - Developer guides
Web › Guide › HTML › HTML5
familiarity and experience using HTML5. Downloadable HTML5 Guide A quick guide to HTML5, including the common HTML tags as well as the new HTML5 tags. Downloadable in PDF and PNG formats. HTML5 Cheat Sheet A handy HTML 5 cheat sheet for beginners who want to master HTML 5, its elements, event attributes and compatibility. HTML5-compliant parser The parser, which turns the bytes of an HTML document into a DOM, has been extended and now precisely defines the behavior to use in all cases, even when faced with invalid HTML. This leads to far greater predictability and interoperability between HTML5-compliant browsers. Connectivity Web Sockets Allows creating a permanent connection between the page and the server and to exchange non-HTML data through that means. Server-sent events Allow...
A hybrid approach - Developer guides
ke these are at the heart of mobile web development: be specific about what you would like to accomplish, and pick a practical approach while being aware of the tradeoffs. Good luck! Approaches to mobile Web development See the following articles for background and other approaches to developing for mobile platforms. What is mobile-friendliness? Separate sites Responsive design Original document information This article was originally published on 27 June 2011, on the Mozilla Webdev blog as "Approaches to Mobile Web Development Part 4 - A Hybrid Approach", by Jason Grlicky. ...
Mobile-friendliness - Developer guides
us on tablets and smartphones with standards-friendly browsers. On the other hand, if many of your site's users are on devices with less capable browsers, that may eliminate certain strategies as viable options. Approaches to mobile Web development The following approaches aim to achieve each of these goals by different means. Separate sites Responsive design A hybrid approach Original document information Originally published on 4 May, 2011 on the Mozilla Webdev blog as "Approaches to Mobile Web Development Part 1 - What is Mobile Friendliness?", by Jason Grlicky. ...
Separate sites for mobile and desktop - Developer guides
) and support.mozilla.org (SUMO). If you'd like to see the source code behind an example of this approach in action, feel free to check out the github repository for AMO or SUMO. Approaches to mobile Web development See the following articles for background and other approaches to developing for mobile platforms. What is mobile-friendliness? Responsive design A hybrid approach Original document information This article was originally published on 13 May 2011, on the Mozilla Webdev blog as "Approaches to Mobile Web Development Part 2 - Separate Sites", by Jason Grlicky. ...
Developer guides
se articles provide how-to information to help make use of specific web technologies and APIs. HTML learning area HyperText Markup Language (HTML) is the core language of nearly all web content. Most of what you see on screen in your browser is described, fundamentally, using HTML. CSS learning area Cascading Style Sheets (CSS) is a stylesheet language used to define the presentation of a document written in HTML. Audio and video delivery We can deliver audio and video on the web in several ways, ranging from 'static' media files to adaptive live streams. This article is intended as a starting point for exploring the various delivery mechanisms of web-based media and compatibility with popular browsers. Audio and video manipulation The beauty of the web is that you can combine technolo...
The HTML autocomplete attribute - HTML: Hypertext Markup Language
more information, see the autocomplete attribute in <form>. In order to provide autocompletion, user-agents might require <input>/<select>/<textarea> elements to: Have a name and/or id attribute Be descendants of a <form> element The form to have a submit button Values "off" The browser is not permitted to automatically enter or select a value for this field. It is possible that the document or application provides its own autocomplete feature, or that security concerns require that the field's value not be automatically entered. Note: In most modern browsers, setting autocomplete to "off" will not prevent a password manager from asking the user if they would like to save username and password information, or from automatically filling in those values in a site's login form. See the...
HTML attribute: pattern - HTML: Hypertext Markup Language
bject'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 expression is applied and this attribute is ignored. Tip: Use the titl...
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
t is now deprecated. Implicit ARIA role heading Permitted ARIA roles tab, presentation or none DOM interface HTMLHeadingElement Attributes These elements only include the global attributes. The align attribute is obsolete; don't use it. Usage notes Heading information may be used by user agents, for example, to construct a table of contents for a document automatically. Avoid using heading tags to resize text. Instead, use the CSS font-size property. Headings use size to indicate their relative importance, but CSS is preferred for general-purpose resizing. Avoid skipping heading levels: always start from <h1>, next use <h2> and so on. You should only use one <h1> per page. Using more than one will not result in an error, but using only one is s...
<address>: The Contact Address element - HTML: Hypertext Markup Language
Web › HTML › Element › address
corresponding role Permitted ARIA roles Any DOM interface HTMLElement Prior to Gecko 2.0 (Firefox 4), Gecko implemented this element using the HTMLSpanElement interface Attributes This element only includes the global attributes. Usage notes It used to be the case that an <address> element was only supposed to be used to represent the contact information of the document's author. In the latest spec versions however, its definition has been updated so it can now be used to mark up arbitrary addresses. This element should not contain more information than the contact information, like a publication date (which belongs in a <time> element). Typically an <address> element can be placed inside the <footer> element of the current section, if any. Examples This ex...
<area> - HTML: Hypertext Markup Language
Web › HTML › Element › area
his case is unsafe because it can leak origins and paths from TLS-protected resources to insecure origins. rel For anchors containing the href attribute, this attribute specifies the relationship of the target object to the link object. The value is a space-separated list of link types values. The values and their semantics will be registered by some authority that might have meaning to the document author. The default relationship, if no other is given, is void. Use this attribute only if the href attribute is present. shape The shape of the associated hot spot. The specifications for HTML defines the values rect, which defines a rectangular region; circle, which defines a circular region; poly, which defines a polygon; and default, which indicates the entire region beyond any defined sha...
<aside>: The Aside element - HTML: Hypertext Markup Language
Web › HTML › Element › aside
Asides are frequently presented as sidebars or call-out boxes. 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. Content categories Flow content, sectioning content, palpable content. Permitted content Flow content. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts flow content. ...
<b>: The Bring Attention To element - HTML: Hypertext Markup Language
Web › HTML › Element › b
as been deprecated since HTML4, so the meaning of the <b> element has been changed. If there is no semantic purpose to using the <b> element, you should use the CSS font-weight property with the value "bold" instead in order to make text bold. Examples <p> This article describes several <b class="keywords">text-level</b> elements. It explains their usage in an <b class="keywords">HTML</b> document. </p> Keywords are displayed with the default style of the <b>element, likely in bold.</b> Result Specifications Specification Status Comment HTML Living StandardThe definition of '<b>' in that specification. Living Standard HTML5The definition of '<b>' in that specification. Recommendation HTML 4.01 SpecificationThe definition of ...
<basefont> - HTML: Hypertext Markup Language
Web › HTML › Element › basefont
such as font, font-family, font-size, and color to change the font configuration for an element and its contents. Attributes Like all other HTML elements, this element supports the global attributes. color This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format. face This attribute contains a list of one or more font names. The document text in the default style is rendered in the first font face that the client's browser supports. If no font listed is installed on the local system, the browser typically defaults to the proportional or fixed-width font for that system. size This attribute specifies the font size as either a numeric or relative value. Numeric values range from 1 to 7 with 1 being the smallest and 3 the default.
<blockquote>: The Block Quotation element - HTML: Hypertext Markup Language
t. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts flow content. Implicit ARIA role No corresponding role Permitted ARIA roles Any DOM interface HTMLQuoteElement Attributes This element's attributes include the global attributes. cite A URL that designates a source document or message for the information quoted. This attribute is intended to point to information explaining the context or the reference for the quote. Usage notes To change the indentation applied to the quoted text, use the CSS margin-left and/or margin-right properties, or the margin shorthand property. To include shorter quotes inline rather than in a separate block, use the <q> (Quotation) elem...
<br>: The Line Break element - HTML: Hypertext Markup Language
Web › HTML › Element › br
his can be a confusing and frustrating experience for the person using the screen reader. Use <p> elements, and use CSS properties like margin to control their spacing. Technical summary Content categories Flow content, phrasing content. Permitted content None, it is an empty element. Tag omission Must have a start tag, and must not have an end tag. In XHTML documents, write this element as <br />. Permitted parents Any element that accepts phrasing content. Implicit ARIA role No corresponding role Permitted ARIA roles none, presentation DOM interface HTMLBRElement Specifications Specification Status Comment HTML Living StandardThe definition of '<br>' in that specification. ...
<caption>: The Table Caption element - HTML: Hypertext Markup Language
Web › HTML › Element › caption
a comment. Permitted parents A <table> element, as its first descendant. Implicit ARIA role No corresponding role Permitted ARIA roles No role permitted DOM interface HTMLTableCaptionElement Attributes This element includes the global attributes. Deprecated attributes The following attributes are deprecated and should not be used. They are documented below for reference when updating existing code and for historical interest only. align This enumerated attribute indicates how the caption must be aligned with respect to the table. It may have one of the following values: left The caption is displayed to the left of the table. top The caption is displayed above the table. right The caption is displayed to the right of the ...
<col> - HTML: Hypertext Markup Language
Web › HTML › Element › col
IA roles No role permitted DOM interface HTMLTableColElement Attributes This element includes the global attributes. span This attribute contains a positive integer indicating the number of consecutive columns the <col> element spans. If not present, its default value is 1. Deprecated attributes The following attributes are deprecated and should not be used. They are documented below for reference when updating existing code and for historical interest only. align This enumerated attribute specifies how horizontal alignment of each column cell content will be handled. Possible values are: left, aligning the content to the left of the cell center, centering the content in the cell right, aligning the content to the right of the cell justify, inserting s...
<colgroup> - HTML: Hypertext Markup Language
Web › HTML › Element › colgroup
This attribute is applied on the attributes of the column group, it has no effect on the CSS styling rules associated with it or, even more, to the cells of the column's members of the group. The span attribute is not permitted if there are one or more <col> elements within the <colgroup>. Deprecated attributes The following attributes are deprecated and should not be used. They are documented below for reference when updating existing code and for historical interest only. align This enumerated attribute specifies how horizontal alignment of each column cell content will be handled. Possible values are: left, aligning the content to the left of the cell center, centering the content in the cell right, aligning the content to the right of the cell justify, inserting s...
<del>: The Deleted Text element - HTML: Hypertext Markup Language
Web › HTML › Element › del
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. This element is often (but need not be) rendered by applying a strike-through style to the text. Content categories Phrasing content or flow content. Permitted content Transparent. ...
<dialog>: The Dialog element - HTML: Hypertext Markup Language
Web › HTML › Element › dialog
> <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 favDialog.showModal === "funct...
<div>: The Content Division element - HTML: Hypertext Markup Language
Web › HTML › Element › div
tive 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. As a "pure" container, the <div> element does not inherently represent anything. Instead, it's used to group content so it can be easily styled using the class or id attributes, marking a section of a document as being written in a different language (using the lang attribute), and so on. Content categories Flow content, palpable content. Permitted content Flow content. Or (in WHATWG HTML): If the parent is a <dl> element: one or more <dt> elements followed by one or more <dd> elements, optionally intermixed with <script> and <template> elements. Tag omission No...
<figure>: The Figure with Optional Caption element - HTML: Hypertext Markup Language
Web › HTML › Element › figure
at accepts Flow content. Implicit ARIA role figure Permitted ARIA roles With no figcaption descendant: any, otherwise no permitted roles DOM interface HTMLElement Attributes This element only includes the global attributes. Usage notes Usually a <figure> is an image, illustration, diagram, code snippet, etc., that is referenced in the main flow of a document, but that can be moved to another part of the document or to an appendix without affecting the main flow. Being a sectioning root, the outline of the content of the <figure> element is excluded from the main outline of the document. A caption can be associated with the <figure> element by inserting a <figcaption> inside it (as the first or the last child). The first <figcaption> element found i...
<font> - HTML: Hypertext Markup Language
Web › HTML › Element › font
he <font> element can be achieved, and even better controlled using the CSS Fonts CSS properties. Attributes Like all other HTML elements, this element supports the global attributes. color This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format. face This attribute contains a comma-separated list of one or more font names. The document text in the default style is rendered in the first font face that the client's browser supports. If no font listed is installed on the local system, the browser typically defaults to the proportional or fixed-width font for that system. size This attribute specifies the font size as either a numeric or relative value. Numeric values range from 1 to 7 with 1 being the smallest and 3 the default.
<footer> - HTML: Hypertext Markup Language
Web › HTML › Element › footer
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. Content categories Flow content, palpable content. ...
<img>: The Image Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › img
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. The above example shows usage of the <img> element: The src attribute is required, and contains the path to the image you want to embed. The alt attribute holds a text description of the image, which isn't mandatory but is incredibly useful for accessibility -- screen readers read this description out to their users so they know what the image means. ...
<input type="image"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › image
ontext (that is, a tab, window, or <iframe>. A value specified here overrides any target given by the target attribute on the <form> that owns this input. In addition to the actual names of tabs, windows, or inline frames, there are a few special keywords that can be used: _self Loads the response into the same browsing context as the one that contains the form. This will replace the current document with the received data. This is the default value used if none is specified. _blank Loads the response into a new, unnamed, browsing context. This is typically a new tab in the same window as the current document, but may differ depending on the configuration of the user agent. _parent Loads the response into the parent browsing context of the current one. If there is no parent context, this ...
<input type="radio"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › radio
actChoice2">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.innerText = output; event.preventDefault(); }, false); Try this example out and see how there's never more than one result for the ...
<input type="range"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › range
ribute Description list The id of the <datalist> element that contains optional pre-defined options max The maximum permitted value min The minimum permitted value step The stepping interval, used both for user interface and validation purposes list The values of the list attribute is the id of a <datalist> element located in the same document. The <datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. See the range control with hash marks below for an example of how the opti...
<input type="submit"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › submit
ontext (that is, a tab, window, or <iframe>. A value specified here overrides any target given by the target attribute on the <form> that owns this input. In addition to the actual names of tabs, windows, or inline frames, there are a few special keywords that can be used: _self Loads the response into the same browsing context as the one that contains the form. This will replace the current document with the received data. This is the default value used if none is specified. _blank Loads the response into a new, unnamed, browsing context. This is typically a new tab in the same window as the current document, but may differ depending on the configuration of the user agent. _parent Loads the response into the parent browsing context of the current one. If there is no parent context, this ...
<ins> - HTML: Hypertext Markup Language
Web › HTML › Element › ins
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. Content categories Phrasing content or flow content. Permitted content Transparent. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts phrasing content. ...
<label> - HTML: Hypertext Markup Language
Web › HTML › Element › label
that the label is labeling is called the labeled control of the label element. One input can be associated with multiple labels. When a <label> is clicked or tapped and it is associated with a form control, the resulting click event is also raised for the associated control. Attributes This element includes the global attributes. for The id of a labelable form-related element in the same document as the <label> element. The first element in the document with an id matching the value of the for attribute is the labeled control for this label element, if it is a labelable element. If it is not labelable then the for attribute has no effect. If there are other elements which also match the id value, later in the document, they are not considered. Note: A <label> element can have both a for ...
<map> - HTML: Hypertext Markup Language
Web › HTML › Element › map
ce HTMLMapElement Attributes This element includes the global attributes. name The name attribute gives the map a name so that it can be referenced. The attribute must be present and must have a non-empty value with no space characters. The value of the name attribute must not be a compatibility-caseless match for the value of the name attribute of another <map> element in the same document. If the id attribute is also specified, both attributes must have the same value. Examples <map name="primary"> <area shape="circle" coords="75,75,75" href="left.html"> <area shape="circle" coords="275,75,75" href="right.html"> </map> <img usemap="#primary" src="https://udn.realityripple.com/samples/6a/7e559101b3.png" alt="350 x 150 pic"> Result Expected live example output The live ...
<mark>: The Mark Text element - HTML: Hypertext Markup Language
Web › HTML › Element › mark
r block quote (<blockquote>), it generally indicates text which is of special interest but is not marked in the original source material, or material which needs special scrutiny even though the original author didn't think it was of particular importance. Think of this like using a highlighter pen in a book to mark passages that you find of interest. Otherwise, <mark> indicates a portion of the document's content which is likely to be relevant to the user's current activity. This might be used, for example, to indicate the words that matched a search operation. Don't use <mark> for syntax highlighting purposes; instead, use the <span> element with appropriate CSS applied to it. Don't confuse <mark> with the <strong> element; <mark> is used to denote content which has a degree of relevance, w...
<menu> - HTML: Hypertext Markup Language
Web › HTML › Element › menu
onsist of a <menu> element whose content is described in one of two ways: either as an unordered list of items represented by <li> elements (each representing a command or option the user can utilize), or (if there are no <li> elements), flow content describing the available commands and options. This element was deprecated in HTML4, but reintroduced in HTML5.1 and the HTML living standard. This document describes the current Firefox implementation. Type 'list' is likely to change to 'toolbar' according to HTML5.1. Examples Context menu HTML <!-- A <div> element with a context menu --> <div contextmenu="popup-menu"> Right-click to see the adjusted context menu </div> <menu type="context" id="popup-menu"> <menuitem>Action</menuitem> <menuitem>Another action</menuitem> <hr/> <menu...
theme-color - HTML: Hypertext Markup Language
Web › HTML › Element › meta › name › theme-color
heme-color value for the name attribute of the <meta> element indicates a suggested color that user agents should use to customize the display of the page or of the surrounding user interface. If specified, the content attribute must contain a valid CSS <color>. Example <meta name="theme-color" content="#4285f4"> The following image shows the effect that the <meta> element above will have on a document displayed in Chrome running on an Android mobile device. Image credit: from Icons & Browser Colors, created and shared by Google and used according to terms described in the Creative Commons 4.0 Attribution License. Specifications Specification HTML Living StandardThe definition of 'theme-color' in that specification. ...
<meter>: The HTML Meter element - HTML: Hypertext Markup Language
Web › HTML › Element › meter
ferable. For example, if it is between the min attribute and the low attribute, then the lower range is considered preferred. The browser may color the meter's bar differently depending on whether the value is less than or equal to the optimum value. form The <form> element to associate the <meter> element with (its form owner). The value of this attribute must be the id of a <form> in the same document. If this attribute is not set, the <button> is associated with its ancestor <form> element, if any. This attribute is only used if the <meter> element is being used as a form-associated element, such as one displaying a range corresponding to an <input type="number">. Examples Simple example HTML <p>Heat the oven to <meter min="200" max="500" value="350">350 degrees</meter>.</p> Result ...
<multicol>: The HTML Multi-Column Layout element (Obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › multicol
The HTML Multi-Column Layout element (<multicol>) was an experimental element designed to allow multi-column layouts and must not be used. It never got any significant traction and is not implemented in any major browsers. It's covered here only to warn you off in case you stumble on it in any other documentation. Do not use this! In order to implement a multi-column layout, you should be using the regular HTML elements, like <div> in conjunction with CSS columns. Specifications None. ...
<noframes>: The Frame Fallback element - HTML: Hypertext Markup Language
Web › HTML › Element › noframes
noframes>, provides content to be presented in browsers that don't support (or have disabled support for) the <frame> element. Although most commonly-used browsers support frames, there are exceptions, including certain special-use browsers including some mobile browsers, as well as text-mode browsers. A <noframes> element can contain any HTML elements that are allowed within the body of an HTML document, with the exception of the <frameset> and <frame> elements, since using frames when they aren't supported doesn't make sense. <noframes> can be used to present a message explaining that the user's browser doesn't support frames, but ideally should be used to present an alternate form of the site that doesn't use frames but still offers the same or similar functionality. In HTML 5 and later, <n...
<noscript> - HTML: Hypertext Markup Language
Web › HTML › Element › noscript
ant of the <head> element: any transparent content, but no <noscript> element must be among its descendants. Otherwise: flow content or phrasing content. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts phrasing content, if there are no ancestor <noscript> element, or in a <head> element (but only for an HTML document), here again if there are no ancestor <noscript> element. Implicit ARIA role No corresponding role Permitted ARIA roles No role permitted DOM interface HTMLElement Attributes This element only includes the global attributes. Examples <noscript> <!-- anchor linking to external file --> <a href="https://www.mozilla.com/">External Link</a> </noscript...
<ol>: The Ordered List element - HTML: Hypertext Markup Language
Web › HTML › Element › ol
"iv," use start="4". type Sets the numbering type: a for lowercase letters A for uppercase letters i for lowercase Roman numerals I for uppercase Roman numerals 1 for numbers (default) The specified type is used for the entire list unless a different type attribute is used on an enclosed <li> element. Note: Unless the type of the list number matters (like legal or technical documents where items are referenced by their number/letter), use the CSS list-style-type property instead. Usage notes Typically, ordered list items display with a preceding marker, such as a number or letter. The <ol> and <ul> elements may nest as deeply as desired, alternating between <ol> and <ul> however you like. The <ol> and <ul> elements both represent a list of items. The difference is w...
<option>: The HTML Option element - HTML: Hypertext Markup Language
Web › HTML › Element › option
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. Content categories None. Permitted content Text, possibly with escaped characters (like &eacute;). ...
<output>: The Output element - HTML: Hypertext Markup Language
Web › HTML › Element › output
DOM interface HTMLOutputElement Attributes This element includes the global attributes. for A space-separated list of other elements' ids, indicating that those elements contributed input values to (or otherwise affected) the calculation. form The <form> element to associate the output with (its form owner). The value of this attribute must be the id of a <form> in the same document. (If this attribute is not set, the <output> is associated with its ancestor <form> element, if any.) This attribute lets you associate <output> elements to <form>s anywhere in the document, not just inside a <form>. It can also override an ancestor <form> element. name The element's name. Used in the form.elements API. The <output> value, name, and contents are NOT submitted during form sub...
<param>: The Object Parameter element - HTML: Hypertext Markup Language
Web › HTML › Element › param
ly used if the valuetype is set to ref. Specifies the MIME type of values found at the URI specified by value. valuetype Specifies the type of the value attribute. Possible values are: data: Default value. The value is passed to the object's implementation as a string. ref: The value is a URI to a resource where run-time values are stored. object: An ID of another <object> in the same document. Examples Please see the <object> page for examples on <param>. Specifications Specification Status Comment HTML Living StandardThe definition of '<param>' in that specification. Living Standard HTML5The definition of '<param>' in that specification. Recommendation HTML 4.01 SpecificationThe definition of '<param>' in that speci...
<q>: The Inline Quotation element - HTML: Hypertext Markup Language
Web › HTML › Element › q
g role Permitted ARIA roles Any DOM interface HTMLQuoteElement Usage note: Most modern browsers will automatically add quotation marks around text inside a <q> element. A style rule may be needed to add quotation marks in older browsers. Attributes This element includes the global attributes. cite The value of this attribute is a URL that designates a source document or message for the information quoted. This attribute is intended to point to information explaining the context or the reference for the quote. Example <p>According to Mozilla's website, <q cite="https://www.mozilla.org/about/history/details/">Firefox 1.0 was released in 2004 and became a big success.</q></p> Specifications Specification Status Comment H...
<s> - HTML: Hypertext Markup Language
Web › HTML › Element › s
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. Content categories Phrasing content or flow content. ...
<shadow>: The obsolete Shadow Root element - HTML: Hypertext Markup Language
Web › HTML › Element › shadow
ntal technology. For this code to work, the browser you display it in must support Web Components. See Enabling Web Components in Firefox. <html> <head></head> <body> <!-- This <div> will hold the shadow roots. ...
<summary>: The Disclosure Summary element - HTML: Hypertext Markup Language
Web › HTML › Element › summary
isplayed as the disclosure widget next to the label from the default, which is typically a triangle. You can also change the style to display: block to remove the disclosure triangle. See the Browser compatibility section for details, as not all browsers support full functionality of this element yet. Examples Below are some examples showing <summary> in use. You can find more examples in the documentation for the <details> element. Basic example A simple example showing the use of <summary> in a <details> element: <details open> <summary>Overview</summary> <ol> <li>Cash on hand: $500.00</li> <li>Current invoice: $75.30</li> <li>Due date: 5/6/19</li> </ol> </details> Summaries as headings You can use heading elements in <summary>, like this: <details open> <summary>...
<table>: The Table element - HTML: Hypertext Markup Language
Web › HTML › Element › table
ending tag are mandatory. Permitted parents Any element that accepts flow content Implicit ARIA role table Permitted ARIA roles Any DOM interface HTMLTableElement Attributes This element includes the global attributes. Deprecated attributes align This enumerated attribute indicates how the table must be aligned inside the containing document. It may have the following values: left: the table is displayed on the left side of the document; center: the table is displayed in the center of the document; right: the table is displayed on the right side of the document. Set margin-left and margin-right to auto or margin to 0 auto to achieve an effect that is similar to the align attribute. bgcolor The background color of...
<tbody>: The Table Body element - HTML: Hypertext Markup Language
Web › HTML › Element › tbody
align property instead. Usage notes If the table includes a <thead> block (to semantically identify header rows), the <tbody> block must come after it. If you use <tbody>, you can't also have table rows (<tr> elements) which are direct children of the <table> but not included inside the <tbody>. All non-header and non-footer rows must be inside the <tbody> if one is used. When printing a document, the <thead> and <tfoot> elements specify information that may be the same--or at least very similar--on every page of a multi-page table, while the <tbody> element's contents generally will differ from page to page. When a table is presented in a screen context (such as a window) which is not large enough to display the entire table, the user agent may let the user scroll the contents of the <t...
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. ...
id - HTML: Hypertext Markup Language
Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS). The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. This attribute's value is an opaque string: this means that web authors should not rely on it to convey human-readable information (although having your IDs somewhat human-readable can be useful for code comprehension, e.g. consider ticket-18659 versus r45tgfe-freds&$@). ...
is - HTML: Hypertext Markup Language
Examples The following code is taken from our word-count-web-component example (see it live also). ...
itemref - HTML: Hypertext Markup Language
Note: the itemref attribute is not part of the microdata data model. It is merely a syntactic construct to aid authors in adding annotations to pages where the data to be annotated does not follow a convenient tree structure. ...
title - HTML: Hypertext Markup Language
pairment People with cognitive concerns This is due to inconsistent browser support, compounded by the additional assistive technology parsing of the browser-rendered page. If a tooltip effect is desired, it is better to use a more accessible technique that can be accessed with the above browsing methods. 3.2.5.1. The title attribute | W3C HTML 5.2: 3. Semantics, structure, and APIs of HTML documents Using the HTML title attribute - updated | The Paciello Group Tooltips & Toggletips - Inclusive Components The Trials and Tribulations of the Title Attribute - 24 Accessibility Specifications Specification Status Comment HTML Living StandardThe definition of 'title' in that specification. Living Standard No change from latest snapshot, HTML 5.1 HT...
Inline elements - HTML: Hypertext Markup Language
till would not allow to nest a div element inside it. Conceptual differences In brief, here are the basic conceptual differences between inline and block-level elements: Content model Generally, inline elements may contain only data and other inline elements. You can't put block elements inside inline elements. Formatting By default, inline elements do not force a new line to begin in the document flow. Block elements, on the other hand, typically cause a line break to occur (although, as usual, this can be changed using CSS). List of "inline" elements The following elements are inline by default (although block and inline elements are no longer defined in HTML 5, use content categories instead): <a> <abbr> <acronym> <audio> (if it has visible controls) <b> <bdi> <bdo> <big> ...
Link types: modulepreload - HTML: Hypertext Markup Language
Specifications Specification Status Comment HTML Living StandardThe definition of 'modulepreload' in that specification. Living Standard ...
Link types: noopener - HTML: Hypertext Markup Language
The noopener keyword for the rel attribute of the <a>, <area>, and <form> elements instructs the browser to navigate to the target resource without granting the new browsing context access to the document that opened it -- by not setting the Window.opener property on the opened window (it returns null). This is especially useful when opening untrusted links, in order to ensure they cannot tamper with the originating document via the Window.opener property (see About rel=noopener for more details), while still providing the Referer HTTP header (unless noreferrer is used as well). Note that when noopener is used, nonempty target names other than _top, _self, and _parent are all treated like _blank in terms of deciding whether to open a new window/tab. Specifications Specificatio...
Microdata - HTML: Hypertext Markup Language
. itemprop - Used to add properties to an item. Every HTML element may have an itemprop attribute specified, where an itemprop consists of a name and value pair. itemref - Properties that are not descendants of an element with the itemscope attribute can be associated with the item using an itemref. Itemref provides a list of element ids (not itemids) with additional properties elsewhere in the document. itemscope - Itemscope (usually) works along with itemtype to specify that the HTML contained in a block is about a particular item. itemscope creates the Item and defines the scope of the itemtype associated with it. itemtype is a valid URL of a vocabulary (such as schema.org) that describes the item and its properties context. itemtype - Specifies the URL of the vocabulary that will be used t...
HTML reference - HTML: Hypertext Markup Language
ave attributes; these are additional values that configure the elements or adjust their behavior in various ways to meet the criteria the users want. Global attributes Global attributes are attributes common to all HTML elements; they can be used on all elements, though they may have no effect on some elements. Link types In HTML, the following link types indicate the relationship between two documents, in which one links to the other using an <a>, <area>, or <link> element. Content Categories Every HTML element is a member of one or more content categories -- these categories group elements that share common characteristics. Date and time formats used in HTML Certain HTML elements allow you to specify dates and/or times as the value or as the value of an attribute. These include the date ...
HTTP authentication - HTTP
source, the server should respond with the 403 Forbidden status code. Unlike 401 Unauthorized or 407 Proxy Authentication Required, authentication is impossible for this user. Authentication of cross-origin images A potential security hole recently been fixed by browsers is authentication of cross-site images. From Firefox 59 onwards, image resources loaded from different origins to the current document are no longer able to trigger HTTP authentication dialogs (bug 1423146), preventing user credentials being stolen if attackers were able to embed an arbitrary image into a third-party page. Character encoding of HTTP authentication Browsers use utf-8 encoding for usernames and passwords. Firefox once used ISO-8859-1, but changed to utf-8 for parity with other browsers and to avoid potential pr...
Choosing between www and non-www URLs - HTTP
A server isn't necessarily a physical machine: several servers can reside on the same physical machine. ...
Cross-Origin Resource Sharing (CORS) - HTTP
Web › HTTP › CORS
gery have nothing new to fear from HTTP access control. Note: WebKit Nightly and Safari Technology Preview place additional restrictions on the values allowed in the Accept, Accept-Language, and Content-Language headers. If any of those headers have "nonstandard" values, WebKit/Safari does not consider the request to be a "simple request". ...
Compression in HTTP - HTTP
Over the years, algorithms also got more efficient, and new ones are supported by clients and servers. In practice, web developers don't need to implement compression mechanisms, both browsers and servers have it implemented already, but they have to be sure that the server is configured adequately. ...
Connection management in HTTP/1.x - HTTP
s). The HTTP headers involved in defining the connection model, like Connection and Keep-Alive, are hop-by-hop headers with their values able to be changed by intermediary nodes. A related topic is the concept of HTTP connection upgrades, wherein an HTTP/1.1 connection is upgraded to a different protocol, such as TLS/1.0, WebSocket, or even HTTP/2 in cleartext. This protocol upgrade mechanism is documented in more detail elsewhere. Short-lived connections The original model of HTTP, and the default one in HTTP/1.0, is short-lived connections. Each HTTP request is completed on its own connection; this means a TCP handshake happens before each HTTP request, and these are serialized. The TCP handshake itself is time-consuming, but a TCP connection adapts to its load, becoming more efficient with ...
List of default Accept values - HTTP
Default values These are the values sent when the context doesn't give better information. Note that all browsers add the */* MIME Type to cover all cases. This is typically used for requests initiated via the address bar of a browser, or via an HTML <a> element. ...
Access-Control-Allow-Origin - HTTP
n be specified. If the server supports clients from multiple origins, it must return the origin for the specific client making the request. null Specifies the origin "null". Note: null should not be used: "It may seem safe to return Access-Control-Allow-Origin: "null", but the serialization of the Origin of any resource that uses a non-hierarchical scheme (such as data: or file:) and sandboxed documents is defined to be "null". Many User Agents will grant such documents access to a response with an Access-Control-Allow-Origin: "null" header, and any origin can create a hostile document with a "null" Origin. The "null" value for the ACAO header should therefore be avoided." Examples A response that tells the browser to allow code from any origin to access a resource will include the followi...
Cache-Control - HTTP
erver in an HTTP response. Cache-Control: must-revalidate Cache-Control: no-cache Cache-Control: no-store Cache-Control: no-transform Cache-Control: public Cache-Control: private Cache-Control: proxy-revalidate Cache-Control: max-age=<seconds> Cache-Control: s-maxage=<seconds> Extension Cache-Control directives Extension Cache-Control directives are not part of the core HTTP caching standards document. Check the compatibility table for their support; user-agents that don't recognize them should ignore them. Cache-Control: immutable Cache-Control: stale-while-revalidate=<seconds> Cache-Control: stale-if-error=<seconds> Directives Cacheability A response is normally cached by the browser if: it has a status code of 301, 302, 307, 308, or 410 and Cache-Control does not have no-store, or ...
Content-Range - HTTP
>-<range-end>/<size> Content-Range: <unit> <range-start>-<range-end>/* Content-Range: <unit> */<size> Directives <unit> The unit in which ranges are specified. This is usually bytes. <range-start> An integer in the given unit indicating the beginning of the request range. <range-end> An integer in the given unit indicating the end of the requested range. <size> The total size of the document (or '*' if unknown). Examples Content-Range: bytes 200-1000/67589 Specifications Specification Title RFC 7233, section 4.2: Content-Range Hypertext Transfer Protocol (HTTP/1.1): Range Requests ...
CSP: block-all-mixed-content - HTTP
The upgrade-insecure-requests directive is evaluated before block-all-mixed-content. ...
CSP: child-src - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: connect-src - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: default-src - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: font-src - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: form-action - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: frame-ancestors - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. Examples Content-Security-Policy: frame-a...
CSP: frame-src - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: img-src - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: manifest-src - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: media-src - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: object-src - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: prefetch-src - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: referrer - HTTP
alues: "no-referrer" The Referer header will be omitted entirely. No referrer information is sent along with requests. "none-when-downgrade" This is the user agent's default behavior if no policy is specified. The origin is sent as referrer to a-priori as-much-secure destination (HTTPS->HTTPS), but isn't sent to a less secure destination (HTTPS->HTTP). "origin" Only send the origin of the document as the referrer in all cases. The document https://example.com/page.html will send the referrer https://example.com/. "origin-when-cross-origin" / "origin-when-crossorigin" Send a full URL when performing a same-origin request, but only send the origin of the document for other cases. "unsafe-url" Send a full URL (stripped from parameters) when performing a same-origin or cross-origin reques...
CSP: report-uri - HTTP
Though the report-to directive is intended to replace the deprecated report-uri directive, report-to isn't supported in most browsers yet. ...
CSP: script-src-attr - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: script-src-elem - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: style-src-attr - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: style-src-elem - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
CSP: worker-src - HTTP
as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts. mediastream: Allows mediastream: URIs to be used as a content source. blob: Allows blob: URIs to be used as a content source. filesystem: Allows filesystem: URIs to be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and 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. 'uns...
ETag - HTTP
Web › HTTP › Headers › ETag
, when editing MDN, the current wiki content is hashed and put into an Etag in the response: ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4" When saving changes to a wiki page (posting data), the POST request will contain the If-Match header containing the ETag values to check freshness against. If-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4" If the hashes don't match, it means that the document has been edited in-between and a 412 Precondition Failed error is thrown. Caching of unchanged resources Another typical use of the ETag header is to cache resources that are unchanged. If a user visits a given URL again (that has an ETag set), and it is stale (too old to be considered usable), the client will send the value of its ETag along in an If-None-Match header field: If-None-Match: "3...
If-Unmodified-Since - HTTP
r non-safe method, only if it has not been last modified after the given date. If the resource has been modified after the given date, the response will be a 412 (Precondition Failed) error. There are two common use cases: In conjunction with non-safe methods, like POST, it can be used to implement an optimistic concurrency control, like done by some wikis: editions are rejected if the stored document has been modified since the original has been retrieved. In conjunction with a range request with a If-Range header, it can be used to ensure that the new fragment requested comes from an unmodified document. Header type Request header Forbidden header name no Syntax If-Unmodified-Since: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT Directives ...
SourceMap - HTTP
ent the reconstructed original in the debugger. ...
Firefox user agent string reference - HTTP
General form The UA string of Firefox itself is broken down into four components: Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail Firefox/firefoxversion Mozilla/5.0 is the general token that says the browser is Mozilla compatible, and is common to almost every browser today. platform describes the native platform the browser is running on (e.g. Windows, Mac, Linux or Android), and whether or not it's a mobile phone. ...
X-Content-Type-Options - HTTP
configured. This header was introduced by Microsoft in IE 8 as a way for webmasters to block content sniffing that was happening and could transform non-executable MIME types into executable MIME types. Since then, other browsers have introduced it, even if their MIME sniffing algorithms were less aggressive. Starting with Firefox 72, the opting out of MIME sniffing is also applied to top-level documents if a Content-type is provided. This can cause HTML web pages to be downloaded instead of being rendered when they are served with a MIME type other than text/html. Make sure to set both headers correctly. Site security testers usually expect this header to be set. Note: X-Content-Type-Options only apply request-blocking due to nosniff for request destinations of "script" and "style". However, ...
X-Frame-Options - HTTP
The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>, <iframe>, <embed> or <object>. Sites can use this to avoid click-jacking attacks, by ensuring that their content is not embedded into other sites. The added security is provided only if the user accessing the document is using a browser that supports X-Frame-Options. Note: The Content-Security-Policy HTTP header has a frame-ancestors directive which obsoletes this header for supporting browsers. Header type Response header Forbidden header name no Syntax There are two possible directives for X-Frame-Options: X-Frame-Options: DENY X-Frame-Options: SAMEORIGIN Directives If you specify DENY, not only will attempts to load ...
PATCH - HTTP
Web › HTTP › Methods › PATCH
, but not necessarily so for PATCH. PATCH (like PUT) may have side-effects on other resources. To find out whether a server supports PATCH, a server can advertise its support by adding it to the list in the Allow or Access-Control-Allow-Methods (for CORS) response headers. Another (implicit) indication that PATCH is allowed, is the presence of the Accept-Patch header, which specifies the patch document formats accepted by the server. Request has body Yes Successful response has body Yes Safe No Idempotent No Cacheable No Allowed in HTML forms No Syntax PATCH /file.txt HTTP/1.1 Example Request PATCH /file.txt HTTP/1.1 Host: www.example.com Content-Type: application/example If-Match: "e0023aa4e" Content-Length: 1...
Redirections in HTTP - HTTP
If you don't want a temporary redirect, an extra parameter (either the HTTP status code to use or the permanent keyword) can be used to set up a different redirect: Redirect permanent / https://www.example.com # ...acts the same as: Redirect 301 / https://www.example.com The mod_rewrite module can also create redirects. It is more...
A typical HTTP session - HTTP
Web › HTTP › Session
equest Once the connection is established, the user-agent can send the request (a user-agent is typically a web browser, but can be anything else, a crawler, for example). A client request consists of text directives, separated by CRLF (carriage return, followed by line feed), divided into three blocks: The first line contains a request method followed by its parameters: the path of the document, i.e. an absolute URL without the protocol or domain name the HTTP protocol version Subsequent lines represent an HTTP header, giving the server information about what type of data is appropriate (e.g., what language, what MIME types), or other data altering its behavior (e.g., not sending an answer if it is already cached). These HTTP headers form a block which ends with an empty line. ...
205 Reset Content - HTTP
Web › HTTP › Status › 205
The HTTP 205 Reset Content response status tells the client to reset the document view, so for example to clear the content of a form, reset a canvas state, or to refresh the UI. Status 205 Reset Content Specifications Specification Title RFC 7231, section 6.3.6: 205 Reset Content Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content Compatibility Notes Browser behavior differs if this response erroneously includes a body on persistent connections See 204 No Content for more detail. ...
206 Partial Content - HTTP
Web › HTTP › Status › 206
If several ranges are sent back, the Content-Type is set to multipart/byteranges and each fragment covers one range, with Content-Range and Content-Type describing it. ...
404 Not Found - HTTP
Web › HTTP › Status › 404
rarily or permanently missing. But if a resource is permanently removed, a 410 (Gone) should be used instead of a 404 status. Status 404 Not Found Custom error pages Many web sites customize the look of a 404 page to be more helpful to the user and provide guidance on what to do next. Apache servers can be configured using an .htaccess file and a code snippet like the following example. ErrorDocument 404 /notfound.html For an example of a custom 404 page, see MDN's 404 page. Custom design is a good thing, in moderation. Feel free to make your 404 page humorous and human, but don't confuse your users. Specifications Specification Title RFC 7231, section 6.5.4: 404 Not Found Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
412 Precondition Failed - HTTP
Web › HTTP › Status › 412
Specifications Specification Title RFC 7232, section 4.2: 412 Precondition Failed Hypertext Transfer Protocol (HTTP/1.1): Conditional Requests ...
416 Range Not Satisfiable - HTTP
Web › HTTP › Status › 416
The HyperText Transfer Protocol (HTTP) 416 Range Not Satisfiable error response code indicates that a server cannot serve the requested ranges. The most likely reason is that the document doesn't contain such ranges, or that the Range header value, though syntactically correct, doesn't make sense. The 416 response message contains a Content-Range indicating an unsatisfied range (that is a '*') followed by a '/' and the current length of the resource. E.g. Content-Range: bytes */12777 Faced with this error, browsers usually either abort the operation (for example, a download will be considered as non-resumable) or ask for the whole document again. Status 416 Range Not Satisfiable Specifications Specification Title RFC 7233, section 4.4: 416 Request Not Satisfiable ...
HTTP response status codes - HTTP
Web › HTTP › Status
or a third-party copy. This is mostly used for mirrors or backups of another resource. Except for that specific case, the "200 OK" response is preferred to this status. 204 No Content There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones. 205 Reset Content Tells the user-agent to reset the document which sent this request. 206 Partial Content This response code is used when the Range header is sent from the client to request only part of a resource. 207 Multi-Status (WebDAV) Conveys information about multiple resources, for situations where multiple status codes might be appropriate. 208 Already Reported (WebDAV) Used inside a <dav:propstat> response element to avoid repeatedly enumer...
Control flow and error handling - JavaScript
rue and false values of the Boolean object! For example: var b = new Boolean(false); if (b) // this condition evaluates to true if (b == true) // this condition evaluates to false Example In the following example, the function checkData returns true if the number of characters in a Text object is three. Otherwise, it displays an alert and returns false. function checkData() { if (document.form1.threeChar.value.length == 3) { return true; } else { alert( 'Enter exactly three characters. ' + `${document.form1.threeChar.value} is not valid.`); return false; } } switch statement A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the assoc...
Expressions and operators - JavaScript
rds true and null, the typeof operator returns the following results: typeof true; // returns "boolean" typeof null; // returns "object" For a number or string, the typeof operator returns the following results: typeof 62; // returns "number" typeof 'Hello world'; // returns "string" For property values, the typeof operator returns the type of value the property contains: typeof document.lastModified; // returns "string" typeof window.length; // returns "number" typeof Math.LN2; // returns "number" For methods and functions, the typeof operator returns results as follows: typeof blur; // returns "function" typeof eval; // returns "function" typeof parseInt; // returns "function" typeof shape.split; // returns "function" For predefined ob...
Regular expressions - JavaScript
llowed by the remembered match of a dash, forward slash, or decimal point \1, followed by four digits \d{4}. The Change event activated when the user presses Enter sets the value of RegExp.input. HTML <p> Enter your phone number (with area code) and then click "Check". <br> The expected format is like ###-###-####. ...
Working with objects - JavaScript
myCar.color = "red"). If you initially define an object property with an index, such as myCar[5] = "25 mpg", you subsequently refer to the property only as myCar[5]. The exception to this rule is array-like object reflected from HTML, such as the forms array-like object. You can always refer to objects in these array-like objects by either their ordinal number (based on where they appear in the document) or their name (if defined). For example, if the second <FORM> tag in a document has a NAME attribute of "myForm", you can refer to the form as document.forms[1] or document.forms["myForm"] or document.forms.myForm. Defining properties for an object type You can add a property to a previously defined object type by using the prototype property. This defines a property that is shared by all obje...
Public class fields - JavaScript
nsole.log(ClassWithStaticField.anotherBaseStaticField) // expected output: "base static field" console.log(SubClassWithStaticField.subStaticField) // expected output: "base static method output" Public instance fields Public instance fields exist on every created instance of a class. By declaring a public field, you can ensure the field is always present, and the class definition is more self-documenting. Public instance fields are added with Object.defineProperty() either at construction time in the base class (before the constructor body runs), or just after super() returns in a subclass. class ClassWithInstanceField { instanceField = 'instance field' } const instance = new ClassWithInstanceField() console.log(instance.instanceField) // expected output: "instance field" Fields without ...
Classes - JavaScript
wsers is limited, but the feature can be used through a build step with systems like Babel. Public field declarations With the JavaScript field declaration syntax, the above example can be written as: class Rectangle { height = 0; width; constructor(height, width) { this.height = height; this.width = width; } } By declaring fields up-front, class definitions become more self-documenting, and the fields are always present. As seen above, the fields can be declared with or without a default value. See public class fields for more information. Private field declarations Using private fields, the definition can be refined as below. class Rectangle { #height = 0; #width; constructor(height, width) { this.#height = height; this.#width = width; } } It's an err...
RangeError: invalid date - JavaScript
rings usually return NaN. However, depending on the implementation, non-conforming ISO format strings, may also throw RangeError: invalid date, like the following cases in Firefox: new Date('foo-bar 2014'); new Date('2014-25-23').toISOString(); new Date('foo-bar 2014').toString(); This, however, returns NaN in Firefox: Date.parse('foo-bar 2014'); // NaN For more details, see the Date.parse() documentation. Valid cases new Date('05 October 2011 14:48 UTC'); new Date(1317826080); // Unix Time Stamp for 05 October 2011 14:48:00 UTC ...
SyntaxError: missing variable name - JavaScript
t be variable names There are a few variable names that are reserved keywords. You can't use these. Sorry :( var debugger = "whoop"; // SyntaxError: missing variable name Declaring multiple variables Pay special attention to commas when declaring multiple variables. Is there an excess comma? Did you accidentally add commas instead of semicolons? var x, y = "foo", var x, = "foo" var first = document.getElementById('one'), var second = document.getElementById('two'), // SyntaxError: missing variable name The fixed version: var x, y = "foo"; var x = "foo"; var first = document.getElementById('one'); var second = document.getElementById('two'); Arrays Array literals in JavaScript need square brackets around the values. This won't work: var arr = 1,2,3,4,5; // SyntaxError: missing variab...
getter - JavaScript
re not "lazy" or "memozied" by nature; you must implement this technique if you desire this behavior. In the following example, the object has a getter as its own property. On getting the property, the property is removed from the object and re-added, but implicitly as a data property this time. Finally, the value gets returned. get notifier() { delete this.notifier; return this.notifier = document.getElementById('bookmarked-notification-anchor'); }, For Firefox code, see also the XPCOMUtils.jsm code module, which defines the defineLazyGetter() function. get vs. defineProperty While using the get keyword and Object.defineProperty() have similar results, there is a subtle difference between the two when used on classes. When using get the property will be defined on the instance's protot...
Array.prototype[@@iterator]() - JavaScript
ion 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.map() - JavaScript
.charCodeAt(0) }) // a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] Using map generically querySelectorAll This example shows how to iterate through a collection of objects collected by querySelectorAll. This is because querySelectorAll returns a NodeList (which is a collection of objects). In this case, we return all the selected options' values on the screen: let elems = document.querySelectorAll('select option:checked') let values = Array.prototype.map.call(elems, function(obj) { return obj.value }) An easier way would be the Array.from() method. Tricky use case (inspired by this blog post) It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional o...
Boolean - JavaScript
ue of a Boolean object, the new Boolean object has a value of true. var myFalse = new Boolean(false); // initial value of false var g = Boolean(myFalse); // initial value of true var myString = new String('Hello'); // string object var s = Boolean(myString); // initial value of true Do not use a Boolean object in place of a Boolean primitive. Note: When the non-standard property document.all is used as an argument for this constructor, the result is a Boolean object with the value false. This property is legacy and non-standard and should not be used. Constructor Boolean() Creates a new Boolean object. Instance methods Boolean.prototype.toString() Returns a string of either true or false depending upon the value of the object. Overrides the Object.prototype.toString()...
FinalizationRegistry - JavaScript
er 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 proposal that FinalizationRegistry is part of included in its explainer document: Garbage collectors are complicated. If an application or library depends on GC cleaning up a FinalizationRegistry or calling a finalizer [cleanup callback] in a timely, predictable manner, it's likely to be disappointed: the cleanup may happen much later than expected, or not at all. Sources of variability include: One object might be garbage-collected much sooner than another object, even ...
Function.prototype.bind() - JavaScript
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 ignored. However, provided ar...
Set - JavaScript
es()) console.log(item) // logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} // (key and value are the same here) for (let [key, value] of mySet.entries()) console.log(key) // convert Set object to an Array object, with Array.from let myArr = Array.from(mySet) // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}] // the following will also work if run in an HTML document mySet.add(document.body) mySet.has(document.querySelector('body')) // true // converting between Set and Array mySet2 = new Set([1, 2, 3, 4]) mySet2.size // 4 [...mySet2] // [1, 2, 3, 4] // intersect can be simulated via let intersection = new Set([...set1].filter(x => set2.has(x))) // difference can be simulated via let difference = new Set([...set1].filt...
String.prototype.anchor() - JavaScript
<a name="..."> start tag. Return value A string beginning with an <a name="name"> start tag, then the text str, and then an </a> end tag Description Don't use this method. Use DOM APIs instead. Also, the HTML specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup. Examples Using anchor() var myString = 'Table of Contents'; document.body.innerHTML = myString.anchor('contents_anchor'); will output the following HTML: <a name="contents_anchor">Table of Contents</a> Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.anchor' in that specification. ...
String.prototype.big() - JavaScript
...
String.prototype.fontcolor() - JavaScript
...
String.prototype.fontsize() - JavaScript
...
String.prototype.link() - JavaScript
rl) Parameters url Any string that specifies the href attribute of the <a> tag; it should be a valid URL (relative or absolute), with any & characters escaped as &amp;, and any " characters escaped as &quot;. Return value A string containing an <a> HTML element. Description Use the link() method to create an HTML snippet for a hypertext link. The returned string can then be added to the document via document.write() or element.innerHTML. Links created with the link() method become elements in the links array of the document object. See document.links. Examples Using link() The following example displays the word "MDN" as a hypertext link that returns the user to the Mozilla Developer Network. var hotText = 'MDN'; var URL = 'https://developer.mozilla.org/'; console.log('Click to ret...
String.prototype.small() - JavaScript
...
Symbol.toStringTag - JavaScript
...
WebAssembly.Global() constructor - JavaScript
bal instance being created using the WebAssembly.Global() constructor. It is being defined as a mutable i32 type, with a value of 0. The value of the global is then changed, first to 42 using the Global.value property, and then to 43 using the incGlobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value). ...
WebAssembly.Global - JavaScript
bal instance being created using the WebAssembly.Global() constructor. It is being defined as a mutable i32 type, with a value of 0. The value of the global is then changed, first to 42 using the Global.value property, and then to 43 using the incGlobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value). ...
globalThis - JavaScript
rity considerations, it references a Proxy around the actual global object (which you can't directly access). This distinction is rarely relevant in common usage, but important to be aware of. Naming Several other popular name choices such as self and global were removed from consideration because of their potential to break compatibility with existing code. See the language proposal's "naming" document for more details. Examples Search for the global across environments Prior to globalThis, the only reliable cross-platform way to get the global object for an environment was Function('return this')(). However, this causes CSP violations in some settings, so es6-shim uses a check like this, for example: var getGlobal = function () { if (typeof self !== 'undefined') { return self; } if (ty...
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 o...
Greater than (>) - JavaScript
d is greater than the right operand, and false otherwise. 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 x > y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. Examples String to string comparison console.log("a" > "b"); // false console.log("a" > "a"); // false console.log("a" > "3"); // true String to number comparison console.log("5" > 3); // true console.log("3" > 3); // false console.log("3" > 5); // false console.log("hello" > 5);...
Greater than or equal (>=) - JavaScript
han or equal to the right operand, and false otherwise. 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 x >= y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. Examples String to string comparison console.log("a" >= "b"); // false console.log("a" >= "a"); // true console.log("a" >= "3"); // true String to number comparison console.log("5" >= 3); // true console.log("3" >= 3); // true console.log("3" >= 5); // false console.log("hello" >= 5); // false ...
Less than or equal (<=) - JavaScript
han or equal to the right operand, and false otherwise. 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 x <= y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. Examples String to string comparison console.log("a" <= "b"); // true console.log("a" <= "a"); // true console.log("a" <= "3"); // false String to number comparison console.log("5" <= 3); // false console.log("3" <= 3); // true console.log("3" <= 5); // true console.log("hello" <= 5); // false ...
Logical OR assignment (||=) - JavaScript
gical operation would evaluate the right-hand side. In other words, x ||= y is equivalent to: x || (x = y); And not equivalent to the following which would always perform an assignment: x = x || y; Note that this behavior is different to mathematical and bitwise assignment operators. Examples Setting default content If the "lyrics" element is empty, set the innerHTML to a default value: document.getElementById('lyrics').innerHTML ||= '<i>No lyrics.</i>' Here the short-circuit is especially beneficial, since the element will not be updated unnecessarily and won't cause unwanted side-effects such as additional parsing or rendering work, or loss of focus, etc. Note: Pay attention to the value returned by the API you're checking against. If an empty string is returned (a falsy value), ||= ...
instanceof - JavaScript
make sense at first, but for scripts dealing with multiple frames or windows, and passing objects from one context to another via functions, this will be a valid and strong issue. For instance, you can securely check if a given object is, in fact, an Array using Array.isArray(myObj) For example, checking if a Nodes is a SVGElement in a different context, you can use myNode instanceof myNode.ownerDocument.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 Ja...
typeof - JavaScript
block until the initialization is processed, during which, it will throw an error if accessed. typeof undeclaredVariable === 'undefined'; typeof newLetVariable; // ReferenceError typeof newConstVariable; // ReferenceError typeof newClass; // ReferenceError let newLetVariable; const newConstVariable = 'hello'; class newClass{}; Exceptions All current 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 Spec...
void operator - JavaScript
word 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 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 previo...
Expressions and operators - JavaScript
Expressions and operators by category For an alphabetical listing see the sidebar on the left. Primary expressions Basic keywords and general expressions in 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. ...
for...of - JavaScript
In these cases, the iterator is closed. function* foo(){ yield 1; yield 2; yield 3; }; for (const o of foo()) { console.log(o); break; // closes iterator, execut...
for - JavaScript
at some point. var i = 0; for (;;) { if (i > 3) break; console.log(i); i++; } Using for without a statement The following for cycle calculates the offset position of a node in the final-expression section, and therefore it does not require the use of a statement section, a semicolon is used instead. ...
import.meta - JavaScript
module my-module.js <script type="module" src="my-module.js"></script> you can access meta information about the module using the import.meta object. console.log(import.meta); // { url: "file:///home/user/my-module.js" } It returns an object with a url property indicating the 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 #). For example, with the following HTML: <script type="module"> import './index.mjs?someURLInfo=5'; </script> ..the following JavaScript file will log the `someURLInfo parameter: // index.mjs new URL(import.meta.url).searchParams.get('someURLInfo'); // ...
JavaScript reference - JavaScript
arguments Arrow functions Default parameters Rest parameters Additional reference pages Lexical grammar Data types and data structures Strict mode Deprecated features ...
Web app manifests
Browsers generally support manifests with other appropriate extensions like .json (Content-Type: application/json). Note: If the manifest requir...
Web audio codec guide - Web media technologies
d files Stereo coding Simple stereo and mid-side stereo coding don't affect quality; intensity stereo coding introduces loss of detail, however. Joint stereo can reduce the size of the encoded audio to some extent The parameters available--and the range of possible values--varies from codec to codec, and even among different encoding utilities for the same codec, so read the documentation that comes with the encoding software you use to learn more. Features affecting encoded audio size Several factors affect the size of the encoded audio. Some of these are a matter of the form of the source audio; others are related to decisions made while encoding the audio. Lossless versus lossy codecs There are two basic categories of audio compression. Lossless compression algorithms ...
Digital audio concepts - Web media technologies
, or the number of times given algorithms should be run Lossy encoder parameters Most codecs have input values you can tune to optimize the compression in various ways, either for size or for quality. When using a lossy encoder, the higher the quality, the larger the encoded audio will be. Because of this, most options affect both quality and size in some manner. You will need to refer to the documentation for the encoding software you use to determine which options are available, which will depend on the codec and the encoding software itself. Some codecs have a number of values you can adjust (some of which may require a deep understanding of both psychoacoustics and of the codec's algorithms), and others offer a simple "quality" parameter you can set, which automatically adjusts various pro...
Media container formats (file types) - Web media technologies
Yes [1] Firefox support for H.264 relies upon the operating system's media infrastructure, so it is available as long as the OS supports it. Ogg The Ogg container format is a free and open format maintained by the Xiph.org Foundation. The Ogg framework also defines patent unencumbered media data formats, such as the Theora video codec and the Vorbis and Opus audio codecs. Xiph.org documents about the Ogg format are available on their web site. While Ogg has been around for a long time, it has never gained the wide support needed to make it a good first choice for a media container. You are typically better off using WebM, though there are times when Ogg is useful to offer, such as when you wish to support older versions of Firefox and Chrome which don't yet support WebM. For examp...
Codecs used by WebRTC - Web media technologies
ault color space), recommendations for webcam processing features (automatic focus, automatic white balance, automatic light level), and so on. Note: These requirements are for web browsers and other fully-WebRTC compliant products. Non-WebRTC products that are able to communicate with WebRTC to some extent may or may not support these codecs, although they're encouraged to by the specification documents. In addition to the mandatory codecs, some browsers support additional codecs as well. Those are listed in the following table. Other video codecs Codec name Profile(s) Browser compatibility VP9 -- Chrome (48+), Firefox VP8 VP8, which we describe in general in the main guide to video codecs used on the web, has some specific requirements that must be...
Using audio and video in HTML - Web media technologies
> and <video> elements let you embed audio and video content into a web page. More than that, their underlying interfaces are the key to manipulating and playing back media in general, even offscreen. In this guide, we'll review the media elements and how to use them in HTML content. Note: This guide is a planned update to integrate content from various scattered places on MDN into one cohesive document or document set. The work is not yet scheduled but hopefully will come soon. For now, some of the key information you may be looking for can be found in our Learning Area article on the topic. We don't have a particularly good guide to using these objects offscreen at this time, although Audio and video manipulation may be a good start. ...
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
This change means that the aspect ratio of the image is calculated by the browser early on and can then be used to correct the size needed to display the image before it has loaded, if CSS has been applied that causes problems with its display size. Read on to find out more. ...
Using images in HTML - Web media technologies
Web › Media › images
In this guide you'll find links to resources that deal with adding images to websites. References These articles cover some of the HTML elements and CSS properties that are used to control how images are displayed on the web. HTML <img> The HTML <img> element is used to embed an image in a webpage. It supports a wide range of attributes that control how the image behaves and allows you to add important information like alt text for people who don't see the image. ...
Web media technologies
s ability to present, create, and manage audio, video, and other media has grown at an increasing pace. Today, there are a large number of APIs available, as well as HTML elements, DOM interfaces, and other features that make it possible to not only perform these tasks, but use media in tandem with other technologies to do truly remarkable things. This article lists the various APIs with links to documentation you may find helpful in mastering them. References HTML These articles cover HTML features for media developers. <audio> The <audio> element is used to play audio in a Web context. These can be used invisibly as a destination for more complex media, or with visible controls for user-controlled playback of audio files. Accessible from JavaScript as HTMLAudioElement objects. <video> ...
Optimizing startup performance - Web Performance
startup code on the main thread. However, even code like that can be made asynchronous, with a little work. Getting asynchronous Here are some suggestions for how to build your startup process to be as asynchronous as possible (whether it's a new app or a port): Use the defer or async attribute on script tags needed by the Web application. This allows HTML parsers to continue processing the document, instead of having to wait until the scripts have been downloaded and executed before continuing. If you need to decode asset files (for example, decoding JPEG files and turning them into raw texture data for later use by WebGL), that's great to do in workers. When dealing with data supported by the browser (for example, decoding image data), use the decoders built into the browser or device ra...
PWA developer guide - Progressive web apps (PWAs)
--->>> Titles below are just for the list; give articles good SEO names and feel free to tweak those and this as needed... <<<--- Web app basics Introduction and getting started with PWA development some description Installing and uninstalling web apps An introductory guide to how a web app can be installed on the user's device... ...
How to make PWAs installable - Progressive web apps (PWAs)
atory, but to be certain we're on the same page: name: The full name of your web app. short_name: Short name to be shown on the home screen. description: A sentence or two explaining what your app does. icons: A bunch of icon information -- source URLs, sizes, and types. Be sure to include at least a few, so that one that fits best will be chosen for the user's device. start_url: The index document to launch when starting the app. display: How the app is displayed; can be fullscreen, standalone, minimal-ui, or browser. theme_color: A primary color for the UI, used by operating system. background_color: A color used as the app's default background, used during install and on the splash screen. A minimal web manifest must have at least a name and an icons field with at least one icon def...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
d and do them in the worker, and receive results as soon as they are available. Performance-wise, you can prefetch resources that are not needed right now, but might be in the near future, so the app will be faster when you actually need those resources. Summary In this article we took a simple look at how you can make your PWA work offline with service workers. Be sure to check out our further documentation if you want to learn more about the concepts behind the Service Worker API and how to use it in more detail. Service Workers are also used when dealing with push notifications -- this will be explained in a subsequent article. Previous Overview: Progressive web apps Next ...
The building blocks of responsive design - Progressive web apps (PWAs)
Next up, the font-size of the buttons is set to 6.8vw. Why? Because the top-margin of the x-cards was set to 17vw earlier on. All buttons in the app have been set to have a line-height of 2.5, in the default CSS at the top of the stylesheet (check if you don't believe me.) And 6.8 x 2.5 = 17. Last, w...
Web API reference - Web technology reference
Web › Reference › API
APIs to perform various useful tasks. These can be accessed using JavaScript code, and let you do anything from making minor adjustments to any window or element, to generating intricate graphical and audio effects using APIs such as WebGL and Web Audio. 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. Device APIs This set of APIs allows access to various hardware features available to Web pages and applications. E.g. Ambient Light Sensor API, Geolocation API, Pointer Lock ...
baseProfile - SVG: Scalable Vector Graphics
The baseProfile attribute describes the minimum SVG language profile that the author believes is necessary to correctly render the content. The attribute does not specify any processing restrictions; It can be considered metadata. For example, the value of the attribute could be used by an authoring tool to warn the user when they are modifying the document beyond the scope of the specified base profile. Each SVG profile should define the text that is appropriate for this attribute. Only one element is using this attribute: <svg> Context notes Value Profile name Default value none Animatable No Example <svg width="120" height="120" version="1.1" xmlns="http://www.w3.org/2000/svg" baseProfile="full"> ... </svg> Specifications Speci...
begin - SVG: Scalable Vector Graphics
Web › SVG › Attribute › begin
nd <set>, begin defines when the element should begin, i.e. become active. Value <begin-value-list> Default value 0s Animatable No The <begin-value-list> is a semicolon-separated list of values. Each value can be one of the following: <offset-value> This value defines a clock-value that represents a point in time relative to the beginning of the SVG document (usually the load or DOMContentLoaded event). Negative values are valid. <syncbase-value> This value defines a syncbase and an optional offset from that syncbase. The element's animation start time is defined relative to the begin or active end of another animation. A valid syncbase-value consists of an ID reference to another animation element followed by a dot and either begin or end to iden...
class - SVG: Scalable Vector Graphics
Web › SVG › Attribute › class
separated by whitespace characters. An element's class name serves two key roles: As a style sheet selector, for when an author assigns style information to a set of elements. For general use by the browser. You can use this class to style SVG content using CSS. Usage context Categories None Value <list-of-class-names> Animatable Yes Normative document SVG 1.1 (2nd Edition): The class attribute List-of-Ts <list-of-Ts> (Where T is some type.) A list consists of a separated sequence of values. Unless explicitly described differently, lists within SVG's XML attributes can be either comma-separated (with optional white space before or after the comma), or white space-separated. White space in lists is defined as one or more of the...
clip-rule - SVG: Scalable Vector Graphics
shape: <g> <clipPath id="MyClip"> <path d="..." /> </clipPath> <rect clip-path="url(#MyClip)" clip-rule="evenodd" ... /> </g> As a presentation attribute, it also can be used as a property directly inside a CSS stylesheet Usage context Categories Presentation attribute Value nonzero | evenodd | inherit Animatable Yes Normative document SVG 1.1 (2nd Edition) nonzero See description of fill-rule property. evenodd See description of fill-rule property. Example <svg width="100" viewBox="0 0 100 90" xmlns="http://www.w3.org/2000/svg" version="1.1"> <!-- Define star path --> <defs> <path d="M50,0 21,90 98,35 2,35 79,90z" id="star" /> </defs> <!-- Left: evenodd --> <clipPath id="emptyStar"> <use xl...
contentScriptType - SVG: Scalable Vector Graphics
This attribute sets the default scripting language used to process the value strings in event attributes. This language must be used for all instances of script that do not specify their own scripting language. The value specifies a media type, per MIME Part Two: Media Types [RFC2046]. ...
contentStyleType - SVG: Scalable Vector Graphics
This language is used for all instances of style that do not specify their own styling language, such as the style attribute that is available on many elements. The value specifies a media type, per MIME Part Two: Media Types [RFC2046]. Usage notes Value One of the content types specified in the Media Types Default value text/css Animatable No Since CSS is the only widely deployed style sheet language for online styling and it's already defined as default value if contentStyleType is ommitted, the attribute is not well supported in user agents. ...
cursor - SVG: Scalable Vector Graphics
Web › SVG › Attribute › cursor
as a property directly inside a CSS stylesheet, see css cursor for further information. Usage context Categories Presentation attribute Value [[<funciri>,]* [ auto | crosshair | default | pointer | move | e-resize | ne-resize | nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize| text | wait | help ]] | inherit Animatable Yes Normative document SVG 1.1 (2nd Edition) <FuncIRI> Functional notation for a reference. The syntax for this reference is the same as the css uri. Elements The following elements can use the cursor attribute Container elements >> Graphics elements >> Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please che...
end - SVG: Scalable Vector Graphics
Web › SVG › Attribute › end
<animateColor>, <animateMotion>, <animateTransform>, and <set> Usage notes Default value None Value <end-value-list> Animatable No The <end-value-list> is a semicolon-separated list of values. Each value can be one of the following: <offset-value> This value defines a clock-value that represents a point in time relative to the beginning of the SVG document (usually the load or DOMContentLoaded event). Negative values are valid. <syncbase-value> This value defines a syncbase and an optional offset from that syncbase. The element's animation end time is defined relative to the begin or active end of another animation. A valid syncbase-value consists of an ID reference to another animation element followed by a dot and either begin or end to identi...
id - SVG: Scalable Vector Graphics
Web › SVG › Attribute › id
> Specifies the element's ID. The ID must be unique within the node tree, must not be an empty string, and must not contain any whitespace characters. Note: You should avoid the use of id values that would be parsed as an SVG view specification (e.g., MyDrawing.svg#svgView(viewBox(0,200,1000,1000))) or a basic media fragment when used as a URL target fragment. It must be valid in XML documents. A stand-alone SVG document uses XML 1.0 syntax, which specifies that valid IDs only include designated characters (letters, digits, and a few punctuation marks), and do not start with a digit, a full stop (.) character, or a hyphen-minus (-) character. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'id' in that spec...
in - SVG: Scalable Vector Graphics
Web › SVG › Attribute › in
rceGraphic This keyword represents the graphics elements that were the original input into the <filter> element. SourceAlpha This keyword represents the graphics elements that were the original input into the <filter> element. SourceAlpha has all of the same rules as SourceGraphic except that only the alpha channel is used. BackgroundImage This keyword represents an image snapshot of the SVG document under the filter region at the time that the <filter> element was invoked. BackgroundAlpha Same as BackgroundImage except only the alpha channel is used. FillPaint This keyword represents the value of the fill property on the target element for the filter effect. In many cases, the FillPaint is opaque everywhere, but that might not be the case if a shape is painted with a gradient or pattern ...
overflow - SVG: Scalable Vector Graphics
viewport whether or not any of its content is clipped. Within SVG content, the value auto implies that all rendered content for child elements must be visible, either through a scrolling mechanism, or by rendering with no clip. Although the initial value for overflow is auto, it is overwritten in the User Agent style sheet for the <svg> element when it is not the root element of a stand-alone document, the <pattern> element, and the <marker> element to be hidden by default. Note: As a presentation attribute, overflow can be used as a CSS property. See the css opacity property for more information. As a presentation attribute, it can be applied to any element but it has effect only on the following eight elements: <foreignObject>, <iframe>, <image>, <marker>, <pattern>, <symbol>, <svg>, and <...
overline-position - SVG: Scalable Vector Graphics
The overline-position attribute represents the ideal vertical position of the overline. The overline position is expressed in the font's coordinate system. ...
overline-thickness - SVG: Scalable Vector Graphics
The overline-thickness attribute represents the ideal thickness of the overline. The overline thickness is expressed in the font's coordinate system. ...
pointer-events - SVG: Scalable Vector Graphics
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. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internetpointer-eve...
repeatCount - SVG: Scalable Vector Graphics
umber> | indefinite Default value None Animatable No <number> This value specifies the number of iterations. It can include partial iterations expressed as fraction values. A fractional value describes a portion of the simple duration. Values must be greater than 0. indefinite This value indicates that the animation will be repeated indefinitely (i.e. until the document ends). Specifications Specification Status Comment SVG Animations Level 2The definition of 'repeatCount' in that specification. Editor's Draft No change Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'repeatCount' in that specification. Recommendation Initial definition ...
repeatDur - SVG: Scalable Vector Graphics
"0" to="50" dur="1s" repeatDur="indefinite"/> </rect> </svg> Usage notes Value <clock-value> | indefinite Default values None Animatable No <clock-value> This value specifies the duration in presentation time to repeat the animation. indefinite This value indicates that the animation will be repeated indefinitely (i.e. until the document ends). Specifications Specification Status Comment SVG Animations Level 2The definition of 'repeatDur' in that specification. Editor's Draft No change Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'repeatDur' in that specification. Recommendation Initial definition ...
strikethrough-position - SVG: Scalable Vector Graphics
<< SVG Attribute reference home The strikethrough-position attribute represents the ideal vertical position of the strikethrough. ...
strikethrough-thickness - SVG: Scalable Vector Graphics
<< SVG Attribute reference home The strikethrough-thickness attribute represents the ideal thickness of the strikethrough. ...
transform - SVG: Scalable Vector Graphics
(1 0.5)"> <path id="heart" d="M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z" /> </g> <use xlink:href="#heart" fill="none" stroke="red"/> </svg> Note: As of SVG2, transform is a presentation attribute, meaning it can be used as a CSS property. However, be aware that there are some difference in syntax between the CSS property and the attribute. See the documentation for the CSS property transform for the specific syntax to use in that case. As a presentation attribute, transform can be used by any element (in SVG 1.1, only these 16 elements were allowed to use it: <a>, <circle>, <clipPath>, <defs>, <ellipse>, <foreignObject>, <g>, <image>, <line>, <path>, <polygon>, <polyline>, <rect>, <switch>, <text>, and <use>). Also, as a legacy from SVG 1.1, <lin...
underline-position - SVG: Scalable Vector Graphics
<< SVG Attribute reference home The underline-position attribute represents the ideal vertical position of the underline. ...
underline-thickness - SVG: Scalable Vector Graphics
<< SVG Attribute reference home The underline-thickness attribute represents the ideal thickness of the underline. ...
version - SVG: Scalable Vector Graphics
Web › SVG › Attribute › version
It is only allowed on the root <svg> element. It is purely advisory and has no influence on rendering or processing. While it is specified to accept any number, the only two valid choices are currently 1.0 and 1.1. ...
visibility - SVG: Scalable Vector Graphics
Recommen...
xlink:show - SVG: Scalable Vector Graphics
ew window or tab. This is similar to the effect achieved by an HTML <a> element with target set to _blank. replace This value specifies that the referenced resource is opened in the same window or tab. This is similar to the effect achieved by an HTML <a> element with target set to _self. embed This value specifies that instead of linking to the resource it will be loaded and shown within the document. This is similar to the effect achieved by an HTML <img> element. other This value indicates that other markup present in the link, i.e. the target attribute, determines its behavior. none This value specifies that there is no indication for how to refer to the linked resource. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 1.1 (Secon...
xml:base - SVG: Scalable Vector Graphics
All elements are using this attribute. Usage notes Value <iri> Default value None Animatable No <iri> This value specifies the base IRI of the element. ...
zoomAndPan - SVG: Scalable Vector Graphics
The zoomAndPan attribute specifies whether the SVG document can be magnified and panned. Magnification in this context means the effect of a supplemental scale and translate transformation on the outermost SVG document fragment. Panning represents a translation (i.e., a shift) transformation on an SVG document fragment in response to a user interface action. Two elements are using this attribute: <svg> and <view> html, body, svg { height: 100%; } <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" zoomAndPan="disable"> <filter id="diffuseLighting" x="0" y="0" width="100%" height="100%"> <feDiffuseLighting in="SourceGraphic" zoomAndPan="1"> <fePointLight x="60" y="60" z="20" /> </feDiffuseLighting> </filter> <rect x="0" y="0" width="200" height="200" style...
Content type - SVG: Scalable Vector Graphics
number or an SVGAnimatedInteger. IRI <IRI> An Internationalized Resource Identifier. On the Internet, resources are identified using IRIs (Internationalized Resource Identifiers). For example, an SVG file called someDrawing.svg located at http://example.com might have the following IRI: http://example.com/someDrawing.svg An IRI can also address a particular element within an XML document by including an IRI fragment identifier as part of the IRI. An IRI which includes an IRI fragment identifier consists of an optional base IRI, followed by a "#" character, followed by the IRI fragment identifier. For example, the following IRI can be used to specify the element whose ID is "Lamppost" within file someDrawing.svg: http://example.com/someDrawing.svg#Lamppost IRIs are used in th...
<a> - SVG: Scalable Vector Graphics
Web › SVG › Element › a
RL fragment that the hyperlink points to. May be required for backwards compatibility for older browsers. ...
<animate> - SVG: Scalable Vector Graphics
Web › SVG › Element › animate
Accessibility concerns Blinking and flashing animation can be problematic for people with cognitive concerns such as Attention Deficit Hyperactivity Disorder (ADHD). Additionally, certain kinds of motion can be a trigger for Vestibular disorders, epilepsy, and migraine and Scotopic sensitivity. Con...
<animateMotion> - SVG: Scalable Vector Graphics
Specifications Specification Status Comment SVG Animations Level 2The definition of '<animateMotion>' in that specification. Editor's Draft No change Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of '<animateMotion>' in that specif...
<desc> - SVG: Scalable Vector Graphics
Web › SVG › Element › desc
Candidate Recommendation Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of '<desc>' in tha...
<discard> - SVG: Scalable Vector Graphics
Web › SVG › Element › discard
The <discard> element may occur wherever the <animate> element may. ...
<image> - SVG: Scalable Vector Graphics
Web › SVG › Element › image
The <image> SVG element includes images inside SVG documents. It can display raster image files or other SVG files. The only image formats SVG software must support are JPEG, PNG, and other SVG files. Animated GIF behavior is undefined. SVG files displayed with <image> are treated as an image: external resources aren't loaded, :visited styles aren't applied, and they cannot be interactive. To include dynamic SVG elements, try <use> with an external URL. To include SVG files and run scripts inside them, try <object> inside of <foreignObject>. Note: The HTML spec defines <image> as a synonym for <img> while parsing HTML. This specific element and its behavior only apply inside SVG documents or inline SVG. Usage context CategoriesGraphics element, Graphics referencing elementPermitted content...
<linearGradient> - SVG: Scalable Vector Graphics
adient is drawn. Value type: <length> ; Default value: 0%; Animatable: yes y2 This attribute defines the y coordinate of the ending point of the vector gradient along which the linear gradient is drawn. ...
<radialGradient> - SVG: Scalable Vector Graphics
the shape containing the gradient. Value type: pad|reflect|repeat ; Default value: pad; Animatable: yes xlink:href An <IRI> reference to another <linearGradient> element that will be used as a template. ...
<set> - SVG: Scalable Vector Graphics
Web › SVG › Element › set
Editor's Draft Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition o...
<solidcolor> - SVG: Scalable Vector Graphics
It is also useful as away of animating a palette colors. Note: This is an experimental technology, and not yet implemented in browsers. A workaround is to use a <linearGradient> with only one color stop. This is less elegant, and unlike <solidcolor>, cannot itself be used in the definition of gradients. Usage context missing Attributes Global attributes Core attributes Global event attributes Presentation attributes Style attributes Specific attributes None. DOM interface This element implements the SVGSolidcolorElement interface. ...
<stop> - SVG: Scalable Vector Graphics
Web › SVG › Element › stop
a CSS property. Value type: currentcolor|<color>|<icccolor>; Default value: black; Animatable: yes stop-opacity This attribute defines the opacity of the gradient stop. It can be used as a CSS property. ...
<style> - SVG: Scalable Vector Graphics
Web › SVG › Element › style
s to which media the style applies. Value type: <string>; Default value: all; Animatable: no title This attribute the title of the style sheet which can be used to switch between alternate style sheets. Value type: <string>; Default value: none; Animatable: no Global attributes Core Attributes Most notably: id Styling Attributes class, style Event Attributes Global event attributes, Document element event attributes Usage notes CategoriesNonePermitted contentAny elements or character data Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of '<style>' in that specification. Candidate Recommendation Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of '<style>' in that specificatio...
<title> — the SVG accessible name element - SVG: Scalable Vector Graphics
Web › SVG › Element › title
Candidate Recommendation Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of '<title>' in t...
<use> - SVG: Scalable Vector Graphics
Web › SVG › Element › use
html,body,svg { height:100% } <svg viewBox="0 0 30 10" xmlns="http://www.w3.org/2000/svg"> <circle id="myCircle" cx="5" cy="5" r="4" stroke="blue"/> <use href="#myCircle" x="10" fill="blue"/> <use href="#myCircle" x="20" fill="white" stroke="red"/> <!-- stroke="red" will be ignored here, as stroke was already set on myCircle. Most attributes (except for x, y, width, height and (xlink:)href) do not override those set in the ancestor. That's why the circles have different x positions, but the same stroke value. ...
SVG element reference - SVG: Scalable Vector Graphics
Web › SVG › Element
<< SVG / SVG Attribute reference >> SVG drawings and images are created using a wide array of elements which are dedicated to the construction, drawing, and layout of vector images and diagrams. Here you'll find reference documentation for each of the SVG elements. SVG elements A to Z A <a> <animate> <animateMotion> <animateTransform> C <circle> <clipPath> <color-profile> D <defs> <desc> <discard> E <ellipse> F <feBlend> <feColorMatrix> <feComponentTransfer> <feComposite> <feConvolveMatrix> <feDiffuseLighting> <feDisplacementMap> <feDistantLight> <feDropShadow> <feFlood> <feFuncA> <feFuncB> <feFuncG> <feFuncR> <feGaussianBlur> <feImage> <feMerge> <feMergeNode> <feMorphology> <feOffset> <fePointLight> <feSpecularLighting> <feSpotLight>...
SVG as an Image - SVG: Scalable Vector Graphics
JavaScript is disabled. 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 the <iframe>, <object>, or <embed> elements. Specifications Specification Status Comment HTML5The definition of 'SVG within <img> element' in that specification. Recommendation Defines the usage of SVG within <img> elements. CSS Backgrounds and Borders Module Level 3The definition of 'SVG within 'background-image' CSS property' in that specificatio...
Basic shapes - SVG: Scalable Vector Graphics
reviousNext >> There are several basic shapes used for most SVG drawing. The purpose of these shapes is fairly obvious from their names. Some of the parameters that determine their position and size are given, but an element reference would probably contain more accurate and complete descriptions along with other properties that won't be covered in here. However, since they're used in most SVG documents, it's necessary to give them some sort of introduction. Basic shapes To insert a shape, you create an element in the document. Different elements correspond to different shapes and take different parameters to describe the size and position of those shapes. Some are slightly redundant in that they can be created by other shapes, but they're all there for your convenience and to keep your SVG d...
Basic Transformations - SVG: Scalable Vector Graphics
te system into a new coordinate system by {xnewCoordSys=axprevCoordSys+cyprevCoordSys+eynewCoordSys=bxprevCoordSys+dyprevCoordSys+f\left{ \begin{matrix} x_{\mathrm{prevCoordSys}} = a x_{\mathrm{newCoordSys}} + c y_{\mathrm{newCoordSys}} + e \\ y_{\mathrm{prevCoordSys}} = b x_{\mathrm{newCoordSys}} + d y_{\mathrm{newCoordSys}} + f \end{matrix} \right. See a concrete example on the SVG transform documentation. Detailed information about this property can be found in the SVG Recommendation. Effects on Coordinate Systems When using transformations you establish a new coordinate system inside the element the transformations apply to. That means, the units you specify for the element and its children might not follow the 1:1 pixel mapping, but are also distorted, skewed, translated and scaled accor...
Gradients in SVG - SVG: Scalable Vector Graphics
Gradient id="Gradient1"> <stop id="stop1" offset="0%"/> <stop id="stop2" offset="50%"/> <stop id="stop3" offset="100%"/> </linearGradient> <linearGradient id="Gradient2" x1="0" x2="0" y1="0" y2="1" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#Gradient1"/> I've included the xlink namespace here directly on the node, although usually you would define it at the top of your document. More on that when we talk about images. Radial Gradient Radial gradients are similar to linear ones but draw a gradient that radiates out from a point. To create one you add a <radialGradient> element to the definitions section of your document. Basic example <?xml version="1.0" standalone="no"?> <svg width="120" height="240" version="1.1" xmlns="http://www.w3.org/2000/svg"> <defs> <...
Introduction - SVG: Scalable Vector Graphics
offer benefits, some of which include having a DOM interface available for it, and not requiring third-party extensions. Whether or not to use it often depends on your specific use case. Basic ingredients HTML provides elements for defining headers, paragraphs, tables, and so on. In much the same way SVG provides elements for circles, rectangles, and 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 featu...
Other content in SVG - SVG: Scalable Vector Graphics
://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"> <image x="90" y="-65" width="128" height="146" transform="rotate(45)" xlink:href="https://developer.mozilla.org/static/img/favicon144.png"/> </svg> ScreenshotLive sample Embedding arbitrary XML Since SVG is an XML application, you can of course always embed arbitrary XML anywhere in an SVG document. But then you have no means to define how the surrounding SVG should react on the content. Actually, in a conforming viewer it will react in no way at all, the data will simply be omitted. Therefore the specification adds the <foreignObject> element to SVG. Its sole purpose is to be a container for other markup and a carrier for SVG styling attributes (most prominently width and height to define ...
Texts - SVG: Scalable Vector Graphics
Web › SVG › Tutorial › Texts
differentiate two almost completely separate topics. The one is the inclusion and display of text in an image, and the other are SVG fonts. The latter may be described in a later section of the tutorial, while we will focus completely on the first part: Bringing text into an SVG image. Basics We have seen in the introducing example, that the text element can be used to put arbitrary text in SVG documents: <text x="10" y="10">Hello World!</text> The x and y attributes determine, where in the viewport the text will appear. The attribute text-anchor, which can have the values "start", "middle", "end" or "inherit", decides in which direction the text flows from this point. The attribute dominant-baseline decides the vertical alignment. Like with the shape elements text can be colorized with the ...
SVG Tutorial - SVG: Scalable Vector Graphics
Web › SVG › Tutorial
Scalable Vector Graphics, SVG, is a W3C XML dialect to mark up graphics. It is partially implemented in Firefox, Opera, WebKit browsers, Internet Explorer and other browsers. This tutorial aims to explain the internals of SVG and is packed with technical details. If you just want to draw beautiful images, you might find more useful resources at Inkscape's documentation page. Another good introduction to SVG is provided by the W3C's SVG Primer. The tutorial is in an early stage of development. If you're able, please help out by chipping in and writing a paragraph or two. Extra points for writing a whole page! Introducing SVG from Scratch Introduction Getting Started Positions Basic Shapes Paths Fills and Strokes Gradients Patterns Texts Basic Transformations Clipping and mas...
Mixed content - Web security
they could determine which webpage the user is visiting. Passive content list This section lists all types of HTTP requests which are considered passive content: <img> (src attribute) <audio> (src attribute) <video> (src attribute) <object> subresources (when an <object> performs HTTP requests) Mixed active content Mixed active content is content that has access to all or parts of the Document Object Model of the HTTPS page. This type of mixed content can alter 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 con...
Features restricted to secure contexts - Web security
the web platform features available only in secure contexts -- see Secure Contexts for a definition and more details. Current features available only in secure contexts This section lists all the APIs available only in secure contexts, along with browser versions the limitation was introduced in, as appropriate. Note: Only the browsers that actually support secure contexts are listed in this document. See here for information on secure contexts support. API Chrome/Opera Edge Safari Firefox Async Clipboard API 66 Not supported Not supported 63 Background Sync (see SyncManager, for example) 49 Not supported Not supported Not supported Cache-Control: immutable Not supported 15 11 49 Credential Mana...
Types of attacks - Web security
POST endpoints should not interchangeably accept GET requests with parameters in the query string. A CSRF token ...
Web security
ons. Information leakage Referer header policy: privacy and security concerns There are privacy and security risks associated with the Referer HTTP header. This article describes them and offers advice on mitigating those risks. Robots.txt to be written Site maps to be written Integrity Same-origin policy The same-origin policy is a critical security mechanism that restricts how a document or script loaded from one origin can interact with a resource from another origin. It helps isolate potentially malicious documents, reducing possible attack vectors. Subresource integrity Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to...
Tutorials
or look up specific topics. Essential JavaScript Design Patterns An introduction to essential JavaScript design patterns. Advanced level JavaScript Guide A comprehensive, regularly updated guide to JavaScript for all levels of learning from beginner to advanced. You Don't Know JS A series of books diving deep into the core mechanisms of the JavaScript language. JavaScript Garden Documentation of the most quirky parts of JavaScript. Exploring ES6 Reliable and in-depth information on ECMAScript 2015. JavaScript Patterns A JavaScript pattern and antipattern collection that covers function patterns, jQuery patterns, jQuery plugin patterns, design patterns, general patterns, literals and constructor patterns, object creation patterns, code reuse patterns, DOM. How browsers ...
HTML Imports - Web Components
ML Imports in its current form. See this status update for more information. Until there is a consensus on the standard or alternative mechanisms are worked out, you can use a polyfill such as Google's webcomponents.js. HTML Imports is intended to be the packaging mechanism for web components, but you can also use HTML Imports by itself. You import an HTML file by using a <link> tag in an HTML document like this: <link rel="import" href="myfile.html"> The import link type is new. Specification Specification Status Comment HTML Imports Working Draft Initial definition. ...
following-sibling - XPath
...
preceding-sibling - XPath
...
preceding - XPath
Web › XPath › Axes › preceding
...
Comparison of CSS Selectors and XPath - XPath
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes This article seeks to document the difference between CSS Selectors and XPath for web developers to be able to better choose the right tool for the right job. XPath feature CSS equivalent ancestor, parent or preceding-sibling axis :has() selector attribute axis Attribute selectors child axis Child combinator descendant axis Descendant combinator following-sibling axis General sibling combinator or adjacent sibling combinator self axis :scope or :host selector ...
format-number - XPath
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The format-number function evaluates a number and returns a string representing the number in a given format. Syntax format-number(number ,pattern [,decimal-format] ) Arguments number The number to be formatted pattern A string in the format of the JDK 1.1 DecimalFormat class. (The documentation for JDK 1.1 is not available online. Here is the Java SE 6 DecimalFormat.) decimal-format (optional) The name of an xsl:decimal-format element that defines the number format to be used. If omitted, the default decimal-format will be used. Returns A string representing the number in the new format. Notes This function is an XSLT-specific addition to XPath. It is not a part of the core X...
generate-id - XPath
id for the first node in a given node-set and returns a string containing that id. Syntax generate-id( [node-set] ) Arguments node-set (optional) An id will be generated for the first node in this node-set. If omitted, the current context node will be used. Returns A string containing the generated id. Notes The same id must be generated every time for the same node in the current document in the current transformation. The generated id may not be the same in subsequent transformations. This function is an XSLT-specific addition to XPath. It is not a part of the core XPath function library. Defined XSLT 1.0 12.4 Gecko support Supported. ...
id - XPath
Web › XPath › Functions › id
is treated as an individual id. The returned node set is the nodes corresponding to those ids. If expression is a string, or anything other than a node-set, then expression is treated as a space-separated list of ids. The returned node set is the nodes corresponding to those ids. Returns A node-set containing the node or nodes identified by the given id or ids. Notes The DTD of the XML document determines what attribute is an ID. See XPath 1.0 5.2.1 Defined XPath 1.0 4.1 Gecko support Partially supported. ...
not - XPath
Web › XPath › Functions › not
function. Returns True for an expression that evaluates to false; false for an expression that evaluates to true. Notes This function should behave similarly to the boolean() function except that it returns the opposite value. You can test if an element doesn't have some attribute. <xsl:for-each match="//a[not(@name and @name = 'badname')]"> <!-- iterates over any <a> element in the document, that either has no 'name' attribute at all, or it has one, but its value is not "badname". --> </xsl:template> Defined XPath 1.0 4.3 Gecko support Supported. ...
position - XPath
context. Syntax position() Returns An integer equal to the context position from the expression evaluation context. Notes Note that a node's position in a context is not zero-based. The first node has a position of 1. The context is determined by the rest of the path. <xsl:template match="//a[position() = 5]"> <!-- this template matches the fifth a element anywhere in the document. --> </xsl:template> <xsl:template match="//div[@class='foo']/bar[position() = 1]"> <!-- this template matches the first bar element that is a child of a div element with a class attribute equal to "foo" --> </xsl:template> Defined XPath 1.0 4.1 Gecko support Supported. ...
system-property - XPath
roperty function returns an object representing the value of the system property identified by the name. If there is no such system property, the empty string should be returned. Returns An object representing the given system-property. Notes xsl:version, a number giving the version of XSLT implemented by the processor; for XSLT processors implementing the version of XSLT specified by this document, this is the number 1.0 xsl:vendor, a string identifying the vendor of the XSLT processor xsl:vendor-url, a string containing a URL identifying the vendor of the XSLT processor; typically this is the host page (home page) of the vendor's Web site. Defined XSLT 1.0 12.4 Gecko support Supported. ...
unparsed-entity-url - XPath
Syntax string unparsed-entity-url(string) Arguments The name of the unparsed entity. ...
Functions - XPath
of core XPath functions and XSLT-specific additions to XPath, including a description, syntax, a list of arguments, result-type, source in the appropriate W3C Recommendation, and degree of present Gecko support. For further information on using XPath/XSLT functions, please see the For Further Reading page. ...
Common XSLT Errors - XSLT: Extensible Stylesheet Language Transformations
n. Firefox only supports the official XSLT 1.0 version. Missing features There are some features in the XSLT 1.0 specification which Firefox unfortunately does not yet support. Specifically: The namespace:: axis in XPath expressions. Support for this will hopefully be available in the future. The disable-output-escaping attribute. This feature controls how serializing the constructed output document works. However Firefox never serializes the output document and so the attribute isn't really applicable. While we could try to add some heuristics to serialize and reparse just the part of the output document which has disable-output-escaping applied, heuristics often get things wrong and lead to surprising results, hence we've been reluctant to add this so far. Often times stylesheets contain c...
<xsl:attribute-set> - XSLT: Extensible Stylesheet Language Transformations
Syntax <xsl:attribute-set name=NAME use-attribute-sets=LIST-OF-NAMES> <xsl:attribute> </xsl:attribute-set> Required Attributes name Specifies the name of the attribute set. The name must be a valid QName. Optional Attributes use-attribute-sets Builds an attribute set from other attribute sets. ...
<xsl:attribute> - XSLT: Extensible Stylesheet Language Transformations
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The <xsl:attribute> element creates an attribute in the output document, using any values that can be accessed from the stylesheet. The element must be defined before any other output document element inside the output document element for which it establishes attribute values. But it may be after or inside elements that won't be part of the output (like <xsl:choose> or <xsl:apply-templates> etc.). Syntax <xsl:attribute name=NAME namespace=URI> TEMPLATE </xsl:attribute> Required Attributes name Specifies the name of the attribute to be created in the output document. The name must be a valid QName. Optional Attributes namespace Defines the namespace URI for this attribute in the output do...
<xsl:comment> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › comment
It must include only text. Syntax <xsl:comment> TEMPLATE </xsl:comment> Required Attributes None. ...
<xsl:copy-of> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › copy-of
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The <xsl:copy-of> element makes a deep copy (including descendant nodes) of whatever the select attribute specifies to the output document. Syntax <xsl:copy-of select=EXPRESSION /> Required Attributes select Uses an XPath expression that specifies what is to be copied. Optional Attributes None. Type Instruction, appears within a template. Defined XSLT, section 11.3. Gecko support Supported. ...
<xsl:copy> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › copy
It does not copy any children or attributes of the current node. Syntax <xsl:copy use-attribute-sets=LIST-OF-NAMES> TEMPLATE </xsl:copy> Required Attributes None. ...
<xsl:element> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › element
Syntax <xsl:element name=NAME namespace=URI use-attribute-sets=LIST-OF-NAMES > TEMPLATE </xsl:element> Required Attributes name Specifies the desired name of the output element. The name must be a valid QName. Optional Attributes namespace Specifies the namespace of the output element. use-attribute-sets A whitespace-separated list of attribute-set element names to be applied to the element element's output element. ...
<xsl:for-each> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › for-each
T/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The <xsl:for-each> element selects a set of nodes and processes each of them in the same way. It is often used to iterate through a set of nodes or to change the current node. If one or more <xsl:sort> elements appear as the children of this element, sorting occurs before processing. Otherwise, nodes are processed in document order. Syntax <xsl:for-each select=EXPRESSION> <xsl:sort> [optional] TEMPLATE </xsl:for-each> Required Attributes select Uses an XPath expression to select nodes to be processed. Optional Attributes None. Type Instruction, appears within a template. Defined XSLT, section 8. Gecko support Supported. ...
<xsl:number> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › number
bute, the processor counts how many preceding matching siblings it has, and adds one for the node itself. If no match is found, the sequence will be an empty list. any (Not supported at this time.) Numbers all matching nodes, regardless of level, sequentially. The ancestor, self, and preceding axes are all considered. The processor starts at the current node and proceeds in reverse document order, stopping if it reaches a match to any from attribute. If no match to the count attribute is found, the sequence will be an empty list. This level is not supported at this time. from Specifies where the numbering should start or start over. The sequence begins with the first descendant of the node that matches the from attribute. value Applies a given format to a number. This ...
<xsl:preserve-space> - XSLT: Extensible Stylesheet Language Transformations
If there is more than one element, separate the names with a whitespace character. Preserving whitespace is the default setting, so this element only needs to be used to counteract an <xsl:strip-space> element. Syntax <xsl:preserve-space elements=LIST-OF-ELEMENT-NAMES /> Required Attributes elements Specifies the elements for which whitespace should be preserved. ...
<xsl:processing-instruction> - XSLT: Extensible Stylesheet Language Transformations
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The <xsl:processing-instruction> element writes a processing instruction to the output document. Syntax <xsl:processing-instruction name=NAME> TEMPLATE </xsl:processing-instruction> Required Attributes name Specifies the name of this processing instruction. Optional Attributes None. Type Instruction, appears within a template. Defined XSLT, section 7.3 Gecko support Supported. ...
<xsl:strip-space> - XSLT: Extensible Stylesheet Language Transformations
Syntax <xsl:strip-space elements=LIST-OF-ELEMENT-NAMES /> Required Attributes elements Specifies a space-separated list of elements in the source whose whitespace-only text nodes should be removed. Optional Attributes None. ...
<xsl:variable> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › variable
lect=EXPRESSION > TEMPLATE </xsl:variable> Required Attributes name Gives the variable a name. Optional Attributes select Defines the value of the variable through an XPath expression. If the element contains a template, this attribute is ignored. Type Top-level or instruction. If it occurs as a top-level element, the variable is global in scope, and can be accessed throughout the document. If it occurs within a template, the variable is local in scope, accessible only within the template in which it appears. Defined XSLT, section 11. Gecko support Supported. ...
XSLT elements reference - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element
p-level element must appear as the child of either <xsl:stylesheet> or <xsl:transform>. An instruction, on the other hand, is associated with a template. A stylesheet may include several templates. A third type of element, not discussed here, is the literal result element (LRE). An LRE also appears in a template. It consists of any non-instruction element that should be copied as-is to the result document, for example, an <hr> element in an HTML conversion stylesheet. On a related note, any attribute in an LRE and some attributes of a limited number of XSLT elements can also include what is known as an attribute value template. An attribute value template is simply a string that includes an embedded XPath expression which is used to specify the value of an attribute. At run-time the expression is...
Interface List - XSLT: Extensible Stylesheet Language Transformations
...
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 ...
Compiling a New C/C++ Module to WebAssembly - WebAssembly
he same thing as before! Now we need to run our new myFunction() function from JavaScript. First of all, open up your hello3.html file in a text editor. Add a <button> element as shown below, just above the first opening <script type='text/javascript'> tag. <button class="mybutton">Run myFunction</button> Now add the following code at the end of the first <script> element: document.querySelector('.mybutton') .addEventListener('click', function() { alert('check console'); var result = Module.ccall( 'myFunction', // name of C function null, // return type null, // argument types null // arguments ); }); This illustrates how ccall() is used to call the exported function. ...
Understanding WebAssembly text format - WebAssembly
ry useful for allowing wasm modules to call JavaScript functions, DOM APIs, etc., and generally to pave the way for easier interoperability with the host environment. externref can be used for value types and table elements. A number of new instructions that allow wasm modules to directly manipulate WebAssembly tables, rather than having to do it via the JavaScript API. Note: The wasm-bindgen documentation contains some useful information on how to take advantage of externref from Rust. Multi-value WebAssembly Another more recent addition to the language (for example, in Firefox 78) is WebAssembly multi-value, meaning that WebAssembly functions can now return multiple values, and instruction sequences can consume and produce multiple stack values. At the time of writing (June 2020) this is...
Using the WebAssembly JavaScript API - WebAssembly
specified data type. So how do we use this? In the following example we define a global as a mutable i32 type, with a value of 0. The value of the global is then changed, first to 42 using the Global.value property, and then to 43 using the incGlobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value). ...
UDN Web Docs
In order to preverve documentation on XUL, this backup retains a snapshot of developer.mozilla.org from August, 2020. ...